1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/CodeGen/CodeGenAction.h"
11 #include "clang/Basic/SourceManager.h"
12 #include "clang/Basic/TargetInfo.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclGroup.h"
16 #include "clang/CodeGen/BackendUtil.h"
17 #include "clang/CodeGen/ModuleBuilder.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/Support/IRReader.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/Timer.h"
28 using namespace clang;
32 class BackendConsumer : public ASTConsumer {
33 DiagnosticsEngine &Diags;
35 const CodeGenOptions &CodeGenOpts;
36 const TargetOptions &TargetOpts;
37 const LangOptions &LangOpts;
38 raw_ostream *AsmOutStream;
41 Timer LLVMIRGeneration;
43 llvm::OwningPtr<CodeGenerator> Gen;
45 llvm::OwningPtr<llvm::Module> TheModule;
48 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
49 const CodeGenOptions &compopts,
50 const TargetOptions &targetopts,
51 const LangOptions &langopts,
53 const std::string &infile, raw_ostream *OS,
57 CodeGenOpts(compopts),
58 TargetOpts(targetopts),
61 LLVMIRGeneration("LLVM IR Generation Time"),
62 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)) {
63 llvm::TimePassesIsEnabled = TimePasses;
66 llvm::Module *takeModule() { return TheModule.take(); }
68 virtual void Initialize(ASTContext &Ctx) {
71 if (llvm::TimePassesIsEnabled)
72 LLVMIRGeneration.startTimer();
76 TheModule.reset(Gen->GetModule());
78 if (llvm::TimePassesIsEnabled)
79 LLVMIRGeneration.stopTimer();
82 virtual void HandleTopLevelDecl(DeclGroupRef D) {
83 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
84 Context->getSourceManager(),
85 "LLVM IR generation of declaration");
87 if (llvm::TimePassesIsEnabled)
88 LLVMIRGeneration.startTimer();
90 Gen->HandleTopLevelDecl(D);
92 if (llvm::TimePassesIsEnabled)
93 LLVMIRGeneration.stopTimer();
96 virtual void HandleTranslationUnit(ASTContext &C) {
98 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
99 if (llvm::TimePassesIsEnabled)
100 LLVMIRGeneration.startTimer();
102 Gen->HandleTranslationUnit(C);
104 if (llvm::TimePassesIsEnabled)
105 LLVMIRGeneration.stopTimer();
108 // Silently ignore if we weren't initialized for some reason.
112 // Make sure IR generation is happy with the module. This is released by
113 // the module provider.
114 Module *M = Gen->ReleaseModule();
116 // The module has been released by IR gen on failures, do not double
122 assert(TheModule.get() == M &&
123 "Unexpected module change during IR generation");
125 // Install an inline asm handler so that diagnostics get printed through
126 // our diagnostics hooks.
127 LLVMContext &Ctx = TheModule->getContext();
128 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
129 Ctx.getInlineAsmDiagnosticHandler();
130 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
131 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
133 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
134 TheModule.get(), Action, AsmOutStream);
136 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
139 virtual void HandleTagDeclDefinition(TagDecl *D) {
140 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
141 Context->getSourceManager(),
142 "LLVM IR generation of declaration");
143 Gen->HandleTagDeclDefinition(D);
146 virtual void CompleteTentativeDefinition(VarDecl *D) {
147 Gen->CompleteTentativeDefinition(D);
150 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
151 Gen->HandleVTable(RD, DefinitionRequired);
154 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
155 unsigned LocCookie) {
156 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
157 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
160 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
161 SourceLocation LocCookie);
165 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
166 /// buffer to be a valid FullSourceLoc.
167 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
168 SourceManager &CSM) {
169 // Get both the clang and llvm source managers. The location is relative to
170 // a memory buffer that the LLVM Source Manager is handling, we need to add
171 // a copy to the Clang source manager.
172 const llvm::SourceMgr &LSM = *D.getSourceMgr();
174 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
175 // already owns its one and clang::SourceManager wants to own its one.
176 const MemoryBuffer *LBuf =
177 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
179 // Create the copy and transfer ownership to clang::SourceManager.
180 llvm::MemoryBuffer *CBuf =
181 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
182 LBuf->getBufferIdentifier());
183 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
185 // Translate the offset into the file.
186 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
187 SourceLocation NewLoc =
188 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
189 return FullSourceLoc(NewLoc, CSM);
193 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
194 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
195 /// the temporary memory buffer that the inline asm parser has set up.
196 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
197 SourceLocation LocCookie) {
198 // There are a couple of different kinds of errors we could get here. First,
199 // we re-format the SMDiagnostic in terms of a clang diagnostic.
201 // Strip "error: " off the start of the message string.
202 StringRef Message = D.getMessage();
203 if (Message.startswith("error: "))
204 Message = Message.substr(7);
206 // If the SMDiagnostic has an inline asm source location, translate it.
208 if (D.getLoc() != SMLoc())
209 Loc = ConvertBackendLocation(D, Context->getSourceManager());
212 // If this problem has clang-level source location information, report the
213 // issue as being an error in the source with a note showing the instantiated
215 if (LocCookie.isValid()) {
216 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
218 if (D.getLoc().isValid())
219 Diags.Report(Loc, diag::note_fe_inline_asm_here);
223 // Otherwise, report the backend error as occurring in the generated .s file.
224 // If Loc is invalid, we still need to report the error, it just gets no
226 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
231 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
232 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
233 OwnsVMContext(!_VMContext) {}
235 CodeGenAction::~CodeGenAction() {
241 bool CodeGenAction::hasIRSupport() const { return true; }
243 void CodeGenAction::EndSourceFileAction() {
244 // If the consumer creation failed, do nothing.
245 if (!getCompilerInstance().hasASTConsumer())
248 // Steal the module from the consumer.
249 TheModule.reset(BEConsumer->takeModule());
252 llvm::Module *CodeGenAction::takeModule() {
253 return TheModule.take();
256 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
257 OwnsVMContext = false;
261 static raw_ostream *GetOutputStream(CompilerInstance &CI,
263 BackendAction Action) {
265 case Backend_EmitAssembly:
266 return CI.createDefaultOutputFile(false, InFile, "s");
268 return CI.createDefaultOutputFile(false, InFile, "ll");
270 return CI.createDefaultOutputFile(true, InFile, "bc");
271 case Backend_EmitNothing:
273 case Backend_EmitMCNull:
274 case Backend_EmitObj:
275 return CI.createDefaultOutputFile(true, InFile, "o");
278 llvm_unreachable("Invalid action!");
281 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
283 BackendAction BA = static_cast<BackendAction>(Act);
284 llvm::OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
285 if (BA != Backend_EmitNothing && !OS)
289 new BackendConsumer(BA, CI.getDiagnostics(),
290 CI.getCodeGenOpts(), CI.getTargetOpts(),
292 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
297 void CodeGenAction::ExecuteAction() {
298 // If this is an IR file, we have to treat it specially.
299 if (getCurrentFileKind() == IK_LLVM_IR) {
300 BackendAction BA = static_cast<BackendAction>(Act);
301 CompilerInstance &CI = getCompilerInstance();
302 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
303 if (BA != Backend_EmitNothing && !OS)
307 SourceManager &SM = CI.getSourceManager();
308 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
313 // FIXME: This is stupid, IRReader shouldn't take ownership.
314 llvm::MemoryBuffer *MainFileCopy =
315 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
316 getCurrentFile().c_str());
318 llvm::SMDiagnostic Err;
319 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
321 // Translate from the diagnostic info to the SourceManager location.
322 SourceLocation Loc = SM.translateFileLineCol(
323 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
324 Err.getColumnNo() + 1);
326 // Get a custom diagnostic for the error. We strip off a leading
327 // diagnostic code if there is one.
328 StringRef Msg = Err.getMessage();
329 if (Msg.startswith("error: "))
331 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
332 DiagnosticsEngine::Error, Msg);
334 CI.getDiagnostics().Report(Loc, DiagID);
338 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
339 CI.getTargetOpts(), CI.getLangOpts(),
345 // Otherwise follow the normal AST path.
346 this->ASTFrontendAction::ExecuteAction();
351 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
352 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
354 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
355 : CodeGenAction(Backend_EmitBC, _VMContext) {}
357 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
358 : CodeGenAction(Backend_EmitLL, _VMContext) {}
360 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
361 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
363 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
364 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
366 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
367 : CodeGenAction(Backend_EmitObj, _VMContext) {}