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/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclGroup.h"
14 #include "clang/Basic/FileManager.h"
15 #include "clang/Basic/SourceManager.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/CodeGen/BackendUtil.h"
18 #include "clang/CodeGen/ModuleBuilder.h"
19 #include "clang/Frontend/CompilerInstance.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IRReader/IRReader.h"
27 #include "llvm/Linker.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Support/Timer.h"
32 using namespace clang;
36 class BackendConsumer : public ASTConsumer {
37 virtual void anchor();
38 DiagnosticsEngine &Diags;
40 const CodeGenOptions &CodeGenOpts;
41 const TargetOptions &TargetOpts;
42 const LangOptions &LangOpts;
43 raw_ostream *AsmOutStream;
46 Timer LLVMIRGeneration;
48 OwningPtr<CodeGenerator> Gen;
50 OwningPtr<llvm::Module> TheModule, LinkModule;
53 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
54 const CodeGenOptions &compopts,
55 const TargetOptions &targetopts,
56 const LangOptions &langopts,
58 const std::string &infile,
59 llvm::Module *LinkModule,
64 CodeGenOpts(compopts),
65 TargetOpts(targetopts),
69 LLVMIRGeneration("LLVM IR Generation Time"),
70 Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
71 LinkModule(LinkModule)
73 llvm::TimePassesIsEnabled = TimePasses;
76 llvm::Module *takeModule() { return TheModule.take(); }
77 llvm::Module *takeLinkModule() { return LinkModule.take(); }
79 virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
80 Gen->HandleCXXStaticMemberVarInstantiation(VD);
83 virtual void Initialize(ASTContext &Ctx) {
86 if (llvm::TimePassesIsEnabled)
87 LLVMIRGeneration.startTimer();
91 TheModule.reset(Gen->GetModule());
93 if (llvm::TimePassesIsEnabled)
94 LLVMIRGeneration.stopTimer();
97 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
98 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
99 Context->getSourceManager(),
100 "LLVM IR generation of declaration");
102 if (llvm::TimePassesIsEnabled)
103 LLVMIRGeneration.startTimer();
105 Gen->HandleTopLevelDecl(D);
107 if (llvm::TimePassesIsEnabled)
108 LLVMIRGeneration.stopTimer();
113 virtual void HandleTranslationUnit(ASTContext &C) {
115 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
116 if (llvm::TimePassesIsEnabled)
117 LLVMIRGeneration.startTimer();
119 Gen->HandleTranslationUnit(C);
121 if (llvm::TimePassesIsEnabled)
122 LLVMIRGeneration.stopTimer();
125 // Silently ignore if we weren't initialized for some reason.
129 // Make sure IR generation is happy with the module. This is released by
130 // the module provider.
131 llvm::Module *M = Gen->ReleaseModule();
133 // The module has been released by IR gen on failures, do not double
139 assert(TheModule.get() == M &&
140 "Unexpected module change during IR generation");
142 // Link LinkModule into this module if present, preserving its validity.
144 std::string ErrorMsg;
145 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
147 Diags.Report(diag::err_fe_cannot_link_module)
148 << LinkModule->getModuleIdentifier() << ErrorMsg;
153 // Install an inline asm handler so that diagnostics get printed through
154 // our diagnostics hooks.
155 LLVMContext &Ctx = TheModule->getContext();
156 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
157 Ctx.getInlineAsmDiagnosticHandler();
158 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
159 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
161 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
162 TheModule.get(), Action, AsmOutStream);
164 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
167 virtual void HandleTagDeclDefinition(TagDecl *D) {
168 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
169 Context->getSourceManager(),
170 "LLVM IR generation of declaration");
171 Gen->HandleTagDeclDefinition(D);
174 virtual void HandleTagDeclRequiredDefinition(const TagDecl *D) {
175 Gen->HandleTagDeclRequiredDefinition(D);
178 virtual void CompleteTentativeDefinition(VarDecl *D) {
179 Gen->CompleteTentativeDefinition(D);
182 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
183 Gen->HandleVTable(RD, DefinitionRequired);
186 virtual void HandleLinkerOptionPragma(llvm::StringRef Opts) {
187 Gen->HandleLinkerOptionPragma(Opts);
190 virtual void HandleDetectMismatch(llvm::StringRef Name,
191 llvm::StringRef Value) {
192 Gen->HandleDetectMismatch(Name, Value);
195 virtual void HandleDependentLibrary(llvm::StringRef Opts) {
196 Gen->HandleDependentLibrary(Opts);
199 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
200 unsigned LocCookie) {
201 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
202 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
205 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
206 SourceLocation LocCookie);
209 void BackendConsumer::anchor() {}
212 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
213 /// buffer to be a valid FullSourceLoc.
214 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
215 SourceManager &CSM) {
216 // Get both the clang and llvm source managers. The location is relative to
217 // a memory buffer that the LLVM Source Manager is handling, we need to add
218 // a copy to the Clang source manager.
219 const llvm::SourceMgr &LSM = *D.getSourceMgr();
221 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
222 // already owns its one and clang::SourceManager wants to own its one.
223 const MemoryBuffer *LBuf =
224 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
226 // Create the copy and transfer ownership to clang::SourceManager.
227 llvm::MemoryBuffer *CBuf =
228 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
229 LBuf->getBufferIdentifier());
230 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
232 // Translate the offset into the file.
233 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
234 SourceLocation NewLoc =
235 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
236 return FullSourceLoc(NewLoc, CSM);
240 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
241 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
242 /// the temporary memory buffer that the inline asm parser has set up.
243 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
244 SourceLocation LocCookie) {
245 // There are a couple of different kinds of errors we could get here. First,
246 // we re-format the SMDiagnostic in terms of a clang diagnostic.
248 // Strip "error: " off the start of the message string.
249 StringRef Message = D.getMessage();
250 if (Message.startswith("error: "))
251 Message = Message.substr(7);
253 // If the SMDiagnostic has an inline asm source location, translate it.
255 if (D.getLoc() != SMLoc())
256 Loc = ConvertBackendLocation(D, Context->getSourceManager());
259 // If this problem has clang-level source location information, report the
260 // issue as being an error in the source with a note showing the instantiated
262 if (LocCookie.isValid()) {
263 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
265 if (D.getLoc().isValid()) {
266 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
267 // Convert the SMDiagnostic ranges into SourceRange and attach them
268 // to the diagnostic.
269 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
270 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
271 unsigned Column = D.getColumnNo();
272 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
273 Loc.getLocWithOffset(Range.second - Column));
279 // Otherwise, report the backend error as occurring in the generated .s file.
280 // If Loc is invalid, we still need to report the error, it just gets no
282 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
287 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
288 : Act(_Act), LinkModule(0),
289 VMContext(_VMContext ? _VMContext : new LLVMContext),
290 OwnsVMContext(!_VMContext) {}
292 CodeGenAction::~CodeGenAction() {
298 bool CodeGenAction::hasIRSupport() const { return true; }
300 void CodeGenAction::EndSourceFileAction() {
301 // If the consumer creation failed, do nothing.
302 if (!getCompilerInstance().hasASTConsumer())
305 // If we were given a link module, release consumer's ownership of it.
307 BEConsumer->takeLinkModule();
309 // Steal the module from the consumer.
310 TheModule.reset(BEConsumer->takeModule());
313 llvm::Module *CodeGenAction::takeModule() {
314 return TheModule.take();
317 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
318 OwnsVMContext = false;
322 static raw_ostream *GetOutputStream(CompilerInstance &CI,
324 BackendAction Action) {
326 case Backend_EmitAssembly:
327 return CI.createDefaultOutputFile(false, InFile, "s");
329 return CI.createDefaultOutputFile(false, InFile, "ll");
331 return CI.createDefaultOutputFile(true, InFile, "bc");
332 case Backend_EmitNothing:
334 case Backend_EmitMCNull:
335 case Backend_EmitObj:
336 return CI.createDefaultOutputFile(true, InFile, "o");
339 llvm_unreachable("Invalid action!");
342 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
344 BackendAction BA = static_cast<BackendAction>(Act);
345 OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
346 if (BA != Backend_EmitNothing && !OS)
349 llvm::Module *LinkModuleToUse = LinkModule;
351 // If we were not given a link module, and the user requested that one be
352 // loaded from bitcode, do so now.
353 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
354 if (!LinkModuleToUse && !LinkBCFile.empty()) {
355 std::string ErrorStr;
357 llvm::MemoryBuffer *BCBuf =
358 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
360 CI.getDiagnostics().Report(diag::err_cannot_open_file)
361 << LinkBCFile << ErrorStr;
365 LinkModuleToUse = getLazyBitcodeModule(BCBuf, *VMContext, &ErrorStr);
366 if (!LinkModuleToUse) {
367 CI.getDiagnostics().Report(diag::err_cannot_open_file)
368 << LinkBCFile << ErrorStr;
374 new BackendConsumer(BA, CI.getDiagnostics(),
375 CI.getCodeGenOpts(), CI.getTargetOpts(),
377 CI.getFrontendOpts().ShowTimers, InFile,
378 LinkModuleToUse, OS.take(), *VMContext);
382 void CodeGenAction::ExecuteAction() {
383 // If this is an IR file, we have to treat it specially.
384 if (getCurrentFileKind() == IK_LLVM_IR) {
385 BackendAction BA = static_cast<BackendAction>(Act);
386 CompilerInstance &CI = getCompilerInstance();
387 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
388 if (BA != Backend_EmitNothing && !OS)
392 SourceManager &SM = CI.getSourceManager();
393 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
398 // FIXME: This is stupid, IRReader shouldn't take ownership.
399 llvm::MemoryBuffer *MainFileCopy =
400 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
403 llvm::SMDiagnostic Err;
404 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
406 // Translate from the diagnostic info to the SourceManager location.
407 SourceLocation Loc = SM.translateFileLineCol(
408 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
409 Err.getColumnNo() + 1);
411 // Get a custom diagnostic for the error. We strip off a leading
412 // diagnostic code if there is one.
413 StringRef Msg = Err.getMessage();
414 if (Msg.startswith("error: "))
417 // Escape '%', which is interpreted as a format character.
418 SmallString<128> EscapedMessage;
419 for (unsigned i = 0, e = Msg.size(); i != e; ++i) {
421 EscapedMessage += '%';
422 EscapedMessage += Msg[i];
425 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
426 DiagnosticsEngine::Error, EscapedMessage);
428 CI.getDiagnostics().Report(Loc, DiagID);
432 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
433 CI.getTargetOpts(), CI.getLangOpts(),
439 // Otherwise follow the normal AST path.
440 this->ASTFrontendAction::ExecuteAction();
445 void EmitAssemblyAction::anchor() { }
446 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
447 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
449 void EmitBCAction::anchor() { }
450 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
451 : CodeGenAction(Backend_EmitBC, _VMContext) {}
453 void EmitLLVMAction::anchor() { }
454 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
455 : CodeGenAction(Backend_EmitLL, _VMContext) {}
457 void EmitLLVMOnlyAction::anchor() { }
458 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
459 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
461 void EmitCodeGenOnlyAction::anchor() { }
462 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
463 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
465 void EmitObjAction::anchor() { }
466 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
467 : CodeGenAction(Backend_EmitObj, _VMContext) {}