| 1 |
//===--- FrontendActions.cpp ----------------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
// |
| 9 |
// Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/ |
| 10 |
// |
| 11 |
//===----------------------------------------------------------------------===// |
| 12 |
|
| 13 |
#include "flang/Frontend/FrontendActions.h" |
| 14 |
#include "flang/Common/default-kinds.h" |
| 15 |
#include "flang/Frontend/CompilerInstance.h" |
| 16 |
#include "flang/Frontend/CompilerInvocation.h" |
| 17 |
#include "flang/Frontend/FrontendOptions.h" |
| 18 |
#include "flang/Frontend/PreprocessorOptions.h" |
| 19 |
#include "flang/Lower/Bridge.h" |
| 20 |
#include "flang/Lower/PFTBuilder.h" |
| 21 |
#include "flang/Lower/Support/Verifier.h" |
| 22 |
#include "flang/Optimizer/Dialect/Support/FIRContext.h" |
| 23 |
#include "flang/Optimizer/Dialect/Support/KindMapping.h" |
| 24 |
#include "flang/Optimizer/Support/DataLayout.h" |
| 25 |
#include "flang/Optimizer/Support/InitFIR.h" |
| 26 |
#include "flang/Optimizer/Support/Utils.h" |
| 27 |
#include "flang/Optimizer/Transforms/Passes.h" |
| 28 |
#include "flang/Parser/dump-parse-tree.h" |
| 29 |
#include "flang/Parser/parsing.h" |
| 30 |
#include "flang/Parser/provenance.h" |
| 31 |
#include "flang/Parser/source.h" |
| 32 |
#include "flang/Parser/unparse.h" |
| 33 |
#include "flang/Semantics/runtime-type-info.h" |
| 34 |
#include "flang/Semantics/semantics.h" |
| 35 |
#include "flang/Semantics/unparse-with-symbols.h" |
| 36 |
#include "flang/Tools/CrossToolHelpers.h" |
| 37 |
|
| 38 |
#include "mlir/IR/Dialect.h" |
| 39 |
#include "mlir/Parser/Parser.h" |
| 40 |
#include "mlir/Pass/PassManager.h" |
| 41 |
#include "mlir/Support/LLVM.h" |
| 42 |
#include "mlir/Target/LLVMIR/Import.h" |
| 43 |
#include "mlir/Target/LLVMIR/ModuleTranslation.h" |
| 44 |
#include "clang/Basic/Diagnostic.h" |
| 45 |
#include "clang/Basic/DiagnosticFrontend.h" |
| 46 |
#include "clang/Basic/FileManager.h" |
| 47 |
#include "clang/Basic/FileSystemOptions.h" |
| 48 |
#include "clang/Driver/DriverDiagnostic.h" |
| 49 |
#include "llvm/ADT/SmallString.h" |
| 50 |
#include "llvm/ADT/StringRef.h" |
| 51 |
#include "llvm/Analysis/TargetLibraryInfo.h" |
| 52 |
#include "llvm/Analysis/TargetTransformInfo.h" |
| 53 |
#include "llvm/Bitcode/BitcodeWriterPass.h" |
| 54 |
#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" |
| 55 |
#include "llvm/IR/LLVMRemarkStreamer.h" |
| 56 |
#include "llvm/IR/LegacyPassManager.h" |
| 57 |
#include "llvm/IR/Verifier.h" |
| 58 |
#include "llvm/IRPrinter/IRPrintingPasses.h" |
| 59 |
#include "llvm/IRReader/IRReader.h" |
| 60 |
#include "llvm/Linker/Linker.h" |
| 61 |
#include "llvm/Object/OffloadBinary.h" |
| 62 |
#include "llvm/Passes/PassBuilder.h" |
| 63 |
#include "llvm/Passes/PassPlugin.h" |
| 64 |
#include "llvm/Passes/StandardInstrumentations.h" |
| 65 |
#include "llvm/Support/AMDGPUAddrSpace.h" |
| 66 |
#include "llvm/Support/Error.h" |
| 67 |
#include "llvm/Support/ErrorHandling.h" |
| 68 |
#include "llvm/Support/FileSystem.h" |
| 69 |
#include "llvm/Support/Path.h" |
| 70 |
#include "llvm/Support/SourceMgr.h" |
| 71 |
#include "llvm/Support/ToolOutputFile.h" |
| 72 |
#include "llvm/Target/TargetMachine.h" |
| 73 |
#include "llvm/TargetParser/RISCVISAInfo.h" |
| 74 |
#include "llvm/TargetParser/RISCVTargetParser.h" |
| 75 |
#include "llvm/Transforms/IPO/Internalize.h" |
| 76 |
#include "llvm/Transforms/Utils/ModuleUtils.h" |
| 77 |
#include <memory> |
| 78 |
#include <system_error> |
| 79 |
|
| 80 |
#include "flang/Tools/CLOptions.inc" |
| 81 |
|
| 82 |
using namespace Fortran::frontend; |
| 83 |
|
| 84 |
// Declare plugin extension function declarations. |
| 85 |
#define HANDLE_EXTENSION(Ext) \ |
| 86 |
llvm::PassPluginLibraryInfo get##Ext##PluginInfo(); |
| 87 |
#include "llvm/Support/Extension.def" |
| 88 |
|
| 89 |
/// Save the given \c mlirModule to a temporary .mlir file, in a location |
| 90 |
/// decided by the -save-temps flag. No files are produced if the flag is not |
| 91 |
/// specified. |
| 92 |
static bool saveMLIRTempFile(const CompilerInvocation &ci, |
| 93 |
mlir::ModuleOp mlirModule, |
| 94 |
llvm::StringRef inputFile, |
| 95 |
llvm::StringRef outputTag) { |
| 96 |
if (!ci.getCodeGenOpts().SaveTempsDir.has_value()) |
| 97 |
return true; |
| 98 |
|
| 99 |
const llvm::StringRef compilerOutFile = ci.getFrontendOpts().outputFile; |
| 100 |
const llvm::StringRef saveTempsDir = ci.getCodeGenOpts().SaveTempsDir.value(); |
| 101 |
auto dir = llvm::StringSwitch<llvm::StringRef>(saveTempsDir) |
| 102 |
.Case("cwd", "") |
| 103 |
.Case("obj", llvm::sys::path::parent_path(compilerOutFile)) |
| 104 |
.Default(saveTempsDir); |
| 105 |
|
| 106 |
// Build path from the compiler output file name, triple, cpu and OpenMP |
| 107 |
// information |
| 108 |
llvm::SmallString<256> path(dir); |
| 109 |
llvm::sys::path::append(path, llvm::sys::path::stem(inputFile) + "-" + |
| 110 |
outputTag + ".mlir"); |
| 111 |
|
| 112 |
std::error_code ec; |
| 113 |
llvm::ToolOutputFile out(path, ec, llvm::sys::fs::OF_Text); |
| 114 |
if (ec) |
| 115 |
return false; |
| 116 |
|
| 117 |
mlirModule->print(out.os()); |
| 118 |
out.os().close(); |
| 119 |
out.keep(); |
| 120 |
|
| 121 |
return true; |
| 122 |
} |
| 123 |
|
| 124 |
//===----------------------------------------------------------------------===// |
| 125 |
// Custom BeginSourceFileAction |
| 126 |
//===----------------------------------------------------------------------===// |
| 127 |
|
| 128 |
bool PrescanAction::beginSourceFileAction() { return runPrescan(); } |
| 129 |
|
| 130 |
bool PrescanAndParseAction::beginSourceFileAction() { |
| 131 |
return runPrescan() && runParse(/*emitMessages=*/true); |
| 132 |
} |
| 133 |
|
| 134 |
bool PrescanAndSemaAction::beginSourceFileAction() { |
| 135 |
return runPrescan() && runParse(/*emitMessages=*/false) && |
| 136 |
runSemanticChecks() && generateRtTypeTables(); |
| 137 |
} |
| 138 |
|
| 139 |
bool PrescanAndSemaDebugAction::beginSourceFileAction() { |
| 140 |
// This is a "debug" action for development purposes. To facilitate this, the |
| 141 |
// semantic checks are made to succeed unconditionally to prevent this action |
| 142 |
// from exiting early (i.e. in the presence of semantic errors). We should |
| 143 |
// never do this in actions intended for end-users or otherwise regular |
| 144 |
// compiler workflows! |
| 145 |
return runPrescan() && runParse(/*emitMessages=*/false) && |
| 146 |
(runSemanticChecks() || true) && (generateRtTypeTables() || true); |
| 147 |
} |
| 148 |
|
| 149 |
static void addDependentLibs(mlir::ModuleOp &mlirModule, CompilerInstance &ci) { |
| 150 |
const std::vector<std::string> &libs = |
| 151 |
ci.getInvocation().getCodeGenOpts().DependentLibs; |
| 152 |
if (libs.empty()) { |
| 153 |
return; |
| 154 |
} |
| 155 |
// dependent-lib is currently only supported on Windows, so the list should be |
| 156 |
// empty on non-Windows platforms |
| 157 |
assert( |
| 158 |
llvm::Triple(ci.getInvocation().getTargetOpts().triple).isOSWindows() && |
| 159 |
"--dependent-lib is only supported on Windows"); |
| 160 |
// Add linker options specified by --dependent-lib |
| 161 |
auto builder = mlir::OpBuilder(mlirModule.getRegion()); |
| 162 |
for (const std::string &lib : libs) { |
| 163 |
builder.create<mlir::LLVM::LinkerOptionsOp>( |
| 164 |
mlirModule.getLoc(), builder.getStrArrayAttr({"/DEFAULTLIB:" + lib})); |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
// Add to MLIR code target specific items which are dependent on target |
| 169 |
// configuration specified by the user. |
| 170 |
// Clang equivalent function: AMDGPUTargetCodeGenInfo::emitTargetGlobals |
| 171 |
static void addAMDGPUSpecificMLIRItems(mlir::ModuleOp &mlirModule, |
| 172 |
CompilerInstance &ci) { |
| 173 |
const TargetOptions &targetOpts = ci.getInvocation().getTargetOpts(); |
| 174 |
const llvm::Triple triple(targetOpts.triple); |
| 175 |
const llvm::StringRef codeObjectVersionGlobalOpName = "__oclc_ABI_version"; |
| 176 |
|
| 177 |
if (!triple.isAMDGPU()) { |
| 178 |
return; |
| 179 |
} |
| 180 |
const CodeGenOptions &codeGenOpts = ci.getInvocation().getCodeGenOpts(); |
| 181 |
if (codeGenOpts.CodeObjectVersion == llvm::CodeObjectVersionKind::COV_None) { |
| 182 |
return; |
| 183 |
} |
| 184 |
|
| 185 |
mlir::IRRewriter builder(mlirModule.getContext()); |
| 186 |
unsigned oclcABIVERsion = codeGenOpts.CodeObjectVersion; |
| 187 |
auto int32Type = builder.getI32Type(); |
| 188 |
|
| 189 |
std::optional<mlir::LLVM::GlobalOp> originalGV; |
| 190 |
|
| 191 |
mlirModule.walk([&originalGV, codeObjectVersionGlobalOpName]( |
| 192 |
mlir::LLVM::GlobalOp globalOp) { |
| 193 |
if (globalOp.getName() == codeObjectVersionGlobalOpName) |
| 194 |
originalGV = globalOp; |
| 195 |
}); |
| 196 |
if (originalGV.has_value()) { |
| 197 |
mlir::LLVM::GlobalOp originalGVOp = originalGV.value(); |
| 198 |
if (originalGVOp.getLinkage() != mlir::LLVM::Linkage::External) { |
| 199 |
return; |
| 200 |
} |
| 201 |
// Update the variable if it is already present in MLIR but it was marked |
| 202 |
// as external linkage variable |
| 203 |
originalGVOp.setLinkage(mlir::LLVM::Linkage::WeakODR); |
| 204 |
originalGVOp.setValueAttr( |
| 205 |
builder.getIntegerAttr(int32Type, oclcABIVERsion)); |
| 206 |
originalGVOp.setUnnamedAddr(mlir::LLVM::UnnamedAddr::Local); |
| 207 |
originalGVOp.setAddrSpace(llvm::AMDGPUAS::CONSTANT_ADDRESS); |
| 208 |
originalGVOp.setVisibility_(mlir::LLVM::Visibility::Hidden); |
| 209 |
return; |
| 210 |
} |
| 211 |
|
| 212 |
mlir::LLVM::GlobalOp covInfo = builder.create<mlir::LLVM::GlobalOp>( |
| 213 |
/* Location */ mlirModule.getLoc(), /* Type */ int32Type, |
| 214 |
/* IsConstant */ true, /* Linkage */ mlir::LLVM::Linkage::WeakODR, |
| 215 |
/* Name */ codeObjectVersionGlobalOpName, |
| 216 |
/* Value */ builder.getIntegerAttr(int32Type, oclcABIVERsion)); |
| 217 |
covInfo.setUnnamedAddr(mlir::LLVM::UnnamedAddr::Local); |
| 218 |
covInfo.setAddrSpace(llvm::AMDGPUAS::CONSTANT_ADDRESS); |
| 219 |
covInfo.setVisibility_(mlir::LLVM::Visibility::Hidden); |
| 220 |
builder.setInsertionPointToStart(mlirModule.getBody()); |
| 221 |
builder.insert(covInfo); |
| 222 |
} |
| 223 |
|
| 224 |
bool CodeGenAction::beginSourceFileAction() { |
| 225 |
llvmCtx = std::make_unique<llvm::LLVMContext>(); |
| 226 |
CompilerInstance &ci = this->getInstance(); |
| 227 |
|
| 228 |
// If the input is an LLVM file, just parse it and return. |
| 229 |
if (this->getCurrentInput().getKind().getLanguage() == Language::LLVM_IR) { |
| 230 |
llvm::SMDiagnostic err; |
| 231 |
llvmModule = llvm::parseIRFile(getCurrentInput().getFile(), err, *llvmCtx); |
| 232 |
if (!llvmModule || llvm::verifyModule(*llvmModule, &llvm::errs())) { |
| 233 |
err.print("flang-new", llvm::errs()); |
| 234 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 235 |
clang::DiagnosticsEngine::Error, "Could not parse IR"); |
| 236 |
ci.getDiagnostics().Report(diagID); |
| 237 |
return false; |
| 238 |
} |
| 239 |
|
| 240 |
return true; |
| 241 |
} |
| 242 |
|
| 243 |
// Load the MLIR dialects required by Flang |
| 244 |
mlir::DialectRegistry registry; |
| 245 |
mlirCtx = std::make_unique<mlir::MLIRContext>(registry); |
| 246 |
fir::support::registerNonCodegenDialects(registry); |
| 247 |
fir::support::loadNonCodegenDialects(*mlirCtx); |
| 248 |
fir::support::loadDialects(*mlirCtx); |
| 249 |
fir::support::registerLLVMTranslation(*mlirCtx); |
| 250 |
|
| 251 |
const llvm::TargetMachine &targetMachine = ci.getTargetMachine(); |
| 252 |
|
| 253 |
// If the input is an MLIR file, just parse it and return. |
| 254 |
if (this->getCurrentInput().getKind().getLanguage() == Language::MLIR) { |
| 255 |
llvm::SourceMgr sourceMgr; |
| 256 |
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr = |
| 257 |
llvm::MemoryBuffer::getFileOrSTDIN(getCurrentInput().getFile()); |
| 258 |
sourceMgr.AddNewSourceBuffer(std::move(*fileOrErr), llvm::SMLoc()); |
| 259 |
mlir::OwningOpRef<mlir::ModuleOp> module = |
| 260 |
mlir::parseSourceFile<mlir::ModuleOp>(sourceMgr, mlirCtx.get()); |
| 261 |
|
| 262 |
if (!module || mlir::failed(module->verifyInvariants())) { |
| 263 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 264 |
clang::DiagnosticsEngine::Error, "Could not parse FIR"); |
| 265 |
ci.getDiagnostics().Report(diagID); |
| 266 |
return false; |
| 267 |
} |
| 268 |
|
| 269 |
mlirModule = std::make_unique<mlir::ModuleOp>(module.release()); |
| 270 |
const llvm::DataLayout &dl = targetMachine.createDataLayout(); |
| 271 |
fir::support::setMLIRDataLayout(*mlirModule, dl); |
| 272 |
return true; |
| 273 |
} |
| 274 |
|
| 275 |
// Otherwise, generate an MLIR module from the input Fortran source |
| 276 |
if (getCurrentInput().getKind().getLanguage() != Language::Fortran) { |
| 277 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 278 |
clang::DiagnosticsEngine::Error, |
| 279 |
"Invalid input type - expecting a Fortran file"); |
| 280 |
ci.getDiagnostics().Report(diagID); |
| 281 |
return false; |
| 282 |
} |
| 283 |
bool res = runPrescan() && runParse(/*emitMessages=*/false) && |
| 284 |
runSemanticChecks() && generateRtTypeTables(); |
| 285 |
if (!res) |
| 286 |
return res; |
| 287 |
|
| 288 |
// Create a LoweringBridge |
| 289 |
const common::IntrinsicTypeDefaultKinds &defKinds = |
| 290 |
ci.getSemanticsContext().defaultKinds(); |
| 291 |
fir::KindMapping kindMap(mlirCtx.get(), llvm::ArrayRef<fir::KindTy>{ |
| 292 |
fir::fromDefaultKinds(defKinds)}); |
| 293 |
lower::LoweringBridge lb = Fortran::lower::LoweringBridge::create( |
| 294 |
*mlirCtx, ci.getSemanticsContext(), defKinds, |
| 295 |
ci.getSemanticsContext().intrinsics(), |
| 296 |
ci.getSemanticsContext().targetCharacteristics(), |
| 297 |
ci.getParsing().allCooked(), ci.getInvocation().getTargetOpts().triple, |
| 298 |
kindMap, ci.getInvocation().getLoweringOpts(), |
| 299 |
ci.getInvocation().getFrontendOpts().envDefaults, |
| 300 |
ci.getInvocation().getFrontendOpts().features, targetMachine, |
| 301 |
ci.getInvocation().getTargetOpts().cpuToTuneFor); |
| 302 |
|
| 303 |
// Fetch module from lb, so we can set |
| 304 |
mlirModule = std::make_unique<mlir::ModuleOp>(lb.getModule()); |
| 305 |
|
| 306 |
if (ci.getInvocation().getFrontendOpts().features.IsEnabled( |
| 307 |
Fortran::common::LanguageFeature::OpenMP)) { |
| 308 |
setOffloadModuleInterfaceAttributes(*mlirModule, |
| 309 |
ci.getInvocation().getLangOpts()); |
| 310 |
setOpenMPVersionAttribute(*mlirModule, |
| 311 |
ci.getInvocation().getLangOpts().OpenMPVersion); |
| 312 |
} |
| 313 |
|
| 314 |
// Create a parse tree and lower it to FIR |
| 315 |
Fortran::parser::Program &parseTree{*ci.getParsing().parseTree()}; |
| 316 |
lb.lower(parseTree, ci.getSemanticsContext()); |
| 317 |
|
| 318 |
// Add target specific items like dependent libraries, target specific |
| 319 |
// constants etc. |
| 320 |
addDependentLibs(*mlirModule, ci); |
| 321 |
addAMDGPUSpecificMLIRItems(*mlirModule, ci); |
| 322 |
|
| 323 |
// run the default passes. |
| 324 |
mlir::PassManager pm((*mlirModule)->getName(), |
| 325 |
mlir::OpPassManager::Nesting::Implicit); |
| 326 |
// Add OpenMP-related passes |
| 327 |
// WARNING: These passes must be run immediately after the lowering to ensure |
| 328 |
// that the FIR is correct with respect to OpenMP operations/attributes. |
| 329 |
if (ci.getInvocation().getFrontendOpts().features.IsEnabled( |
| 330 |
Fortran::common::LanguageFeature::OpenMP)) { |
| 331 |
bool isDevice = false; |
| 332 |
if (auto offloadMod = llvm::dyn_cast<mlir::omp::OffloadModuleInterface>( |
| 333 |
mlirModule->getOperation())) |
| 334 |
isDevice = offloadMod.getIsTargetDevice(); |
| 335 |
// WARNING: This pipeline must be run immediately after the lowering to |
| 336 |
// ensure that the FIR is correct with respect to OpenMP operations/ |
| 337 |
// attributes. |
| 338 |
fir::createOpenMPFIRPassPipeline(pm, isDevice); |
| 339 |
} |
| 340 |
|
| 341 |
pm.enableVerifier(/*verifyPasses=*/true); |
| 342 |
pm.addPass(std::make_unique<Fortran::lower::VerifierPass>()); |
| 343 |
|
| 344 |
if (mlir::failed(pm.run(*mlirModule))) { |
| 345 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 346 |
clang::DiagnosticsEngine::Error, |
| 347 |
"verification of lowering to FIR failed"); |
| 348 |
ci.getDiagnostics().Report(diagID); |
| 349 |
return false; |
| 350 |
} |
| 351 |
|
| 352 |
// Print initial full MLIR module, before lowering or transformations, if |
| 353 |
// -save-temps has been specified. |
| 354 |
if (!saveMLIRTempFile(ci.getInvocation(), *mlirModule, getCurrentFile(), |
| 355 |
"fir")) { |
| 356 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 357 |
clang::DiagnosticsEngine::Error, "Saving MLIR temp file failed"); |
| 358 |
ci.getDiagnostics().Report(diagID); |
| 359 |
return false; |
| 360 |
} |
| 361 |
|
| 362 |
return true; |
| 363 |
} |
| 364 |
|
| 365 |
//===----------------------------------------------------------------------===// |
| 366 |
// Custom ExecuteAction |
| 367 |
//===----------------------------------------------------------------------===// |
| 368 |
void InputOutputTestAction::executeAction() { |
| 369 |
CompilerInstance &ci = getInstance(); |
| 370 |
|
| 371 |
// Create a stream for errors |
| 372 |
std::string buf; |
| 373 |
llvm::raw_string_ostream errorStream{buf}; |
| 374 |
|
| 375 |
// Read the input file |
| 376 |
Fortran::parser::AllSources &allSources{ci.getAllSources()}; |
| 377 |
std::string path{getCurrentFileOrBufferName()}; |
| 378 |
const Fortran::parser::SourceFile *sf; |
| 379 |
if (path == "-") |
| 380 |
sf = allSources.ReadStandardInput(errorStream); |
| 381 |
else |
| 382 |
sf = allSources.Open(path, errorStream, std::optional<std::string>{"."s}); |
| 383 |
llvm::ArrayRef<char> fileContent = sf->content(); |
| 384 |
|
| 385 |
// Output file descriptor to receive the contents of the input file. |
| 386 |
std::unique_ptr<llvm::raw_ostream> os; |
| 387 |
|
| 388 |
// Copy the contents from the input file to the output file |
| 389 |
if (!ci.isOutputStreamNull()) { |
| 390 |
// An output stream (outputStream_) was set earlier |
| 391 |
ci.writeOutputStream(fileContent.data()); |
| 392 |
} else { |
| 393 |
// No pre-set output stream - create an output file |
| 394 |
os = ci.createDefaultOutputFile( |
| 395 |
/*binary=*/true, getCurrentFileOrBufferName(), "txt"); |
| 396 |
if (!os) |
| 397 |
return; |
| 398 |
(*os) << fileContent.data(); |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
void PrintPreprocessedAction::executeAction() { |
| 403 |
std::string buf; |
| 404 |
llvm::raw_string_ostream outForPP{buf}; |
| 405 |
|
| 406 |
// Format or dump the prescanner's output |
| 407 |
CompilerInstance &ci = this->getInstance(); |
| 408 |
if (ci.getInvocation().getPreprocessorOpts().showMacros) { |
| 409 |
ci.getParsing().EmitPreprocessorMacros(outForPP); |
| 410 |
} else if (ci.getInvocation().getPreprocessorOpts().noReformat) { |
| 411 |
ci.getParsing().DumpCookedChars(outForPP); |
| 412 |
} else { |
| 413 |
ci.getParsing().EmitPreprocessedSource( |
| 414 |
outForPP, !ci.getInvocation().getPreprocessorOpts().noLineDirectives); |
| 415 |
} |
| 416 |
|
| 417 |
// Print getDiagnostics from the prescanner |
| 418 |
ci.getParsing().messages().Emit(llvm::errs(), ci.getAllCookedSources()); |
| 419 |
|
| 420 |
// If a pre-defined output stream exists, dump the preprocessed content there |
| 421 |
if (!ci.isOutputStreamNull()) { |
| 422 |
// Send the output to the pre-defined output buffer. |
| 423 |
ci.writeOutputStream(outForPP.str()); |
| 424 |
return; |
| 425 |
} |
| 426 |
|
| 427 |
// Create a file and save the preprocessed output there |
| 428 |
std::unique_ptr<llvm::raw_pwrite_stream> os{ci.createDefaultOutputFile( |
| 429 |
/*Binary=*/true, /*InFile=*/getCurrentFileOrBufferName())}; |
| 430 |
if (!os) { |
| 431 |
return; |
| 432 |
} |
| 433 |
|
| 434 |
(*os) << outForPP.str(); |
| 435 |
} |
| 436 |
|
| 437 |
void DebugDumpProvenanceAction::executeAction() { |
| 438 |
this->getInstance().getParsing().DumpProvenance(llvm::outs()); |
| 439 |
} |
| 440 |
|
| 441 |
void ParseSyntaxOnlyAction::executeAction() {} |
| 442 |
|
| 443 |
void DebugUnparseNoSemaAction::executeAction() { |
| 444 |
auto &invoc = this->getInstance().getInvocation(); |
| 445 |
auto &parseTree{getInstance().getParsing().parseTree()}; |
| 446 |
|
| 447 |
// TODO: Options should come from CompilerInvocation |
| 448 |
Unparse(llvm::outs(), *parseTree, |
| 449 |
/*encoding=*/Fortran::parser::Encoding::UTF_8, |
| 450 |
/*capitalizeKeywords=*/true, /*backslashEscapes=*/false, |
| 451 |
/*preStatement=*/nullptr, |
| 452 |
invoc.getUseAnalyzedObjectsForUnparse() ? &invoc.getAsFortran() |
| 453 |
: nullptr); |
| 454 |
} |
| 455 |
|
| 456 |
void DebugUnparseAction::executeAction() { |
| 457 |
auto &invoc = this->getInstance().getInvocation(); |
| 458 |
auto &parseTree{getInstance().getParsing().parseTree()}; |
| 459 |
|
| 460 |
CompilerInstance &ci = this->getInstance(); |
| 461 |
auto os{ci.createDefaultOutputFile( |
| 462 |
/*Binary=*/false, /*InFile=*/getCurrentFileOrBufferName())}; |
| 463 |
|
| 464 |
// TODO: Options should come from CompilerInvocation |
| 465 |
Unparse(*os, *parseTree, |
| 466 |
/*encoding=*/Fortran::parser::Encoding::UTF_8, |
| 467 |
/*capitalizeKeywords=*/true, /*backslashEscapes=*/false, |
| 468 |
/*preStatement=*/nullptr, |
| 469 |
invoc.getUseAnalyzedObjectsForUnparse() ? &invoc.getAsFortran() |
| 470 |
: nullptr); |
| 471 |
|
| 472 |
// Report fatal semantic errors |
| 473 |
reportFatalSemanticErrors(); |
| 474 |
} |
| 475 |
|
| 476 |
void DebugUnparseWithSymbolsAction::executeAction() { |
| 477 |
auto &parseTree{*getInstance().getParsing().parseTree()}; |
| 478 |
|
| 479 |
Fortran::semantics::UnparseWithSymbols( |
| 480 |
llvm::outs(), parseTree, /*encoding=*/Fortran::parser::Encoding::UTF_8); |
| 481 |
|
| 482 |
// Report fatal semantic errors |
| 483 |
reportFatalSemanticErrors(); |
| 484 |
} |
| 485 |
|
| 486 |
void DebugUnparseWithModulesAction::executeAction() { |
| 487 |
auto &parseTree{*getInstance().getParsing().parseTree()}; |
| 488 |
CompilerInstance &ci{getInstance()}; |
| 489 |
Fortran::semantics::UnparseWithModules( |
| 490 |
llvm::outs(), ci.getSemantics().context(), parseTree, |
| 491 |
/*encoding=*/Fortran::parser::Encoding::UTF_8); |
| 492 |
reportFatalSemanticErrors(); |
| 493 |
} |
| 494 |
|
| 495 |
void DebugDumpSymbolsAction::executeAction() { |
| 496 |
CompilerInstance &ci = this->getInstance(); |
| 497 |
|
| 498 |
if (!ci.getRtTyTables().schemata) { |
| 499 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 500 |
clang::DiagnosticsEngine::Error, |
| 501 |
"could not find module file for __fortran_type_info"); |
| 502 |
ci.getDiagnostics().Report(diagID); |
| 503 |
llvm::errs() << "\n"; |
| 504 |
return; |
| 505 |
} |
| 506 |
|
| 507 |
// Dump symbols |
| 508 |
ci.getSemantics().DumpSymbols(llvm::outs()); |
| 509 |
} |
| 510 |
|
| 511 |
void DebugDumpAllAction::executeAction() { |
| 512 |
CompilerInstance &ci = this->getInstance(); |
| 513 |
|
| 514 |
// Dump parse tree |
| 515 |
auto &parseTree{getInstance().getParsing().parseTree()}; |
| 516 |
llvm::outs() << "========================"; |
| 517 |
llvm::outs() << " Flang: parse tree dump "; |
| 518 |
llvm::outs() << "========================\n"; |
| 519 |
Fortran::parser::DumpTree(llvm::outs(), parseTree, |
| 520 |
&ci.getInvocation().getAsFortran()); |
| 521 |
|
| 522 |
if (!ci.getRtTyTables().schemata) { |
| 523 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 524 |
clang::DiagnosticsEngine::Error, |
| 525 |
"could not find module file for __fortran_type_info"); |
| 526 |
ci.getDiagnostics().Report(diagID); |
| 527 |
llvm::errs() << "\n"; |
| 528 |
return; |
| 529 |
} |
| 530 |
|
| 531 |
// Dump symbols |
| 532 |
llvm::outs() << "====================="; |
| 533 |
llvm::outs() << " Flang: symbols dump "; |
| 534 |
llvm::outs() << "=====================\n"; |
| 535 |
ci.getSemantics().DumpSymbols(llvm::outs()); |
| 536 |
} |
| 537 |
|
| 538 |
void DebugDumpParseTreeNoSemaAction::executeAction() { |
| 539 |
auto &parseTree{getInstance().getParsing().parseTree()}; |
| 540 |
|
| 541 |
// Dump parse tree |
| 542 |
Fortran::parser::DumpTree( |
| 543 |
llvm::outs(), parseTree, |
| 544 |
&this->getInstance().getInvocation().getAsFortran()); |
| 545 |
} |
| 546 |
|
| 547 |
void DebugDumpParseTreeAction::executeAction() { |
| 548 |
auto &parseTree{getInstance().getParsing().parseTree()}; |
| 549 |
|
| 550 |
// Dump parse tree |
| 551 |
Fortran::parser::DumpTree( |
| 552 |
llvm::outs(), parseTree, |
| 553 |
&this->getInstance().getInvocation().getAsFortran()); |
| 554 |
|
| 555 |
// Report fatal semantic errors |
| 556 |
reportFatalSemanticErrors(); |
| 557 |
} |
| 558 |
|
| 559 |
void DebugMeasureParseTreeAction::executeAction() { |
| 560 |
CompilerInstance &ci = this->getInstance(); |
| 561 |
|
| 562 |
// Parse. In case of failure, report and return. |
| 563 |
ci.getParsing().Parse(llvm::outs()); |
| 564 |
|
| 565 |
if (!ci.getParsing().messages().empty() && |
| 566 |
(ci.getInvocation().getWarnAsErr() || |
| 567 |
ci.getParsing().messages().AnyFatalError())) { |
| 568 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 569 |
clang::DiagnosticsEngine::Error, "Could not parse %0"); |
| 570 |
ci.getDiagnostics().Report(diagID) << getCurrentFileOrBufferName(); |
| 571 |
|
| 572 |
ci.getParsing().messages().Emit(llvm::errs(), |
| 573 |
this->getInstance().getAllCookedSources()); |
| 574 |
return; |
| 575 |
} |
| 576 |
|
| 577 |
// Report the getDiagnostics from parsing |
| 578 |
ci.getParsing().messages().Emit(llvm::errs(), ci.getAllCookedSources()); |
| 579 |
|
| 580 |
auto &parseTree{*ci.getParsing().parseTree()}; |
| 581 |
|
| 582 |
// Measure the parse tree |
| 583 |
MeasurementVisitor visitor; |
| 584 |
Fortran::parser::Walk(parseTree, visitor); |
| 585 |
llvm::outs() << "Parse tree comprises " << visitor.objects |
| 586 |
<< " objects and occupies " << visitor.bytes |
| 587 |
<< " total bytes.\n"; |
| 588 |
} |
| 589 |
|
| 590 |
void DebugPreFIRTreeAction::executeAction() { |
| 591 |
CompilerInstance &ci = this->getInstance(); |
| 592 |
// Report and exit if fatal semantic errors are present |
| 593 |
if (reportFatalSemanticErrors()) { |
| 594 |
return; |
| 595 |
} |
| 596 |
|
| 597 |
auto &parseTree{*ci.getParsing().parseTree()}; |
| 598 |
|
| 599 |
// Dump pre-FIR tree |
| 600 |
if (auto ast{ |
| 601 |
Fortran::lower::createPFT(parseTree, ci.getSemanticsContext())}) { |
| 602 |
Fortran::lower::dumpPFT(llvm::outs(), *ast); |
| 603 |
} else { |
| 604 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 605 |
clang::DiagnosticsEngine::Error, "Pre FIR Tree is NULL."); |
| 606 |
ci.getDiagnostics().Report(diagID); |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
void DebugDumpParsingLogAction::executeAction() { |
| 611 |
CompilerInstance &ci = this->getInstance(); |
| 612 |
|
| 613 |
ci.getParsing().Parse(llvm::errs()); |
| 614 |
ci.getParsing().DumpParsingLog(llvm::outs()); |
| 615 |
} |
| 616 |
|
| 617 |
void GetDefinitionAction::executeAction() { |
| 618 |
CompilerInstance &ci = this->getInstance(); |
| 619 |
|
| 620 |
// Report and exit if fatal semantic errors are present |
| 621 |
if (reportFatalSemanticErrors()) { |
| 622 |
return; |
| 623 |
} |
| 624 |
|
| 625 |
parser::AllCookedSources &cs = ci.getAllCookedSources(); |
| 626 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 627 |
clang::DiagnosticsEngine::Error, "Symbol not found"); |
| 628 |
|
| 629 |
auto gdv = ci.getInvocation().getFrontendOpts().getDefVals; |
| 630 |
auto charBlock{cs.GetCharBlockFromLineAndColumns(gdv.line, gdv.startColumn, |
| 631 |
gdv.endColumn)}; |
| 632 |
if (!charBlock) { |
| 633 |
ci.getDiagnostics().Report(diagID); |
| 634 |
return; |
| 635 |
} |
| 636 |
|
| 637 |
llvm::outs() << "String range: >" << charBlock->ToString() << "<\n"; |
| 638 |
|
| 639 |
auto *symbol{ |
| 640 |
ci.getSemanticsContext().FindScope(*charBlock).FindSymbol(*charBlock)}; |
| 641 |
if (!symbol) { |
| 642 |
ci.getDiagnostics().Report(diagID); |
| 643 |
return; |
| 644 |
} |
| 645 |
|
| 646 |
llvm::outs() << "Found symbol name: " << symbol->name().ToString() << "\n"; |
| 647 |
|
| 648 |
auto sourceInfo{cs.GetSourcePositionRange(symbol->name())}; |
| 649 |
if (!sourceInfo) { |
| 650 |
llvm_unreachable( |
| 651 |
"Failed to obtain SourcePosition." |
| 652 |
"TODO: Please, write a test and replace this with a diagnostic!"); |
| 653 |
return; |
| 654 |
} |
| 655 |
|
| 656 |
llvm::outs() << "Found symbol name: " << symbol->name().ToString() << "\n"; |
| 657 |
llvm::outs() << symbol->name().ToString() << ": " << sourceInfo->first.path |
| 658 |
<< ", " << sourceInfo->first.line << ", " |
| 659 |
<< sourceInfo->first.column << "-" << sourceInfo->second.column |
| 660 |
<< "\n"; |
| 661 |
} |
| 662 |
|
| 663 |
void GetSymbolsSourcesAction::executeAction() { |
| 664 |
CompilerInstance &ci = this->getInstance(); |
| 665 |
|
| 666 |
// Report and exit if fatal semantic errors are present |
| 667 |
if (reportFatalSemanticErrors()) { |
| 668 |
return; |
| 669 |
} |
| 670 |
|
| 671 |
ci.getSemantics().DumpSymbolsSources(llvm::outs()); |
| 672 |
} |
| 673 |
|
| 674 |
//===----------------------------------------------------------------------===// |
| 675 |
// CodeGenActions |
| 676 |
//===----------------------------------------------------------------------===// |
| 677 |
|
| 678 |
CodeGenAction::~CodeGenAction() = default; |
| 679 |
|
| 680 |
static llvm::OptimizationLevel |
| 681 |
mapToLevel(const Fortran::frontend::CodeGenOptions &opts) { |
| 682 |
switch (opts.OptimizationLevel) { |
| 683 |
default: |
| 684 |
llvm_unreachable("Invalid optimization level!"); |
| 685 |
case 0: |
| 686 |
return llvm::OptimizationLevel::O0; |
| 687 |
case 1: |
| 688 |
return llvm::OptimizationLevel::O1; |
| 689 |
case 2: |
| 690 |
return llvm::OptimizationLevel::O2; |
| 691 |
case 3: |
| 692 |
return llvm::OptimizationLevel::O3; |
| 693 |
} |
| 694 |
} |
| 695 |
|
| 696 |
// Lower using HLFIR then run the FIR to HLFIR pipeline |
| 697 |
void CodeGenAction::lowerHLFIRToFIR() { |
| 698 |
assert(mlirModule && "The MLIR module has not been generated yet."); |
| 699 |
|
| 700 |
CompilerInstance &ci = this->getInstance(); |
| 701 |
auto opts = ci.getInvocation().getCodeGenOpts(); |
| 702 |
llvm::OptimizationLevel level = mapToLevel(opts); |
| 703 |
|
| 704 |
fir::support::loadDialects(*mlirCtx); |
| 705 |
|
| 706 |
// Set-up the MLIR pass manager |
| 707 |
mlir::PassManager pm((*mlirModule)->getName(), |
| 708 |
mlir::OpPassManager::Nesting::Implicit); |
| 709 |
|
| 710 |
pm.addPass(std::make_unique<Fortran::lower::VerifierPass>()); |
| 711 |
pm.enableVerifier(/*verifyPasses=*/true); |
| 712 |
|
| 713 |
// Create the pass pipeline |
| 714 |
fir::createHLFIRToFIRPassPipeline(pm, level); |
| 715 |
(void)mlir::applyPassManagerCLOptions(pm); |
| 716 |
|
| 717 |
if (!mlir::succeeded(pm.run(*mlirModule))) { |
| 718 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 719 |
clang::DiagnosticsEngine::Error, "Lowering to FIR failed"); |
| 720 |
ci.getDiagnostics().Report(diagID); |
| 721 |
} |
| 722 |
} |
| 723 |
|
| 724 |
static std::optional<std::pair<unsigned, unsigned>> |
| 725 |
getAArch64VScaleRange(CompilerInstance &ci) { |
| 726 |
const auto &langOpts = ci.getInvocation().getLangOpts(); |
| 727 |
|
| 728 |
if (langOpts.VScaleMin || langOpts.VScaleMax) |
| 729 |
return std::pair<unsigned, unsigned>( |
| 730 |
langOpts.VScaleMin ? langOpts.VScaleMin : 1, langOpts.VScaleMax); |
| 731 |
|
| 732 |
std::string featuresStr = ci.getTargetFeatures(); |
| 733 |
if (featuresStr.find("+sve") != std::string::npos) |
| 734 |
return std::pair<unsigned, unsigned>(1, 16); |
| 735 |
|
| 736 |
return std::nullopt; |
| 737 |
} |
| 738 |
|
| 739 |
static std::optional<std::pair<unsigned, unsigned>> |
| 740 |
getRISCVVScaleRange(CompilerInstance &ci) { |
| 741 |
const auto &langOpts = ci.getInvocation().getLangOpts(); |
| 742 |
const auto targetOpts = ci.getInvocation().getTargetOpts(); |
| 743 |
const llvm::Triple triple(targetOpts.triple); |
| 744 |
|
| 745 |
auto parseResult = llvm::RISCVISAInfo::parseFeatures( |
| 746 |
triple.isRISCV64() ? 64 : 32, targetOpts.featuresAsWritten); |
| 747 |
if (!parseResult) { |
| 748 |
std::string buffer; |
| 749 |
llvm::raw_string_ostream outputErrMsg(buffer); |
| 750 |
handleAllErrors(parseResult.takeError(), [&](llvm::StringError &errMsg) { |
| 751 |
outputErrMsg << errMsg.getMessage(); |
| 752 |
}); |
| 753 |
ci.getDiagnostics().Report(clang::diag::err_invalid_feature_combination) |
| 754 |
<< outputErrMsg.str(); |
| 755 |
return std::nullopt; |
| 756 |
} |
| 757 |
|
| 758 |
llvm::RISCVISAInfo *const isaInfo = parseResult->get(); |
| 759 |
|
| 760 |
// RISCV::RVVBitsPerBlock is 64. |
| 761 |
unsigned vscaleMin = isaInfo->getMinVLen() / llvm::RISCV::RVVBitsPerBlock; |
| 762 |
|
| 763 |
if (langOpts.VScaleMin || langOpts.VScaleMax) { |
| 764 |
// Treat Zvl*b as a lower bound on vscale. |
| 765 |
vscaleMin = std::max(vscaleMin, langOpts.VScaleMin); |
| 766 |
unsigned vscaleMax = langOpts.VScaleMax; |
| 767 |
if (vscaleMax != 0 && vscaleMax < vscaleMin) |
| 768 |
vscaleMax = vscaleMin; |
| 769 |
return std::pair<unsigned, unsigned>(vscaleMin ? vscaleMin : 1, vscaleMax); |
| 770 |
} |
| 771 |
|
| 772 |
if (vscaleMin > 0) { |
| 773 |
unsigned vscaleMax = isaInfo->getMaxVLen() / llvm::RISCV::RVVBitsPerBlock; |
| 774 |
return std::make_pair(vscaleMin, vscaleMax); |
| 775 |
} |
| 776 |
|
| 777 |
return std::nullopt; |
| 778 |
} |
| 779 |
|
| 780 |
// TODO: We should get this from TargetInfo. However, that depends on |
| 781 |
// too much of clang, so for now, replicate the functionality. |
| 782 |
static std::optional<std::pair<unsigned, unsigned>> |
| 783 |
getVScaleRange(CompilerInstance &ci) { |
| 784 |
const llvm::Triple triple(ci.getInvocation().getTargetOpts().triple); |
| 785 |
|
| 786 |
if (triple.isAArch64()) |
| 787 |
return getAArch64VScaleRange(ci); |
| 788 |
if (triple.isRISCV()) |
| 789 |
return getRISCVVScaleRange(ci); |
| 790 |
|
| 791 |
// All other architectures that don't support scalable vectors (i.e. don't |
| 792 |
// need vscale) |
| 793 |
return std::nullopt; |
| 794 |
} |
| 795 |
|
| 796 |
// Lower the previously generated MLIR module into an LLVM IR module |
| 797 |
void CodeGenAction::generateLLVMIR() { |
| 798 |
assert(mlirModule && "The MLIR module has not been generated yet."); |
| 799 |
|
| 800 |
CompilerInstance &ci = this->getInstance(); |
| 801 |
auto opts = ci.getInvocation().getCodeGenOpts(); |
| 802 |
auto mathOpts = ci.getInvocation().getLoweringOpts().getMathOptions(); |
| 803 |
llvm::OptimizationLevel level = mapToLevel(opts); |
| 804 |
|
| 805 |
fir::support::loadDialects(*mlirCtx); |
| 806 |
mlir::DialectRegistry registry; |
| 807 |
fir::support::registerNonCodegenDialects(registry); |
| 808 |
fir::support::addFIRExtensions(registry); |
| 809 |
mlirCtx->appendDialectRegistry(registry); |
| 810 |
fir::support::registerLLVMTranslation(*mlirCtx); |
| 811 |
|
| 812 |
// Set-up the MLIR pass manager |
| 813 |
mlir::PassManager pm((*mlirModule)->getName(), |
| 814 |
mlir::OpPassManager::Nesting::Implicit); |
| 815 |
|
| 816 |
pm.addPass(std::make_unique<Fortran::lower::VerifierPass>()); |
| 817 |
pm.enableVerifier(/*verifyPasses=*/true); |
| 818 |
|
| 819 |
MLIRToLLVMPassPipelineConfig config(level, opts, mathOpts); |
| 820 |
fir::registerDefaultInlinerPass(config); |
| 821 |
|
| 822 |
if (auto vsr = getVScaleRange(ci)) { |
| 823 |
config.VScaleMin = vsr->first; |
| 824 |
config.VScaleMax = vsr->second; |
| 825 |
} |
| 826 |
|
| 827 |
if (ci.getInvocation().getLoweringOpts().getNSWOnLoopVarInc()) |
| 828 |
config.NSWOnLoopVarInc = true; |
| 829 |
|
| 830 |
// Create the pass pipeline |
| 831 |
fir::createMLIRToLLVMPassPipeline(pm, config, getCurrentFile()); |
| 832 |
(void)mlir::applyPassManagerCLOptions(pm); |
| 833 |
|
| 834 |
// run the pass manager |
| 835 |
if (!mlir::succeeded(pm.run(*mlirModule))) { |
| 836 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 837 |
clang::DiagnosticsEngine::Error, "Lowering to LLVM IR failed"); |
| 838 |
ci.getDiagnostics().Report(diagID); |
| 839 |
} |
| 840 |
|
| 841 |
// Print final MLIR module, just before translation into LLVM IR, if |
| 842 |
// -save-temps has been specified. |
| 843 |
if (!saveMLIRTempFile(ci.getInvocation(), *mlirModule, getCurrentFile(), |
| 844 |
"llvmir")) { |
| 845 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 846 |
clang::DiagnosticsEngine::Error, "Saving MLIR temp file failed"); |
| 847 |
ci.getDiagnostics().Report(diagID); |
| 848 |
return; |
| 849 |
} |
| 850 |
|
| 851 |
// Translate to LLVM IR |
| 852 |
std::optional<llvm::StringRef> moduleName = mlirModule->getName(); |
| 853 |
llvmModule = mlir::translateModuleToLLVMIR( |
| 854 |
*mlirModule, *llvmCtx, moduleName ? *moduleName : "FIRModule"); |
| 855 |
|
| 856 |
if (!llvmModule) { |
| 857 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 858 |
clang::DiagnosticsEngine::Error, "failed to create the LLVM module"); |
| 859 |
ci.getDiagnostics().Report(diagID); |
| 860 |
return; |
| 861 |
} |
| 862 |
|
| 863 |
// Set PIC/PIE level LLVM module flags. |
| 864 |
if (opts.PICLevel > 0) { |
| 865 |
llvmModule->setPICLevel(static_cast<llvm::PICLevel::Level>(opts.PICLevel)); |
| 866 |
if (opts.IsPIE) |
| 867 |
llvmModule->setPIELevel( |
| 868 |
static_cast<llvm::PIELevel::Level>(opts.PICLevel)); |
| 869 |
} |
| 870 |
|
| 871 |
// Set mcmodel level LLVM module flags |
| 872 |
std::optional<llvm::CodeModel::Model> cm = getCodeModel(opts.CodeModel); |
| 873 |
if (cm.has_value()) { |
| 874 |
const llvm::Triple triple(ci.getInvocation().getTargetOpts().triple); |
| 875 |
llvmModule->setCodeModel(*cm); |
| 876 |
if ((cm == llvm::CodeModel::Medium || cm == llvm::CodeModel::Large) && |
| 877 |
triple.getArch() == llvm::Triple::x86_64) { |
| 878 |
llvmModule->setLargeDataThreshold(opts.LargeDataThreshold); |
| 879 |
} |
| 880 |
} |
| 881 |
} |
| 882 |
|
| 883 |
static std::unique_ptr<llvm::raw_pwrite_stream> |
| 884 |
getOutputStream(CompilerInstance &ci, llvm::StringRef inFile, |
| 885 |
BackendActionTy action) { |
| 886 |
switch (action) { |
| 887 |
case BackendActionTy::Backend_EmitAssembly: |
| 888 |
return ci.createDefaultOutputFile( |
| 889 |
/*Binary=*/false, inFile, /*extension=*/"s"); |
| 890 |
case BackendActionTy::Backend_EmitLL: |
| 891 |
return ci.createDefaultOutputFile( |
| 892 |
/*Binary=*/false, inFile, /*extension=*/"ll"); |
| 893 |
case BackendActionTy::Backend_EmitFIR: |
| 894 |
case BackendActionTy::Backend_EmitHLFIR: |
| 895 |
return ci.createDefaultOutputFile( |
| 896 |
/*Binary=*/false, inFile, /*extension=*/"mlir"); |
| 897 |
case BackendActionTy::Backend_EmitBC: |
| 898 |
return ci.createDefaultOutputFile( |
| 899 |
/*Binary=*/true, inFile, /*extension=*/"bc"); |
| 900 |
case BackendActionTy::Backend_EmitObj: |
| 901 |
return ci.createDefaultOutputFile( |
| 902 |
/*Binary=*/true, inFile, /*extension=*/"o"); |
| 903 |
} |
| 904 |
|
| 905 |
llvm_unreachable("Invalid action!"); |
| 906 |
} |
| 907 |
|
| 908 |
/// Generate target-specific machine-code or assembly file from the input LLVM |
| 909 |
/// module. |
| 910 |
/// |
| 911 |
/// \param [in] diags Diagnostics engine for reporting errors |
| 912 |
/// \param [in] tm Target machine to aid the code-gen pipeline set-up |
| 913 |
/// \param [in] act Backend act to run (assembly vs machine-code generation) |
| 914 |
/// \param [in] llvmModule LLVM module to lower to assembly/machine-code |
| 915 |
/// \param [in] codeGenOpts options configuring codegen pipeline |
| 916 |
/// \param [out] os Output stream to emit the generated code to |
| 917 |
static void generateMachineCodeOrAssemblyImpl(clang::DiagnosticsEngine &diags, |
| 918 |
llvm::TargetMachine &tm, |
| 919 |
BackendActionTy act, |
| 920 |
llvm::Module &llvmModule, |
| 921 |
const CodeGenOptions &codeGenOpts, |
| 922 |
llvm::raw_pwrite_stream &os) { |
| 923 |
assert(((act == BackendActionTy::Backend_EmitObj) || |
| 924 |
(act == BackendActionTy::Backend_EmitAssembly)) && |
| 925 |
"Unsupported action"); |
| 926 |
|
| 927 |
// Set-up the pass manager, i.e create an LLVM code-gen pass pipeline. |
| 928 |
// Currently only the legacy pass manager is supported. |
| 929 |
// TODO: Switch to the new PM once it's available in the backend. |
| 930 |
llvm::legacy::PassManager codeGenPasses; |
| 931 |
codeGenPasses.add( |
| 932 |
createTargetTransformInfoWrapperPass(tm.getTargetIRAnalysis())); |
| 933 |
|
| 934 |
llvm::Triple triple(llvmModule.getTargetTriple()); |
| 935 |
llvm::TargetLibraryInfoImpl *tlii = |
| 936 |
llvm::driver::createTLII(triple, codeGenOpts.getVecLib()); |
| 937 |
codeGenPasses.add(new llvm::TargetLibraryInfoWrapperPass(*tlii)); |
| 938 |
|
| 939 |
llvm::CodeGenFileType cgft = (act == BackendActionTy::Backend_EmitAssembly) |
| 940 |
? llvm::CodeGenFileType::AssemblyFile |
| 941 |
: llvm::CodeGenFileType::ObjectFile; |
| 942 |
if (tm.addPassesToEmitFile(codeGenPasses, os, nullptr, cgft)) { |
| 943 |
unsigned diagID = |
| 944 |
diags.getCustomDiagID(clang::DiagnosticsEngine::Error, |
| 945 |
"emission of this file type is not supported"); |
| 946 |
diags.Report(diagID); |
| 947 |
return; |
| 948 |
} |
| 949 |
|
| 950 |
// Run the passes |
| 951 |
codeGenPasses.run(llvmModule); |
| 952 |
} |
| 953 |
|
| 954 |
void CodeGenAction::runOptimizationPipeline(llvm::raw_pwrite_stream &os) { |
| 955 |
auto opts = getInstance().getInvocation().getCodeGenOpts(); |
| 956 |
auto &diags = getInstance().getDiagnostics(); |
| 957 |
llvm::OptimizationLevel level = mapToLevel(opts); |
| 958 |
|
| 959 |
llvm::TargetMachine *targetMachine = &getInstance().getTargetMachine(); |
| 960 |
// Create the analysis managers. |
| 961 |
llvm::LoopAnalysisManager lam; |
| 962 |
llvm::FunctionAnalysisManager fam; |
| 963 |
llvm::CGSCCAnalysisManager cgam; |
| 964 |
llvm::ModuleAnalysisManager mam; |
| 965 |
|
| 966 |
// Create the pass manager builder. |
| 967 |
llvm::PassInstrumentationCallbacks pic; |
| 968 |
llvm::PipelineTuningOptions pto; |
| 969 |
std::optional<llvm::PGOOptions> pgoOpt; |
| 970 |
llvm::StandardInstrumentations si(llvmModule->getContext(), |
| 971 |
opts.DebugPassManager); |
| 972 |
si.registerCallbacks(pic, &mam); |
| 973 |
llvm::PassBuilder pb(targetMachine, pto, pgoOpt, &pic); |
| 974 |
|
| 975 |
// Attempt to load pass plugins and register their callbacks with PB. |
| 976 |
for (auto &pluginFile : opts.LLVMPassPlugins) { |
| 977 |
auto passPlugin = llvm::PassPlugin::Load(pluginFile); |
| 978 |
if (passPlugin) { |
| 979 |
passPlugin->registerPassBuilderCallbacks(pb); |
| 980 |
} else { |
| 981 |
diags.Report(clang::diag::err_fe_unable_to_load_plugin) |
| 982 |
<< pluginFile << passPlugin.takeError(); |
| 983 |
} |
| 984 |
} |
| 985 |
// Register static plugin extensions. |
| 986 |
#define HANDLE_EXTENSION(Ext) \ |
| 987 |
get##Ext##PluginInfo().RegisterPassBuilderCallbacks(pb); |
| 988 |
#include "llvm/Support/Extension.def" |
| 989 |
|
| 990 |
// Register the target library analysis directly and give it a customized |
| 991 |
// preset TLI depending on -fveclib |
| 992 |
llvm::Triple triple(llvmModule->getTargetTriple()); |
| 993 |
llvm::TargetLibraryInfoImpl *tlii = |
| 994 |
llvm::driver::createTLII(triple, opts.getVecLib()); |
| 995 |
fam.registerPass([&] { return llvm::TargetLibraryAnalysis(*tlii); }); |
| 996 |
|
| 997 |
// Register all the basic analyses with the managers. |
| 998 |
pb.registerModuleAnalyses(mam); |
| 999 |
pb.registerCGSCCAnalyses(cgam); |
| 1000 |
pb.registerFunctionAnalyses(fam); |
| 1001 |
pb.registerLoopAnalyses(lam); |
| 1002 |
pb.crossRegisterProxies(lam, fam, cgam, mam); |
| 1003 |
|
| 1004 |
// Create the pass manager. |
| 1005 |
llvm::ModulePassManager mpm; |
| 1006 |
if (opts.PrepareForFullLTO) |
| 1007 |
mpm = pb.buildLTOPreLinkDefaultPipeline(level); |
| 1008 |
else if (opts.PrepareForThinLTO) |
| 1009 |
mpm = pb.buildThinLTOPreLinkDefaultPipeline(level); |
| 1010 |
else |
| 1011 |
mpm = pb.buildPerModuleDefaultPipeline(level); |
| 1012 |
|
| 1013 |
if (action == BackendActionTy::Backend_EmitBC) |
| 1014 |
mpm.addPass(llvm::BitcodeWriterPass(os)); |
| 1015 |
else if (action == BackendActionTy::Backend_EmitLL) |
| 1016 |
mpm.addPass(llvm::PrintModulePass(os)); |
| 1017 |
|
| 1018 |
// Run the passes. |
| 1019 |
mpm.run(*llvmModule, mam); |
| 1020 |
} |
| 1021 |
|
| 1022 |
// This class handles optimization remark messages requested if |
| 1023 |
// any of -Rpass, -Rpass-analysis or -Rpass-missed flags were provided |
| 1024 |
class BackendRemarkConsumer : public llvm::DiagnosticHandler { |
| 1025 |
|
| 1026 |
const CodeGenOptions &codeGenOpts; |
| 1027 |
clang::DiagnosticsEngine &diags; |
| 1028 |
|
| 1029 |
public: |
| 1030 |
BackendRemarkConsumer(clang::DiagnosticsEngine &diags, |
| 1031 |
const CodeGenOptions &codeGenOpts) |
| 1032 |
: codeGenOpts(codeGenOpts), diags(diags) {} |
| 1033 |
|
| 1034 |
bool isAnalysisRemarkEnabled(llvm::StringRef passName) const override { |
| 1035 |
return codeGenOpts.OptimizationRemarkAnalysis.patternMatches(passName); |
| 1036 |
} |
| 1037 |
bool isMissedOptRemarkEnabled(llvm::StringRef passName) const override { |
| 1038 |
return codeGenOpts.OptimizationRemarkMissed.patternMatches(passName); |
| 1039 |
} |
| 1040 |
bool isPassedOptRemarkEnabled(llvm::StringRef passName) const override { |
| 1041 |
return codeGenOpts.OptimizationRemark.patternMatches(passName); |
| 1042 |
} |
| 1043 |
|
| 1044 |
bool isAnyRemarkEnabled() const override { |
| 1045 |
return codeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() || |
| 1046 |
codeGenOpts.OptimizationRemarkMissed.hasValidPattern() || |
| 1047 |
codeGenOpts.OptimizationRemark.hasValidPattern(); |
| 1048 |
} |
| 1049 |
|
| 1050 |
void |
| 1051 |
emitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &diagInfo, |
| 1052 |
unsigned diagID) { |
| 1053 |
// We only support warnings and remarks. |
| 1054 |
assert(diagInfo.getSeverity() == llvm::DS_Remark || |
| 1055 |
diagInfo.getSeverity() == llvm::DS_Warning); |
| 1056 |
|
| 1057 |
std::string msg; |
| 1058 |
llvm::raw_string_ostream msgStream(msg); |
| 1059 |
|
| 1060 |
if (diagInfo.isLocationAvailable()) { |
| 1061 |
// Clang contains a SourceManager class which handles loading |
| 1062 |
// and caching of source files into memory and it can be used to |
| 1063 |
// query SourceLocation data. The SourceLocation data is what is |
| 1064 |
// needed here as it contains the full include stack which gives |
| 1065 |
// line and column number as well as file name and location. |
| 1066 |
// Since Flang doesn't have SourceManager, send file name and absolute |
| 1067 |
// path through msgStream, to use for printing. |
| 1068 |
msgStream << diagInfo.getLocationStr() << ";;" |
| 1069 |
<< diagInfo.getAbsolutePath() << ";;"; |
| 1070 |
} |
| 1071 |
|
| 1072 |
msgStream << diagInfo.getMsg(); |
| 1073 |
|
| 1074 |
// Emit message. |
| 1075 |
diags.Report(diagID) << clang::AddFlagValue(diagInfo.getPassName()) |
| 1076 |
<< msgStream.str(); |
| 1077 |
} |
| 1078 |
|
| 1079 |
void optimizationRemarkHandler( |
| 1080 |
const llvm::DiagnosticInfoOptimizationBase &diagInfo) { |
| 1081 |
auto passName = diagInfo.getPassName(); |
| 1082 |
if (diagInfo.isPassed()) { |
| 1083 |
if (codeGenOpts.OptimizationRemark.patternMatches(passName)) |
| 1084 |
// Optimization remarks are active only if the -Rpass flag has a regular |
| 1085 |
// expression that matches the name of the pass name in \p d. |
| 1086 |
emitOptimizationMessage( |
| 1087 |
diagInfo, clang::diag::remark_fe_backend_optimization_remark); |
| 1088 |
|
| 1089 |
return; |
| 1090 |
} |
| 1091 |
|
| 1092 |
if (diagInfo.isMissed()) { |
| 1093 |
if (codeGenOpts.OptimizationRemarkMissed.patternMatches(passName)) |
| 1094 |
// Missed optimization remarks are active only if the -Rpass-missed |
| 1095 |
// flag has a regular expression that matches the name of the pass |
| 1096 |
// name in \p d. |
| 1097 |
emitOptimizationMessage( |
| 1098 |
diagInfo, |
| 1099 |
clang::diag::remark_fe_backend_optimization_remark_missed); |
| 1100 |
|
| 1101 |
return; |
| 1102 |
} |
| 1103 |
|
| 1104 |
assert(diagInfo.isAnalysis() && "Unknown remark type"); |
| 1105 |
|
| 1106 |
bool shouldAlwaysPrint = false; |
| 1107 |
auto *ora = llvm::dyn_cast<llvm::OptimizationRemarkAnalysis>(&diagInfo); |
| 1108 |
if (ora) |
| 1109 |
shouldAlwaysPrint = ora->shouldAlwaysPrint(); |
| 1110 |
|
| 1111 |
if (shouldAlwaysPrint || |
| 1112 |
codeGenOpts.OptimizationRemarkAnalysis.patternMatches(passName)) |
| 1113 |
emitOptimizationMessage( |
| 1114 |
diagInfo, |
| 1115 |
clang::diag::remark_fe_backend_optimization_remark_analysis); |
| 1116 |
} |
| 1117 |
|
| 1118 |
bool handleDiagnostics(const llvm::DiagnosticInfo &di) override { |
| 1119 |
switch (di.getKind()) { |
| 1120 |
case llvm::DK_OptimizationRemark: |
| 1121 |
optimizationRemarkHandler(llvm::cast<llvm::OptimizationRemark>(di)); |
| 1122 |
break; |
| 1123 |
case llvm::DK_OptimizationRemarkMissed: |
| 1124 |
optimizationRemarkHandler(llvm::cast<llvm::OptimizationRemarkMissed>(di)); |
| 1125 |
break; |
| 1126 |
case llvm::DK_OptimizationRemarkAnalysis: |
| 1127 |
optimizationRemarkHandler( |
| 1128 |
llvm::cast<llvm::OptimizationRemarkAnalysis>(di)); |
| 1129 |
break; |
| 1130 |
case llvm::DK_MachineOptimizationRemark: |
| 1131 |
optimizationRemarkHandler( |
| 1132 |
llvm::cast<llvm::MachineOptimizationRemark>(di)); |
| 1133 |
break; |
| 1134 |
case llvm::DK_MachineOptimizationRemarkMissed: |
| 1135 |
optimizationRemarkHandler( |
| 1136 |
llvm::cast<llvm::MachineOptimizationRemarkMissed>(di)); |
| 1137 |
break; |
| 1138 |
case llvm::DK_MachineOptimizationRemarkAnalysis: |
| 1139 |
optimizationRemarkHandler( |
| 1140 |
llvm::cast<llvm::MachineOptimizationRemarkAnalysis>(di)); |
| 1141 |
break; |
| 1142 |
default: |
| 1143 |
break; |
| 1144 |
} |
| 1145 |
return true; |
| 1146 |
} |
| 1147 |
}; |
| 1148 |
|
| 1149 |
void CodeGenAction::embedOffloadObjects() { |
| 1150 |
CompilerInstance &ci = this->getInstance(); |
| 1151 |
const auto &cgOpts = ci.getInvocation().getCodeGenOpts(); |
| 1152 |
|
| 1153 |
for (llvm::StringRef offloadObject : cgOpts.OffloadObjects) { |
| 1154 |
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> objectOrErr = |
| 1155 |
llvm::MemoryBuffer::getFileOrSTDIN(offloadObject); |
| 1156 |
if (std::error_code ec = objectOrErr.getError()) { |
| 1157 |
auto diagID = ci.getDiagnostics().getCustomDiagID( |
| 1158 |
clang::DiagnosticsEngine::Error, "could not open '%0' for embedding"); |
| 1159 |
ci.getDiagnostics().Report(diagID) << offloadObject; |
| 1160 |
return; |
| 1161 |
} |
| 1162 |
llvm::embedBufferInModule( |
| 1163 |
*llvmModule, **objectOrErr, ".llvm.offloading", |
| 1164 |
llvm::Align(llvm::object::OffloadBinary::getAlignment())); |
| 1165 |
} |
| 1166 |
} |
| 1167 |
|
| 1168 |
void CodeGenAction::linkBuiltinBCLibs() { |
| 1169 |
auto options = clang::FileSystemOptions(); |
| 1170 |
clang::FileManager fileManager(options); |
| 1171 |
CompilerInstance &ci = this->getInstance(); |
| 1172 |
const auto &cgOpts = ci.getInvocation().getCodeGenOpts(); |
| 1173 |
|
| 1174 |
std::vector<std::unique_ptr<llvm::Module>> modules; |
| 1175 |
|
| 1176 |
// Load LLVM modules |
| 1177 |
for (llvm::StringRef bcLib : cgOpts.BuiltinBCLibs) { |
| 1178 |
auto BCBuf = fileManager.getBufferForFile(bcLib); |
| 1179 |
if (!BCBuf) { |
| 1180 |
auto diagID = ci.getDiagnostics().getCustomDiagID( |
| 1181 |
clang::DiagnosticsEngine::Error, "could not open '%0' for linking"); |
| 1182 |
ci.getDiagnostics().Report(diagID) << bcLib; |
| 1183 |
return; |
| 1184 |
} |
| 1185 |
|
| 1186 |
llvm::Expected<std::unique_ptr<llvm::Module>> ModuleOrErr = |
| 1187 |
getOwningLazyBitcodeModule(std::move(*BCBuf), *llvmCtx); |
| 1188 |
if (!ModuleOrErr) { |
| 1189 |
auto diagID = ci.getDiagnostics().getCustomDiagID( |
| 1190 |
clang::DiagnosticsEngine::Error, "error loading '%0' for linking"); |
| 1191 |
ci.getDiagnostics().Report(diagID) << bcLib; |
| 1192 |
return; |
| 1193 |
} |
| 1194 |
modules.push_back(std::move(ModuleOrErr.get())); |
| 1195 |
} |
| 1196 |
|
| 1197 |
// Link modules and internalize functions |
| 1198 |
for (auto &module : modules) { |
| 1199 |
bool Err; |
| 1200 |
Err = llvm::Linker::linkModules( |
| 1201 |
*llvmModule, std::move(module), llvm::Linker::Flags::LinkOnlyNeeded, |
| 1202 |
[](llvm::Module &M, const llvm::StringSet<> &GVS) { |
| 1203 |
llvm::internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) { |
| 1204 |
return !GV.hasName() || (GVS.count(GV.getName()) == 0); |
| 1205 |
}); |
| 1206 |
}); |
| 1207 |
if (Err) { |
| 1208 |
auto diagID = ci.getDiagnostics().getCustomDiagID( |
| 1209 |
clang::DiagnosticsEngine::Error, "link error when linking '%0'"); |
| 1210 |
ci.getDiagnostics().Report(diagID) << module->getSourceFileName(); |
| 1211 |
return; |
| 1212 |
} |
| 1213 |
} |
| 1214 |
} |
| 1215 |
|
| 1216 |
static void reportOptRecordError(llvm::Error e, clang::DiagnosticsEngine &diags, |
| 1217 |
const CodeGenOptions &codeGenOpts) { |
| 1218 |
handleAllErrors( |
| 1219 |
std::move(e), |
| 1220 |
[&](const llvm::LLVMRemarkSetupFileError &e) { |
| 1221 |
diags.Report(clang::diag::err_cannot_open_file) |
| 1222 |
<< codeGenOpts.OptRecordFile << e.message(); |
| 1223 |
}, |
| 1224 |
[&](const llvm::LLVMRemarkSetupPatternError &e) { |
| 1225 |
diags.Report(clang::diag::err_drv_optimization_remark_pattern) |
| 1226 |
<< e.message() << codeGenOpts.OptRecordPasses; |
| 1227 |
}, |
| 1228 |
[&](const llvm::LLVMRemarkSetupFormatError &e) { |
| 1229 |
diags.Report(clang::diag::err_drv_optimization_remark_format) |
| 1230 |
<< codeGenOpts.OptRecordFormat; |
| 1231 |
}); |
| 1232 |
} |
| 1233 |
|
| 1234 |
void CodeGenAction::executeAction() { |
| 1235 |
CompilerInstance &ci = this->getInstance(); |
| 1236 |
|
| 1237 |
clang::DiagnosticsEngine &diags = ci.getDiagnostics(); |
| 1238 |
const CodeGenOptions &codeGenOpts = ci.getInvocation().getCodeGenOpts(); |
| 1239 |
Fortran::lower::LoweringOptions &loweringOpts = |
| 1240 |
ci.getInvocation().getLoweringOpts(); |
| 1241 |
|
| 1242 |
// If the output stream is a file, generate it and define the corresponding |
| 1243 |
// output stream. If a pre-defined output stream is available, we will use |
| 1244 |
// that instead. |
| 1245 |
// |
| 1246 |
// NOTE: `os` is a smart pointer that will be destroyed at the end of this |
| 1247 |
// method. However, it won't be written to until `codeGenPasses` is |
| 1248 |
// destroyed. By defining `os` before `codeGenPasses`, we make sure that the |
| 1249 |
// output stream won't be destroyed before it is written to. This only |
| 1250 |
// applies when an output file is used (i.e. there is no pre-defined output |
| 1251 |
// stream). |
| 1252 |
// TODO: Revisit once the new PM is ready (i.e. when `codeGenPasses` is |
| 1253 |
// updated to use it). |
| 1254 |
std::unique_ptr<llvm::raw_pwrite_stream> os; |
| 1255 |
if (ci.isOutputStreamNull()) { |
| 1256 |
os = getOutputStream(ci, getCurrentFileOrBufferName(), action); |
| 1257 |
|
| 1258 |
if (!os) { |
| 1259 |
unsigned diagID = diags.getCustomDiagID( |
| 1260 |
clang::DiagnosticsEngine::Error, "failed to create the output file"); |
| 1261 |
diags.Report(diagID); |
| 1262 |
return; |
| 1263 |
} |
| 1264 |
} |
| 1265 |
|
| 1266 |
if (action == BackendActionTy::Backend_EmitFIR) { |
| 1267 |
if (loweringOpts.getLowerToHighLevelFIR()) { |
| 1268 |
lowerHLFIRToFIR(); |
| 1269 |
} |
| 1270 |
mlirModule->print(ci.isOutputStreamNull() ? *os : ci.getOutputStream()); |
| 1271 |
return; |
| 1272 |
} |
| 1273 |
|
| 1274 |
if (action == BackendActionTy::Backend_EmitHLFIR) { |
| 1275 |
assert(loweringOpts.getLowerToHighLevelFIR() && |
| 1276 |
"Lowering must have been configured to emit HLFIR"); |
| 1277 |
mlirModule->print(ci.isOutputStreamNull() ? *os : ci.getOutputStream()); |
| 1278 |
return; |
| 1279 |
} |
| 1280 |
|
| 1281 |
// Generate an LLVM module if it's not already present (it will already be |
| 1282 |
// present if the input file is an LLVM IR/BC file). |
| 1283 |
if (!llvmModule) |
| 1284 |
generateLLVMIR(); |
| 1285 |
|
| 1286 |
// If generating the LLVM module failed, abort! No need for further error |
| 1287 |
// reporting since generateLLVMIR() does this already. |
| 1288 |
if (!llvmModule) |
| 1289 |
return; |
| 1290 |
|
| 1291 |
// Set the triple based on the targetmachine (this comes compiler invocation |
| 1292 |
// and the command-line target option if specified, or the default if not |
| 1293 |
// given on the command-line). |
| 1294 |
llvm::TargetMachine &targetMachine = ci.getTargetMachine(); |
| 1295 |
|
| 1296 |
const std::string &theTriple = targetMachine.getTargetTriple().str(); |
| 1297 |
|
| 1298 |
if (llvmModule->getTargetTriple() != theTriple) { |
| 1299 |
diags.Report(clang::diag::warn_fe_override_module) << theTriple; |
| 1300 |
} |
| 1301 |
|
| 1302 |
// Always set the triple and data layout, to make sure they match and are set. |
| 1303 |
// Note that this overwrites any datalayout stored in the LLVM-IR. This avoids |
| 1304 |
// an assert for incompatible data layout when the code-generation happens. |
| 1305 |
llvmModule->setTargetTriple(theTriple); |
| 1306 |
llvmModule->setDataLayout(targetMachine.createDataLayout()); |
| 1307 |
|
| 1308 |
// Link in builtin bitcode libraries |
| 1309 |
if (!codeGenOpts.BuiltinBCLibs.empty()) |
| 1310 |
linkBuiltinBCLibs(); |
| 1311 |
|
| 1312 |
// Embed offload objects specified with -fembed-offload-object |
| 1313 |
if (!codeGenOpts.OffloadObjects.empty()) |
| 1314 |
embedOffloadObjects(); |
| 1315 |
|
| 1316 |
BackendRemarkConsumer remarkConsumer(diags, codeGenOpts); |
| 1317 |
|
| 1318 |
llvmModule->getContext().setDiagnosticHandler( |
| 1319 |
std::make_unique<BackendRemarkConsumer>(remarkConsumer)); |
| 1320 |
|
| 1321 |
// write optimization-record |
| 1322 |
llvm::Expected<std::unique_ptr<llvm::ToolOutputFile>> optRecordFileOrErr = |
| 1323 |
setupLLVMOptimizationRemarks( |
| 1324 |
llvmModule->getContext(), codeGenOpts.OptRecordFile, |
| 1325 |
codeGenOpts.OptRecordPasses, codeGenOpts.OptRecordFormat, |
| 1326 |
/*DiagnosticsWithHotness=*/false, |
| 1327 |
/*DiagnosticsHotnessThreshold=*/0); |
| 1328 |
|
| 1329 |
if (llvm::Error e = optRecordFileOrErr.takeError()) { |
| 1330 |
reportOptRecordError(std::move(e), diags, codeGenOpts); |
| 1331 |
return; |
| 1332 |
} |
| 1333 |
|
| 1334 |
std::unique_ptr<llvm::ToolOutputFile> optRecordFile = |
| 1335 |
std::move(*optRecordFileOrErr); |
| 1336 |
|
| 1337 |
if (optRecordFile) { |
| 1338 |
optRecordFile->keep(); |
| 1339 |
optRecordFile->os().flush(); |
| 1340 |
} |
| 1341 |
|
| 1342 |
// Run LLVM's middle-end (i.e. the optimizer). |
| 1343 |
runOptimizationPipeline(ci.isOutputStreamNull() ? *os : ci.getOutputStream()); |
| 1344 |
|
| 1345 |
if (action == BackendActionTy::Backend_EmitLL || |
| 1346 |
action == BackendActionTy::Backend_EmitBC) { |
| 1347 |
// This action has effectively been completed in runOptimizationPipeline. |
| 1348 |
return; |
| 1349 |
} |
| 1350 |
|
| 1351 |
// Run LLVM's backend and generate either assembly or machine code |
| 1352 |
if (action == BackendActionTy::Backend_EmitAssembly || |
| 1353 |
action == BackendActionTy::Backend_EmitObj) { |
| 1354 |
generateMachineCodeOrAssemblyImpl( |
| 1355 |
diags, targetMachine, action, *llvmModule, codeGenOpts, |
| 1356 |
ci.isOutputStreamNull() ? *os : ci.getOutputStream()); |
| 1357 |
return; |
| 1358 |
} |
| 1359 |
} |
| 1360 |
|
| 1361 |
void InitOnlyAction::executeAction() { |
| 1362 |
CompilerInstance &ci = this->getInstance(); |
| 1363 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 1364 |
clang::DiagnosticsEngine::Warning, |
| 1365 |
"Use `-init-only` for testing purposes only"); |
| 1366 |
ci.getDiagnostics().Report(diagID); |
| 1367 |
} |
| 1368 |
|
| 1369 |
void PluginParseTreeAction::executeAction() {} |
| 1370 |
|
| 1371 |
void DebugDumpPFTAction::executeAction() { |
| 1372 |
CompilerInstance &ci = this->getInstance(); |
| 1373 |
|
| 1374 |
if (auto ast = Fortran::lower::createPFT(*ci.getParsing().parseTree(), |
| 1375 |
ci.getSemantics().context())) { |
| 1376 |
Fortran::lower::dumpPFT(llvm::outs(), *ast); |
| 1377 |
return; |
| 1378 |
} |
| 1379 |
|
| 1380 |
unsigned diagID = ci.getDiagnostics().getCustomDiagID( |
| 1381 |
clang::DiagnosticsEngine::Error, "Pre FIR Tree is NULL."); |
| 1382 |
ci.getDiagnostics().Report(diagID); |
| 1383 |
} |
| 1384 |
|
| 1385 |
Fortran::parser::Parsing &PluginParseTreeAction::getParsing() { |
| 1386 |
return getInstance().getParsing(); |
| 1387 |
} |
| 1388 |
|
| 1389 |
std::unique_ptr<llvm::raw_pwrite_stream> |
| 1390 |
PluginParseTreeAction::createOutputFile(llvm::StringRef extension = "") { |
| 1391 |
|
| 1392 |
std::unique_ptr<llvm::raw_pwrite_stream> os{ |
| 1393 |
getInstance().createDefaultOutputFile( |
| 1394 |
/*Binary=*/false, /*InFile=*/getCurrentFileOrBufferName(), |
| 1395 |
extension)}; |
| 1396 |
return os; |
| 1397 |
} |