1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
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;
33 using namespace llvm;
34 
35 namespace clang {
36   class BackendConsumer : public ASTConsumer {
37     virtual void anchor();
38     DiagnosticsEngine &Diags;
39     BackendAction Action;
40     const CodeGenOptions &CodeGenOpts;
41     const TargetOptions &TargetOpts;
42     const LangOptions &LangOpts;
43     raw_ostream *AsmOutStream;
44     ASTContext *Context;
45 
46     Timer LLVMIRGeneration;
47 
48     OwningPtr<CodeGenerator> Gen;
49 
50     OwningPtr<llvm::Module> TheModule, LinkModule;
51 
52   public:
53     BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
54                     const CodeGenOptions &compopts,
55                     const TargetOptions &targetopts,
56                     const LangOptions &langopts,
57                     bool TimePasses,
58                     const std::string &infile,
59                     llvm::Module *LinkModule,
60                     raw_ostream *OS,
61                     LLVMContext &C) :
62       Diags(_Diags),
63       Action(action),
64       CodeGenOpts(compopts),
65       TargetOpts(targetopts),
66       LangOpts(langopts),
67       AsmOutStream(OS),
68       Context(),
69       LLVMIRGeneration("LLVM IR Generation Time"),
70       Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
71       LinkModule(LinkModule)
72     {
73       llvm::TimePassesIsEnabled = TimePasses;
74     }
75 
76     llvm::Module *takeModule() { return TheModule.take(); }
77     llvm::Module *takeLinkModule() { return LinkModule.take(); }
78 
79     virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
80       Gen->HandleCXXStaticMemberVarInstantiation(VD);
81     }
82 
83     virtual void Initialize(ASTContext &Ctx) {
84       Context = &Ctx;
85 
86       if (llvm::TimePassesIsEnabled)
87         LLVMIRGeneration.startTimer();
88 
89       Gen->Initialize(Ctx);
90 
91       TheModule.reset(Gen->GetModule());
92 
93       if (llvm::TimePassesIsEnabled)
94         LLVMIRGeneration.stopTimer();
95     }
96 
97     virtual bool HandleTopLevelDecl(DeclGroupRef D) {
98       PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
99                                      Context->getSourceManager(),
100                                      "LLVM IR generation of declaration");
101 
102       if (llvm::TimePassesIsEnabled)
103         LLVMIRGeneration.startTimer();
104 
105       Gen->HandleTopLevelDecl(D);
106 
107       if (llvm::TimePassesIsEnabled)
108         LLVMIRGeneration.stopTimer();
109 
110       return true;
111     }
112 
113     virtual void HandleTranslationUnit(ASTContext &C) {
114       {
115         PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
116         if (llvm::TimePassesIsEnabled)
117           LLVMIRGeneration.startTimer();
118 
119         Gen->HandleTranslationUnit(C);
120 
121         if (llvm::TimePassesIsEnabled)
122           LLVMIRGeneration.stopTimer();
123       }
124 
125       // Silently ignore if we weren't initialized for some reason.
126       if (!TheModule)
127         return;
128 
129       // Make sure IR generation is happy with the module. This is released by
130       // the module provider.
131       llvm::Module *M = Gen->ReleaseModule();
132       if (!M) {
133         // The module has been released by IR gen on failures, do not double
134         // free.
135         TheModule.take();
136         return;
137       }
138 
139       assert(TheModule.get() == M &&
140              "Unexpected module change during IR generation");
141 
142       // Link LinkModule into this module if present, preserving its validity.
143       if (LinkModule) {
144         std::string ErrorMsg;
145         if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
146                                 &ErrorMsg)) {
147           Diags.Report(diag::err_fe_cannot_link_module)
148             << LinkModule->getModuleIdentifier() << ErrorMsg;
149           return;
150         }
151       }
152 
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);
160 
161       EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
162                         TheModule.get(), Action, AsmOutStream);
163 
164       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
165     }
166 
167     virtual void HandleTagDeclDefinition(TagDecl *D) {
168       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
169                                      Context->getSourceManager(),
170                                      "LLVM IR generation of declaration");
171       Gen->HandleTagDeclDefinition(D);
172     }
173 
174     virtual void CompleteTentativeDefinition(VarDecl *D) {
175       Gen->CompleteTentativeDefinition(D);
176     }
177 
178     virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
179       Gen->HandleVTable(RD, DefinitionRequired);
180     }
181 
182     virtual void HandleLinkerOptionPragma(llvm::StringRef Opts) {
183       Gen->HandleLinkerOptionPragma(Opts);
184     }
185 
186     virtual void HandleDetectMismatch(llvm::StringRef Name,
187                                       llvm::StringRef Value) {
188       Gen->HandleDetectMismatch(Name, Value);
189     }
190 
191     virtual void HandleDependentLibrary(llvm::StringRef Opts) {
192       Gen->HandleDependentLibrary(Opts);
193     }
194 
195     static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
196                                      unsigned LocCookie) {
197       SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
198       ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
199     }
200 
201     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
202                                SourceLocation LocCookie);
203   };
204 
205   void BackendConsumer::anchor() {}
206 }
207 
208 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
209 /// buffer to be a valid FullSourceLoc.
210 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
211                                             SourceManager &CSM) {
212   // Get both the clang and llvm source managers.  The location is relative to
213   // a memory buffer that the LLVM Source Manager is handling, we need to add
214   // a copy to the Clang source manager.
215   const llvm::SourceMgr &LSM = *D.getSourceMgr();
216 
217   // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
218   // already owns its one and clang::SourceManager wants to own its one.
219   const MemoryBuffer *LBuf =
220   LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
221 
222   // Create the copy and transfer ownership to clang::SourceManager.
223   llvm::MemoryBuffer *CBuf =
224   llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
225                                        LBuf->getBufferIdentifier());
226   FileID FID = CSM.createFileIDForMemBuffer(CBuf);
227 
228   // Translate the offset into the file.
229   unsigned Offset = D.getLoc().getPointer()  - LBuf->getBufferStart();
230   SourceLocation NewLoc =
231   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
232   return FullSourceLoc(NewLoc, CSM);
233 }
234 
235 
236 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
237 /// error parsing inline asm.  The SMDiagnostic indicates the error relative to
238 /// the temporary memory buffer that the inline asm parser has set up.
239 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
240                                             SourceLocation LocCookie) {
241   // There are a couple of different kinds of errors we could get here.  First,
242   // we re-format the SMDiagnostic in terms of a clang diagnostic.
243 
244   // Strip "error: " off the start of the message string.
245   StringRef Message = D.getMessage();
246   if (Message.startswith("error: "))
247     Message = Message.substr(7);
248 
249   // If the SMDiagnostic has an inline asm source location, translate it.
250   FullSourceLoc Loc;
251   if (D.getLoc() != SMLoc())
252     Loc = ConvertBackendLocation(D, Context->getSourceManager());
253 
254 
255   // If this problem has clang-level source location information, report the
256   // issue as being an error in the source with a note showing the instantiated
257   // code.
258   if (LocCookie.isValid()) {
259     Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
260 
261     if (D.getLoc().isValid()) {
262       DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
263       // Convert the SMDiagnostic ranges into SourceRange and attach them
264       // to the diagnostic.
265       for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
266         std::pair<unsigned, unsigned> Range = D.getRanges()[i];
267         unsigned Column = D.getColumnNo();
268         B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
269                          Loc.getLocWithOffset(Range.second - Column));
270       }
271     }
272     return;
273   }
274 
275   // Otherwise, report the backend error as occurring in the generated .s file.
276   // If Loc is invalid, we still need to report the error, it just gets no
277   // location info.
278   Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
279 }
280 
281 //
282 
283 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
284   : Act(_Act), LinkModule(0),
285     VMContext(_VMContext ? _VMContext : new LLVMContext),
286     OwnsVMContext(!_VMContext) {}
287 
288 CodeGenAction::~CodeGenAction() {
289   TheModule.reset();
290   if (OwnsVMContext)
291     delete VMContext;
292 }
293 
294 bool CodeGenAction::hasIRSupport() const { return true; }
295 
296 void CodeGenAction::EndSourceFileAction() {
297   // If the consumer creation failed, do nothing.
298   if (!getCompilerInstance().hasASTConsumer())
299     return;
300 
301   // If we were given a link module, release consumer's ownership of it.
302   if (LinkModule)
303     BEConsumer->takeLinkModule();
304 
305   // Steal the module from the consumer.
306   TheModule.reset(BEConsumer->takeModule());
307 }
308 
309 llvm::Module *CodeGenAction::takeModule() {
310   return TheModule.take();
311 }
312 
313 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
314   OwnsVMContext = false;
315   return VMContext;
316 }
317 
318 static raw_ostream *GetOutputStream(CompilerInstance &CI,
319                                     StringRef InFile,
320                                     BackendAction Action) {
321   switch (Action) {
322   case Backend_EmitAssembly:
323     return CI.createDefaultOutputFile(false, InFile, "s");
324   case Backend_EmitLL:
325     return CI.createDefaultOutputFile(false, InFile, "ll");
326   case Backend_EmitBC:
327     return CI.createDefaultOutputFile(true, InFile, "bc");
328   case Backend_EmitNothing:
329     return 0;
330   case Backend_EmitMCNull:
331   case Backend_EmitObj:
332     return CI.createDefaultOutputFile(true, InFile, "o");
333   }
334 
335   llvm_unreachable("Invalid action!");
336 }
337 
338 ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
339                                               StringRef InFile) {
340   BackendAction BA = static_cast<BackendAction>(Act);
341   OwningPtr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
342   if (BA != Backend_EmitNothing && !OS)
343     return 0;
344 
345   llvm::Module *LinkModuleToUse = LinkModule;
346 
347   // If we were not given a link module, and the user requested that one be
348   // loaded from bitcode, do so now.
349   const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
350   if (!LinkModuleToUse && !LinkBCFile.empty()) {
351     std::string ErrorStr;
352 
353     llvm::MemoryBuffer *BCBuf =
354       CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
355     if (!BCBuf) {
356       CI.getDiagnostics().Report(diag::err_cannot_open_file)
357         << LinkBCFile << ErrorStr;
358       return 0;
359     }
360 
361     LinkModuleToUse = getLazyBitcodeModule(BCBuf, *VMContext, &ErrorStr);
362     if (!LinkModuleToUse) {
363       CI.getDiagnostics().Report(diag::err_cannot_open_file)
364         << LinkBCFile << ErrorStr;
365       return 0;
366     }
367   }
368 
369   BEConsumer =
370       new BackendConsumer(BA, CI.getDiagnostics(),
371                           CI.getCodeGenOpts(), CI.getTargetOpts(),
372                           CI.getLangOpts(),
373                           CI.getFrontendOpts().ShowTimers, InFile,
374                           LinkModuleToUse, OS.take(), *VMContext);
375   return BEConsumer;
376 }
377 
378 void CodeGenAction::ExecuteAction() {
379   // If this is an IR file, we have to treat it specially.
380   if (getCurrentFileKind() == IK_LLVM_IR) {
381     BackendAction BA = static_cast<BackendAction>(Act);
382     CompilerInstance &CI = getCompilerInstance();
383     raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
384     if (BA != Backend_EmitNothing && !OS)
385       return;
386 
387     bool Invalid;
388     SourceManager &SM = CI.getSourceManager();
389     const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
390                                                       &Invalid);
391     if (Invalid)
392       return;
393 
394     // FIXME: This is stupid, IRReader shouldn't take ownership.
395     llvm::MemoryBuffer *MainFileCopy =
396       llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
397                                            getCurrentFile());
398 
399     llvm::SMDiagnostic Err;
400     TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
401     if (!TheModule) {
402       // Translate from the diagnostic info to the SourceManager location.
403       SourceLocation Loc = SM.translateFileLineCol(
404         SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
405         Err.getColumnNo() + 1);
406 
407       // Get a custom diagnostic for the error. We strip off a leading
408       // diagnostic code if there is one.
409       StringRef Msg = Err.getMessage();
410       if (Msg.startswith("error: "))
411         Msg = Msg.substr(7);
412 
413       // Escape '%', which is interpreted as a format character.
414       SmallString<128> EscapedMessage;
415       for (unsigned i = 0, e = Msg.size(); i != e; ++i) {
416         if (Msg[i] == '%')
417           EscapedMessage += '%';
418         EscapedMessage += Msg[i];
419       }
420 
421       unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
422           DiagnosticsEngine::Error, EscapedMessage);
423 
424       CI.getDiagnostics().Report(Loc, DiagID);
425       return;
426     }
427 
428     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
429                       CI.getTargetOpts(), CI.getLangOpts(),
430                       TheModule.get(),
431                       BA, OS);
432     return;
433   }
434 
435   // Otherwise follow the normal AST path.
436   this->ASTFrontendAction::ExecuteAction();
437 }
438 
439 //
440 
441 void EmitAssemblyAction::anchor() { }
442 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
443   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
444 
445 void EmitBCAction::anchor() { }
446 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
447   : CodeGenAction(Backend_EmitBC, _VMContext) {}
448 
449 void EmitLLVMAction::anchor() { }
450 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
451   : CodeGenAction(Backend_EmitLL, _VMContext) {}
452 
453 void EmitLLVMOnlyAction::anchor() { }
454 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
455   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
456 
457 void EmitCodeGenOnlyAction::anchor() { }
458 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
459   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
460 
461 void EmitObjAction::anchor() { }
462 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
463   : CodeGenAction(Backend_EmitObj, _VMContext) {}
464