clang 24.0.0git
CIRGenAction.cpp
Go to the documentation of this file.
1//===--- CIRGenAction.cpp - LLVM Code generation Frontend Action ---------===//
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
10#include "mlir/IR/MLIRContext.h"
11#include "mlir/IR/OwningOpRef.h"
19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/StringSet.h"
22#include "llvm/IR/DiagnosticHandler.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Linker/Linker.h"
28#include "llvm/Support/Path.h"
29#include "llvm/Support/raw_ostream.h"
30#include "llvm/Transforms/IPO/Internalize.h"
31
32using namespace cir;
33using namespace clang;
34
35namespace cir {
36
37static BackendAction
39 switch (Action) {
41 assert(false &&
42 "Unsupported output type for getBackendActionFromOutputType!");
43 break; // Unreachable, but fall through to report that
52 }
53 // We should only get here if a non-enum value is passed in or we went through
54 // the assert(false) case above
55 llvm_unreachable("Unsupported output type!");
56}
57
58static std::unique_ptr<llvm::Module>
59lowerFromCIRToLLVMIR(mlir::ModuleOp MLIRModule, llvm::LLVMContext &LLVMCtx,
60 bool EnableOpenMP,
61 llvm::StringRef mlirSaveTempsOutFile = {},
62 llvm::vfs::FileSystem *fs = nullptr) {
63 return direct::lowerDirectlyFromCIRToLLVMIR(MLIRModule, LLVMCtx, EnableOpenMP,
64 mlirSaveTempsOutFile, fs);
65}
66
68
69 virtual void anchor();
70
72
74
75 std::unique_ptr<raw_pwrite_stream> OutputStream;
76
77 ASTContext *Context{nullptr};
79 std::unique_ptr<CIRGenerator> Gen;
80 const FrontendOptions &FEOptions;
81 CodeGenOptions &CGO;
82
83 llvm::LLVMContext &LLVMCtx;
85
86public:
88 CodeGenOptions &CGO, std::unique_ptr<raw_pwrite_stream> OS,
89 llvm::LLVMContext &LLVMCtx,
91 : Action(Action), CI(CI), OutputStream(std::move(OS)),
92 FS(&CI.getVirtualFileSystem()),
93 Gen(std::make_unique<CIRGenerator>(CI.getDiagnostics(), std::move(FS),
94 CI.getCodeGenOpts())),
95 FEOptions(CI.getFrontendOpts()), CGO(CGO), LLVMCtx(LLVMCtx),
96 LinkModules(LinkModules) {}
97
98 void Initialize(ASTContext &Ctx) override {
99 assert(!Context && "initialized multiple times");
100 Context = &Ctx;
101 Gen->Initialize(Ctx);
102 }
103
105 Gen->HandleTopLevelDecl(D);
106 return true;
107 }
108
110 Gen->HandleCXXStaticMemberVarInstantiation(VD);
111 }
112
114 const OpenACCRoutineDecl *RD) override {
115 Gen->HandleOpenACCRoutineReference(FD, RD);
116 }
117
119 Gen->HandleInlineFunctionDefinition(D);
120 }
121
123 Gen->HandleTranslationUnit(C);
124
125 if (!FEOptions.ClangIRDisableCIRVerifier) {
126 if (!Gen->verifyModule()) {
127 CI.getDiagnostics().Report(
128 diag::err_cir_verification_failed_pre_passes);
129 llvm::report_fatal_error(
130 "CIR codegen: module verification error before running CIR passes");
131 return;
132 }
133 }
134
135 mlir::ModuleOp MlirModule = Gen->getModule();
136 mlir::MLIRContext &MlirCtx = Gen->getMLIRContext();
137
138 if (!FEOptions.ClangIRDisablePasses) {
139 std::string LibOptOptions = FEOptions.ClangIRLibOptOptions;
140
141 // Setup and run CIR pipeline.
142 const bool EnableLibOpt =
143 FEOptions.ClangIRLibOptEnabled && (CGO.OptimizationLevel > 0);
145 MlirModule, MlirCtx, C, !FEOptions.ClangIRDisableCIRVerifier,
146 FEOptions.ClangIREnableIdiomRecognizer, CGO.OptimizationLevel > 0,
147 EnableLibOpt, LibOptOptions,
148 FEOptions.ClangIREnableCallConvLowering)
149 .failed()) {
150 CI.getDiagnostics().Report(diag::err_cir_to_cir_transform_failed);
151 return;
152 }
153 }
154
155 switch (Action) {
157 if (OutputStream && MlirModule) {
158 mlir::OpPrintingFlags Flags;
159 Flags.enableDebugInfo(/*enable=*/true, /*prettyForm=*/false);
160 MlirModule->print(*OutputStream, Flags);
161 }
162 break;
167 StringRef saveTempsPrefix = CGO.SaveTempsFilePrefix;
168 std::string cirSaveTempsOutFile, mlirSaveTempsOutFile;
169 if (!saveTempsPrefix.empty()) {
170 SmallString<128> stem(saveTempsPrefix);
171 llvm::sys::path::replace_extension(stem, "cir");
172 cirSaveTempsOutFile = std::string(stem);
173 llvm::sys::path::replace_extension(stem, "mlir");
174 mlirSaveTempsOutFile = std::string(stem);
175 }
176
177 if (!cirSaveTempsOutFile.empty()) {
178 std::error_code ec;
179 llvm::raw_fd_ostream out(cirSaveTempsOutFile, ec);
180 if (!ec)
181 MlirModule->print(out);
182 }
183
184 std::unique_ptr<llvm::Module> LLVMModule = lowerFromCIRToLLVMIR(
185 MlirModule, LLVMCtx, C.getLangOpts().OpenMP, mlirSaveTempsOutFile,
186 &CI.getVirtualFileSystem());
187
188 if (linkInModules(*LLVMModule))
189 return;
190
193 CI, CI.getCodeGenOpts(), C.getTargetInfo().getDataLayoutString(),
194 LLVMModule.get(), BEAction, FS, std::move(OutputStream));
195 break;
196 }
197 }
198 }
199
200 // TODO: share with BackendConsumer::LinkInModules once OG's CurLinkModule
201 // diagnostic-handler indirection is abstracted behind a callback for CIR.
202 bool linkInModules(llvm::Module &M) {
203 for (auto &LM : LinkModules) {
204 assert(LM.Module && "LinkModule does not actually have a module");
205
206 if (LM.PropagateAttrs)
207 for (llvm::Function &F : *LM.Module) {
208 if (F.isIntrinsic())
209 continue;
211 F, CGO, CI.getLangOpts(), CI.getTargetOpts(), LM.Internalize);
212 }
213
214 bool Err;
215 if (LM.Internalize) {
216 Err = llvm::Linker::linkModules(
217 M, std::move(LM.Module), LM.LinkFlags,
218 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
219 llvm::internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
220 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
221 });
222 });
223 } else {
224 Err = llvm::Linker::linkModules(M, std::move(LM.Module), LM.LinkFlags);
225 }
226
227 if (Err)
228 return true;
229 }
230
231 LinkModules.clear();
232 return false;
233 }
234
237 Context->getSourceManager(),
238 "CIR generation of declaration");
239 Gen->HandleTagDeclDefinition(D);
240 }
241
242 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
243 Gen->HandleTagDeclRequiredDefinition(D);
244 }
245
247 Gen->CompleteTentativeDefinition(D);
248 }
249
250 void HandleVTable(CXXRecordDecl *RD) override { Gen->HandleVTable(RD); }
251};
252} // namespace cir
253
254void CIRGenConsumer::anchor() {}
255
256CIRGenAction::CIRGenAction(OutputType Act, mlir::MLIRContext *MLIRCtx)
257 : MLIRCtx(MLIRCtx ? MLIRCtx : new mlir::MLIRContext),
258 Ctx(std::make_unique<llvm::LLVMContext>()), Action(Act) {}
259
260CIRGenAction::~CIRGenAction() { MLIRMod.release(); }
261
263 if (clang::loadLinkModules(CI, *Ctx, LinkModules))
264 return false;
266}
267
268static std::unique_ptr<raw_pwrite_stream>
269getOutputStream(CompilerInstance &CI, StringRef InFile,
271 switch (Action) {
273 return CI.createDefaultOutputFile(false, InFile, "s");
275 return CI.createDefaultOutputFile(false, InFile, "cir");
277 return CI.createDefaultOutputFile(false, InFile, "ll");
279 return CI.createDefaultOutputFile(true, InFile, "bc");
281 return CI.createDefaultOutputFile(true, InFile, "o");
282 }
283 llvm_unreachable("Invalid CIRGenAction::OutputType");
284}
285
286std::unique_ptr<ASTConsumer>
288 std::unique_ptr<llvm::raw_pwrite_stream> Out = CI.takeOutputStream();
289
290 if (!Out)
291 Out = getOutputStream(CI, InFile, Action);
292
293 auto Result = std::make_unique<cir::CIRGenConsumer>(
294 Action, CI, CI.getCodeGenOpts(), std::move(Out), *Ctx, LinkModules);
295
296 return Result;
297}
298
299void EmitAssemblyAction::anchor() {}
300EmitAssemblyAction::EmitAssemblyAction(mlir::MLIRContext *MLIRCtx)
301 : CIRGenAction(OutputType::EmitAssembly, MLIRCtx) {}
302
303void EmitCIRAction::anchor() {}
304EmitCIRAction::EmitCIRAction(mlir::MLIRContext *MLIRCtx)
305 : CIRGenAction(OutputType::EmitCIR, MLIRCtx) {}
306
307void EmitLLVMAction::anchor() {}
308EmitLLVMAction::EmitLLVMAction(mlir::MLIRContext *MLIRCtx)
309 : CIRGenAction(OutputType::EmitLLVM, MLIRCtx) {}
310
311void EmitBCAction::anchor() {}
312EmitBCAction::EmitBCAction(mlir::MLIRContext *MLIRCtx)
313 : CIRGenAction(OutputType::EmitBC, MLIRCtx) {}
314
315void EmitObjAction::anchor() {}
316EmitObjAction::EmitObjAction(mlir::MLIRContext *MLIRCtx)
317 : CIRGenAction(OutputType::EmitObj, MLIRCtx) {}
static std::unique_ptr< raw_pwrite_stream > getOutputStream(CompilerInstance &CI, StringRef InFile, CIRGenAction::OutputType Action)
CIRGenAction(OutputType Action, mlir::MLIRContext *MLIRCtx=nullptr)
OutputType Action
bool BeginSourceFileAction(clang::CompilerInstance &CI) override
Callback at the start of processing a single input.
~CIRGenAction() override
std::unique_ptr< clang::ASTConsumer > CreateASTConsumer(clang::CompilerInstance &CI, llvm::StringRef InFile) override
void Initialize(ASTContext &Ctx) override
Initialize - This is called to initialize the consumer, providing the ASTContext.
bool HandleTopLevelDecl(DeclGroupRef D) override
HandleTopLevelDecl - Handle the specified top-level declaration.
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
bool linkInModules(llvm::Module &M)
void HandleInlineFunctionDefinition(FunctionDecl *D) override
This callback is invoked each time an inline (method or friend) function definition in a class is com...
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
void HandleTagDeclRequiredDefinition(const TagDecl *D) override
This callback is invoked the first time each TagDecl is required to be complete.
CIRGenConsumer(CIRGenAction::OutputType Action, CompilerInstance &CI, CodeGenOptions &CGO, std::unique_ptr< raw_pwrite_stream > OS, llvm::LLVMContext &LLVMCtx, SmallVectorImpl<::clang::LinkModule > &LinkModules)
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
void HandleCXXStaticMemberVarInstantiation(clang::VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
void HandleOpenACCRoutineReference(const FunctionDecl *FD, const OpenACCRoutineDecl *RD) override
Callback to handle the end-of-translation unit attachment of OpenACC routine declaration information.
void HandleTagDeclDefinition(TagDecl *D) override
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
EmitAssemblyAction(mlir::MLIRContext *MLIRCtx=nullptr)
EmitBCAction(mlir::MLIRContext *MLIRCtx=nullptr)
EmitCIRAction(mlir::MLIRContext *MLIRCtx=nullptr)
EmitLLVMAction(mlir::MLIRContext *MLIRCtx=nullptr)
EmitObjAction(mlir::MLIRContext *MLIRCtx=nullptr)
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
CodeGenOptions & getCodeGenOpts()
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
FrontendOptions - Options for controlling the behavior of the frontend.
Represents a function declaration or definition.
Definition Decl.h:2029
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition DeclBase.h:1317
Encodes a location in the source.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
Represents a variable declaration or definition.
Definition Decl.h:932
std::unique_ptr< llvm::Module > lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp mlirModule, llvm::LLVMContext &llvmCtx, bool enableOpenMP, llvm::StringRef mlirSaveTempsOutFile={}, llvm::vfs::FileSystem *fs=nullptr)
static BackendAction getBackendActionFromOutputType(CIRGenAction::OutputType Action)
mlir::LogicalResult runCIRToCIRPasses(mlir::ModuleOp theModule, mlir::MLIRContext &mlirCtx, clang::ASTContext &astCtx, bool enableVerifier, bool enableIdiomRecognizer, bool enableCIRSimplify, bool enableLibOpt, llvm::StringRef libOptOptions, bool enableCallConvLowering)
Definition CIRPasses.cpp:32
static std::unique_ptr< llvm::Module > lowerFromCIRToLLVMIR(mlir::ModuleOp MLIRModule, llvm::LLVMContext &LLVMCtx, bool EnableOpenMP, llvm::StringRef mlirSaveTempsOutFile={}, llvm::vfs::FileSystem *fs=nullptr)
void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)
Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...
Definition CGCall.cpp:2480
The JSON file list parser is used to communicate input to InstallAPI.
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
BackendAction
Definition BackendUtil.h:33
@ Backend_EmitAssembly
Emit native assembly files.
Definition BackendUtil.h:34
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition BackendUtil.h:36
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition BackendUtil.h:35
@ Backend_EmitObj
Emit native object files.
Definition BackendUtil.h:39
bool loadLinkModules(CompilerInstance &CI, llvm::LLVMContext &Ctx, llvm::SmallVectorImpl< LinkModule > &LinkModules)
Load every bitcode file listed in CodeGenOpts.LinkBitcodeFiles into LinkModules.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30