clang 23.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 llvm::StringRef mlirSaveTempsOutFile = {},
61 llvm::vfs::FileSystem *fs = nullptr) {
62 return direct::lowerDirectlyFromCIRToLLVMIR(MLIRModule, LLVMCtx,
63 mlirSaveTempsOutFile, fs);
64}
65
67
68 virtual void anchor();
69
71
73
74 std::unique_ptr<raw_pwrite_stream> OutputStream;
75
76 ASTContext *Context{nullptr};
78 std::unique_ptr<CIRGenerator> Gen;
79 const FrontendOptions &FEOptions;
80 CodeGenOptions &CGO;
81
82 llvm::LLVMContext &LLVMCtx;
84
85public:
87 CodeGenOptions &CGO, std::unique_ptr<raw_pwrite_stream> OS,
88 llvm::LLVMContext &LLVMCtx,
90 : Action(Action), CI(CI), OutputStream(std::move(OS)),
91 FS(&CI.getVirtualFileSystem()),
92 Gen(std::make_unique<CIRGenerator>(CI.getDiagnostics(), std::move(FS),
93 CI.getCodeGenOpts())),
94 FEOptions(CI.getFrontendOpts()), CGO(CGO), LLVMCtx(LLVMCtx),
95 LinkModules(LinkModules) {}
96
97 void Initialize(ASTContext &Ctx) override {
98 assert(!Context && "initialized multiple times");
99 Context = &Ctx;
100 Gen->Initialize(Ctx);
101 }
102
104 Gen->HandleTopLevelDecl(D);
105 return true;
106 }
107
109 Gen->HandleCXXStaticMemberVarInstantiation(VD);
110 }
111
113 const OpenACCRoutineDecl *RD) override {
114 Gen->HandleOpenACCRoutineReference(FD, RD);
115 }
116
118 Gen->HandleInlineFunctionDefinition(D);
119 }
120
122 Gen->HandleTranslationUnit(C);
123
124 if (!FEOptions.ClangIRDisableCIRVerifier) {
125 if (!Gen->verifyModule()) {
126 CI.getDiagnostics().Report(
127 diag::err_cir_verification_failed_pre_passes);
128 llvm::report_fatal_error(
129 "CIR codegen: module verification error before running CIR passes");
130 return;
131 }
132 }
133
134 mlir::ModuleOp MlirModule = Gen->getModule();
135 mlir::MLIRContext &MlirCtx = Gen->getMLIRContext();
136
137 if (!FEOptions.ClangIRDisablePasses) {
138 std::string LibOptOptions = FEOptions.ClangIRLibOptOptions;
139
140 // Setup and run CIR pipeline.
141 const bool EnableLibOpt =
142 FEOptions.ClangIRLibOptEnabled && (CGO.OptimizationLevel > 0);
144 MlirModule, MlirCtx, C, !FEOptions.ClangIRDisableCIRVerifier,
145 FEOptions.ClangIREnableIdiomRecognizer, CGO.OptimizationLevel > 0,
146 EnableLibOpt, LibOptOptions)
147 .failed()) {
148 CI.getDiagnostics().Report(diag::err_cir_to_cir_transform_failed);
149 return;
150 }
151 }
152
153 switch (Action) {
155 if (OutputStream && MlirModule) {
156 mlir::OpPrintingFlags Flags;
157 Flags.enableDebugInfo(/*enable=*/true, /*prettyForm=*/false);
158 MlirModule->print(*OutputStream, Flags);
159 }
160 break;
165 StringRef saveTempsPrefix = CGO.SaveTempsFilePrefix;
166 std::string cirSaveTempsOutFile, mlirSaveTempsOutFile;
167 if (!saveTempsPrefix.empty()) {
168 SmallString<128> stem(saveTempsPrefix);
169 llvm::sys::path::replace_extension(stem, "cir");
170 cirSaveTempsOutFile = std::string(stem);
171 llvm::sys::path::replace_extension(stem, "mlir");
172 mlirSaveTempsOutFile = std::string(stem);
173 }
174
175 if (!cirSaveTempsOutFile.empty()) {
176 std::error_code ec;
177 llvm::raw_fd_ostream out(cirSaveTempsOutFile, ec);
178 if (!ec)
179 MlirModule->print(out);
180 }
181
182 std::unique_ptr<llvm::Module> LLVMModule =
183 lowerFromCIRToLLVMIR(MlirModule, LLVMCtx, mlirSaveTempsOutFile,
184 &CI.getVirtualFileSystem());
185
186 if (linkInModules(*LLVMModule))
187 return;
188
191 CI, CI.getCodeGenOpts(), C.getTargetInfo().getDataLayoutString(),
192 LLVMModule.get(), BEAction, FS, std::move(OutputStream));
193 break;
194 }
195 }
196 }
197
198 // TODO: share with BackendConsumer::LinkInModules once OG's CurLinkModule
199 // diagnostic-handler indirection is abstracted behind a callback for CIR.
200 bool linkInModules(llvm::Module &M) {
201 for (auto &LM : LinkModules) {
202 assert(LM.Module && "LinkModule does not actually have a module");
203
204 if (LM.PropagateAttrs)
205 for (llvm::Function &F : *LM.Module) {
206 if (F.isIntrinsic())
207 continue;
209 F, CGO, CI.getLangOpts(), CI.getTargetOpts(), LM.Internalize);
210 }
211
212 bool Err;
213 if (LM.Internalize) {
214 Err = llvm::Linker::linkModules(
215 M, std::move(LM.Module), LM.LinkFlags,
216 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
217 llvm::internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
218 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
219 });
220 });
221 } else {
222 Err = llvm::Linker::linkModules(M, std::move(LM.Module), LM.LinkFlags);
223 }
224
225 if (Err)
226 return true;
227 }
228
229 LinkModules.clear();
230 return false;
231 }
232
235 Context->getSourceManager(),
236 "CIR generation of declaration");
237 Gen->HandleTagDeclDefinition(D);
238 }
239
240 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
241 Gen->HandleTagDeclRequiredDefinition(D);
242 }
243
245 Gen->CompleteTentativeDefinition(D);
246 }
247
248 void HandleVTable(CXXRecordDecl *RD) override { Gen->HandleVTable(RD); }
249};
250} // namespace cir
251
252void CIRGenConsumer::anchor() {}
253
254CIRGenAction::CIRGenAction(OutputType Act, mlir::MLIRContext *MLIRCtx)
255 : MLIRCtx(MLIRCtx ? MLIRCtx : new mlir::MLIRContext),
256 Ctx(std::make_unique<llvm::LLVMContext>()), Action(Act) {}
257
258CIRGenAction::~CIRGenAction() { MLIRMod.release(); }
259
261 if (clang::loadLinkModules(CI, *Ctx, LinkModules))
262 return false;
264}
265
266static std::unique_ptr<raw_pwrite_stream>
267getOutputStream(CompilerInstance &CI, StringRef InFile,
269 switch (Action) {
271 return CI.createDefaultOutputFile(false, InFile, "s");
273 return CI.createDefaultOutputFile(false, InFile, "cir");
275 return CI.createDefaultOutputFile(false, InFile, "ll");
277 return CI.createDefaultOutputFile(true, InFile, "bc");
279 return CI.createDefaultOutputFile(true, InFile, "o");
280 }
281 llvm_unreachable("Invalid CIRGenAction::OutputType");
282}
283
284std::unique_ptr<ASTConsumer>
286 std::unique_ptr<llvm::raw_pwrite_stream> Out = CI.takeOutputStream();
287
288 if (!Out)
289 Out = getOutputStream(CI, InFile, Action);
290
291 auto Result = std::make_unique<cir::CIRGenConsumer>(
292 Action, CI, CI.getCodeGenOpts(), std::move(Out), *Ctx, LinkModules);
293
294 return Result;
295}
296
297void EmitAssemblyAction::anchor() {}
298EmitAssemblyAction::EmitAssemblyAction(mlir::MLIRContext *MLIRCtx)
299 : CIRGenAction(OutputType::EmitAssembly, MLIRCtx) {}
300
301void EmitCIRAction::anchor() {}
302EmitCIRAction::EmitCIRAction(mlir::MLIRContext *MLIRCtx)
303 : CIRGenAction(OutputType::EmitCIR, MLIRCtx) {}
304
305void EmitLLVMAction::anchor() {}
306EmitLLVMAction::EmitLLVMAction(mlir::MLIRContext *MLIRCtx)
307 : CIRGenAction(OutputType::EmitLLVM, MLIRCtx) {}
308
309void EmitBCAction::anchor() {}
310EmitBCAction::EmitBCAction(mlir::MLIRContext *MLIRCtx)
311 : CIRGenAction(OutputType::EmitBC, MLIRCtx) {}
312
313void EmitObjAction::anchor() {}
314EmitObjAction::EmitObjAction(mlir::MLIRContext *MLIRCtx)
315 : 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:2027
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:3752
Represents a variable declaration or definition.
Definition Decl.h:932
std::unique_ptr< llvm::Module > lowerDirectlyFromCIRToLLVMIR(mlir::ModuleOp mlirModule, llvm::LLVMContext &llvmCtx, 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)
Definition CIRPasses.cpp:22
static std::unique_ptr< llvm::Module > lowerFromCIRToLLVMIR(mlir::ModuleOp MLIRModule, llvm::LLVMContext &LLVMCtx, 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:2421
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