]> granicus.if.org Git - clang/blob - lib/CodeGen/CodeGenAction.cpp
Embed bitcode in object file (clang cc1 part)
[clang] / lib / CodeGen / CodeGenAction.cpp
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 "CoverageMappingGen.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclGroup.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/CodeGen/BackendUtil.h"
19 #include "clang/CodeGen/CodeGenAction.h"
20 #include "clang/CodeGen/ModuleBuilder.h"
21 #include "clang/Frontend/CompilerInstance.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/Bitcode/ReaderWriter.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/Timer.h"
37 #include <memory>
38 using namespace clang;
39 using namespace llvm;
40
41 namespace clang {
42   class BackendConsumer : public ASTConsumer {
43     virtual void anchor();
44     DiagnosticsEngine &Diags;
45     BackendAction Action;
46     const CodeGenOptions &CodeGenOpts;
47     const TargetOptions &TargetOpts;
48     const LangOptions &LangOpts;
49     raw_pwrite_stream *AsmOutStream;
50     ASTContext *Context;
51
52     Timer LLVMIRGeneration;
53
54     std::unique_ptr<CodeGenerator> Gen;
55
56     SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
57         LinkModules;
58
59     // This is here so that the diagnostic printer knows the module a diagnostic
60     // refers to.
61     llvm::Module *CurLinkModule = nullptr;
62
63   public:
64     BackendConsumer(
65         BackendAction Action, DiagnosticsEngine &Diags,
66         const HeaderSearchOptions &HeaderSearchOpts,
67         const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
68         const TargetOptions &TargetOpts, const LangOptions &LangOpts,
69         bool TimePasses, const std::string &InFile,
70         const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
71         raw_pwrite_stream *OS, LLVMContext &C,
72         CoverageSourceInfo *CoverageInfo = nullptr)
73         : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
74           TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
75           Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
76           Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
77                                 CodeGenOpts, C, CoverageInfo)) {
78       llvm::TimePassesIsEnabled = TimePasses;
79       for (auto &I : LinkModules)
80         this->LinkModules.push_back(
81             std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
82     }
83     llvm::Module *getModule() const { return Gen->GetModule(); }
84     std::unique_ptr<llvm::Module> takeModule() {
85       return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
86     }
87     void releaseLinkModules() {
88       for (auto &I : LinkModules)
89         I.second.release();
90     }
91
92     void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
93       Gen->HandleCXXStaticMemberVarInstantiation(VD);
94     }
95
96     void Initialize(ASTContext &Ctx) override {
97       assert(!Context && "initialized multiple times");
98
99       Context = &Ctx;
100
101       if (llvm::TimePassesIsEnabled)
102         LLVMIRGeneration.startTimer();
103
104       Gen->Initialize(Ctx);
105
106       if (llvm::TimePassesIsEnabled)
107         LLVMIRGeneration.stopTimer();
108     }
109
110     bool HandleTopLevelDecl(DeclGroupRef D) override {
111       PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
112                                      Context->getSourceManager(),
113                                      "LLVM IR generation of declaration");
114
115       if (llvm::TimePassesIsEnabled)
116         LLVMIRGeneration.startTimer();
117
118       Gen->HandleTopLevelDecl(D);
119
120       if (llvm::TimePassesIsEnabled)
121         LLVMIRGeneration.stopTimer();
122
123       return true;
124     }
125
126     void HandleInlineFunctionDefinition(FunctionDecl *D) override {
127       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128                                      Context->getSourceManager(),
129                                      "LLVM IR generation of inline function");
130       if (llvm::TimePassesIsEnabled)
131         LLVMIRGeneration.startTimer();
132
133       Gen->HandleInlineFunctionDefinition(D);
134
135       if (llvm::TimePassesIsEnabled)
136         LLVMIRGeneration.stopTimer();
137     }
138
139     void HandleTranslationUnit(ASTContext &C) override {
140       {
141         PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
142         if (llvm::TimePassesIsEnabled)
143           LLVMIRGeneration.startTimer();
144
145         Gen->HandleTranslationUnit(C);
146
147         if (llvm::TimePassesIsEnabled)
148           LLVMIRGeneration.stopTimer();
149       }
150
151       // Silently ignore if we weren't initialized for some reason.
152       if (!getModule())
153         return;
154
155       // Install an inline asm handler so that diagnostics get printed through
156       // our diagnostics hooks.
157       LLVMContext &Ctx = getModule()->getContext();
158       LLVMContext::InlineAsmDiagHandlerTy OldHandler =
159         Ctx.getInlineAsmDiagnosticHandler();
160       void *OldContext = Ctx.getInlineAsmDiagnosticContext();
161       Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
162
163       LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
164           Ctx.getDiagnosticHandler();
165       void *OldDiagnosticContext = Ctx.getDiagnosticContext();
166       Ctx.setDiagnosticHandler(DiagnosticHandler, this);
167
168       // Link LinkModule into this module if present, preserving its validity.
169       for (auto &I : LinkModules) {
170         unsigned LinkFlags = I.first;
171         CurLinkModule = I.second.get();
172         if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
173           return;
174       }
175
176       EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
177
178       EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
179                         C.getTargetInfo().getDataLayout(),
180                         getModule(), Action, AsmOutStream);
181
182       Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
183
184       Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
185     }
186
187     void HandleTagDeclDefinition(TagDecl *D) override {
188       PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
189                                      Context->getSourceManager(),
190                                      "LLVM IR generation of declaration");
191       Gen->HandleTagDeclDefinition(D);
192     }
193
194     void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
195       Gen->HandleTagDeclRequiredDefinition(D);
196     }
197
198     void CompleteTentativeDefinition(VarDecl *D) override {
199       Gen->CompleteTentativeDefinition(D);
200     }
201
202     void AssignInheritanceModel(CXXRecordDecl *RD) override {
203       Gen->AssignInheritanceModel(RD);
204     }
205
206     void HandleVTable(CXXRecordDecl *RD) override {
207       Gen->HandleVTable(RD);
208     }
209
210     static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
211                                      unsigned LocCookie) {
212       SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
213       ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
214     }
215
216     static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
217                                   void *Context) {
218       ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
219     }
220
221     /// Get the best possible source location to represent a diagnostic that
222     /// may have associated debug info.
223     const FullSourceLoc
224     getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
225                                 bool &BadDebugInfo, StringRef &Filename,
226                                 unsigned &Line, unsigned &Column) const;
227
228     void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
229                                SourceLocation LocCookie);
230
231     void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
232     /// \brief Specialized handler for InlineAsm diagnostic.
233     /// \return True if the diagnostic has been successfully reported, false
234     /// otherwise.
235     bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
236     /// \brief Specialized handler for StackSize diagnostic.
237     /// \return True if the diagnostic has been successfully reported, false
238     /// otherwise.
239     bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
240     /// \brief Specialized handler for unsupported backend feature diagnostic.
241     void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
242     /// \brief Specialized handlers for optimization remarks.
243     /// Note that these handlers only accept remarks and they always handle
244     /// them.
245     void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
246                                  unsigned DiagID);
247     void
248     OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
249     void OptimizationRemarkHandler(
250         const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
251     void OptimizationRemarkHandler(
252         const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
253     void OptimizationRemarkHandler(
254         const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
255     void OptimizationRemarkHandler(
256         const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
257     void OptimizationFailureHandler(
258         const llvm::DiagnosticInfoOptimizationFailure &D);
259   };
260   
261   void BackendConsumer::anchor() {}
262 }
263
264 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
265 /// buffer to be a valid FullSourceLoc.
266 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
267                                             SourceManager &CSM) {
268   // Get both the clang and llvm source managers.  The location is relative to
269   // a memory buffer that the LLVM Source Manager is handling, we need to add
270   // a copy to the Clang source manager.
271   const llvm::SourceMgr &LSM = *D.getSourceMgr();
272
273   // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
274   // already owns its one and clang::SourceManager wants to own its one.
275   const MemoryBuffer *LBuf =
276   LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
277
278   // Create the copy and transfer ownership to clang::SourceManager.
279   // TODO: Avoid copying files into memory.
280   std::unique_ptr<llvm::MemoryBuffer> CBuf =
281       llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
282                                            LBuf->getBufferIdentifier());
283   // FIXME: Keep a file ID map instead of creating new IDs for each location.
284   FileID FID = CSM.createFileID(std::move(CBuf));
285
286   // Translate the offset into the file.
287   unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
288   SourceLocation NewLoc =
289   CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
290   return FullSourceLoc(NewLoc, CSM);
291 }
292
293
294 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
295 /// error parsing inline asm.  The SMDiagnostic indicates the error relative to
296 /// the temporary memory buffer that the inline asm parser has set up.
297 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
298                                             SourceLocation LocCookie) {
299   // There are a couple of different kinds of errors we could get here.  First,
300   // we re-format the SMDiagnostic in terms of a clang diagnostic.
301
302   // Strip "error: " off the start of the message string.
303   StringRef Message = D.getMessage();
304   if (Message.startswith("error: "))
305     Message = Message.substr(7);
306
307   // If the SMDiagnostic has an inline asm source location, translate it.
308   FullSourceLoc Loc;
309   if (D.getLoc() != SMLoc())
310     Loc = ConvertBackendLocation(D, Context->getSourceManager());
311
312   unsigned DiagID;
313   switch (D.getKind()) {
314   case llvm::SourceMgr::DK_Error:
315     DiagID = diag::err_fe_inline_asm;
316     break;
317   case llvm::SourceMgr::DK_Warning:
318     DiagID = diag::warn_fe_inline_asm;
319     break;
320   case llvm::SourceMgr::DK_Note:
321     DiagID = diag::note_fe_inline_asm;
322     break;
323   }
324   // If this problem has clang-level source location information, report the
325   // issue in the source with a note showing the instantiated
326   // code.
327   if (LocCookie.isValid()) {
328     Diags.Report(LocCookie, DiagID).AddString(Message);
329     
330     if (D.getLoc().isValid()) {
331       DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
332       // Convert the SMDiagnostic ranges into SourceRange and attach them
333       // to the diagnostic.
334       for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
335         unsigned Column = D.getColumnNo();
336         B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
337                          Loc.getLocWithOffset(Range.second - Column));
338       }
339     }
340     return;
341   }
342   
343   // Otherwise, report the backend issue as occurring in the generated .s file.
344   // If Loc is invalid, we still need to report the issue, it just gets no
345   // location info.
346   Diags.Report(Loc, DiagID).AddString(Message);
347 }
348
349 #define ComputeDiagID(Severity, GroupName, DiagID)                             \
350   do {                                                                         \
351     switch (Severity) {                                                        \
352     case llvm::DS_Error:                                                       \
353       DiagID = diag::err_fe_##GroupName;                                       \
354       break;                                                                   \
355     case llvm::DS_Warning:                                                     \
356       DiagID = diag::warn_fe_##GroupName;                                      \
357       break;                                                                   \
358     case llvm::DS_Remark:                                                      \
359       llvm_unreachable("'remark' severity not expected");                      \
360       break;                                                                   \
361     case llvm::DS_Note:                                                        \
362       DiagID = diag::note_fe_##GroupName;                                      \
363       break;                                                                   \
364     }                                                                          \
365   } while (false)
366
367 #define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
368   do {                                                                         \
369     switch (Severity) {                                                        \
370     case llvm::DS_Error:                                                       \
371       DiagID = diag::err_fe_##GroupName;                                       \
372       break;                                                                   \
373     case llvm::DS_Warning:                                                     \
374       DiagID = diag::warn_fe_##GroupName;                                      \
375       break;                                                                   \
376     case llvm::DS_Remark:                                                      \
377       DiagID = diag::remark_fe_##GroupName;                                    \
378       break;                                                                   \
379     case llvm::DS_Note:                                                        \
380       DiagID = diag::note_fe_##GroupName;                                      \
381       break;                                                                   \
382     }                                                                          \
383   } while (false)
384
385 bool
386 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
387   unsigned DiagID;
388   ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
389   std::string Message = D.getMsgStr().str();
390
391   // If this problem has clang-level source location information, report the
392   // issue as being a problem in the source with a note showing the instantiated
393   // code.
394   SourceLocation LocCookie =
395       SourceLocation::getFromRawEncoding(D.getLocCookie());
396   if (LocCookie.isValid())
397     Diags.Report(LocCookie, DiagID).AddString(Message);
398   else {
399     // Otherwise, report the backend diagnostic as occurring in the generated
400     // .s file.
401     // If Loc is invalid, we still need to report the diagnostic, it just gets
402     // no location info.
403     FullSourceLoc Loc;
404     Diags.Report(Loc, DiagID).AddString(Message);
405   }
406   // We handled all the possible severities.
407   return true;
408 }
409
410 bool
411 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
412   if (D.getSeverity() != llvm::DS_Warning)
413     // For now, the only support we have for StackSize diagnostic is warning.
414     // We do not know how to format other severities.
415     return false;
416
417   if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
418     Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
419                  diag::warn_fe_frame_larger_than)
420         << D.getStackSize() << Decl::castToDeclContext(ND);
421     return true;
422   }
423
424   return false;
425 }
426
427 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
428     const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
429                                 unsigned &Line, unsigned &Column) const {
430   SourceManager &SourceMgr = Context->getSourceManager();
431   FileManager &FileMgr = SourceMgr.getFileManager();
432   SourceLocation DILoc;
433
434   if (D.isLocationAvailable()) {
435     D.getLocation(&Filename, &Line, &Column);
436     const FileEntry *FE = FileMgr.getFile(Filename);
437     if (FE && Line > 0) {
438       // If -gcolumn-info was not used, Column will be 0. This upsets the
439       // source manager, so pass 1 if Column is not set.
440       DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
441     }
442     BadDebugInfo = DILoc.isInvalid();
443   }
444
445   // If a location isn't available, try to approximate it using the associated
446   // function definition. We use the definition's right brace to differentiate
447   // from diagnostics that genuinely relate to the function itself.
448   FullSourceLoc Loc(DILoc, SourceMgr);
449   if (Loc.isInvalid())
450     if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
451       Loc = FD->getASTContext().getFullLoc(FD->getLocation());
452
453   if (DILoc.isInvalid() && D.isLocationAvailable())
454     // If we were not able to translate the file:line:col information
455     // back to a SourceLocation, at least emit a note stating that
456     // we could not translate this location. This can happen in the
457     // case of #line directives.
458     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
459         << Filename << Line << Column;
460
461   return Loc;
462 }
463
464 void BackendConsumer::UnsupportedDiagHandler(
465     const llvm::DiagnosticInfoUnsupported &D) {
466   // We only support errors.
467   assert(D.getSeverity() == llvm::DS_Error);
468
469   StringRef Filename;
470   unsigned Line, Column;
471   bool BadDebugInfo;
472   FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
473       Line, Column);
474
475   Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
476
477   if (BadDebugInfo)
478     // If we were not able to translate the file:line:col information
479     // back to a SourceLocation, at least emit a note stating that
480     // we could not translate this location. This can happen in the
481     // case of #line directives.
482     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
483         << Filename << Line << Column;
484 }
485
486 void BackendConsumer::EmitOptimizationMessage(
487     const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
488   // We only support warnings and remarks.
489   assert(D.getSeverity() == llvm::DS_Remark ||
490          D.getSeverity() == llvm::DS_Warning);
491
492   StringRef Filename;
493   unsigned Line, Column;
494   bool BadDebugInfo = false;
495   FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
496       Line, Column);
497
498   Diags.Report(Loc, DiagID)
499       << AddFlagValue(D.getPassName() ? D.getPassName() : "")
500       << D.getMsg().str();
501
502   if (BadDebugInfo)
503     // If we were not able to translate the file:line:col information
504     // back to a SourceLocation, at least emit a note stating that
505     // we could not translate this location. This can happen in the
506     // case of #line directives.
507     Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
508         << Filename << Line << Column;
509 }
510
511 void BackendConsumer::OptimizationRemarkHandler(
512     const llvm::DiagnosticInfoOptimizationRemark &D) {
513   // Optimization remarks are active only if the -Rpass flag has a regular
514   // expression that matches the name of the pass name in \p D.
515   if (CodeGenOpts.OptimizationRemarkPattern &&
516       CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
517     EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
518 }
519
520 void BackendConsumer::OptimizationRemarkHandler(
521     const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
522   // Missed optimization remarks are active only if the -Rpass-missed
523   // flag has a regular expression that matches the name of the pass
524   // name in \p D.
525   if (CodeGenOpts.OptimizationRemarkMissedPattern &&
526       CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
527     EmitOptimizationMessage(D,
528                             diag::remark_fe_backend_optimization_remark_missed);
529 }
530
531 void BackendConsumer::OptimizationRemarkHandler(
532     const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
533   // Optimization analysis remarks are active if the pass name is set to
534   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
535   // regular expression that matches the name of the pass name in \p D.
536
537   if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
538       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
539        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
540     EmitOptimizationMessage(
541         D, diag::remark_fe_backend_optimization_remark_analysis);
542 }
543
544 void BackendConsumer::OptimizationRemarkHandler(
545     const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
546   // Optimization analysis remarks are active if the pass name is set to
547   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
548   // regular expression that matches the name of the pass name in \p D.
549
550   if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
551       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
552        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
553     EmitOptimizationMessage(
554         D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
555 }
556
557 void BackendConsumer::OptimizationRemarkHandler(
558     const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
559   // Optimization analysis remarks are active if the pass name is set to
560   // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
561   // regular expression that matches the name of the pass name in \p D.
562
563   if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
564       (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
565        CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
566     EmitOptimizationMessage(
567         D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
568 }
569
570 void BackendConsumer::OptimizationFailureHandler(
571     const llvm::DiagnosticInfoOptimizationFailure &D) {
572   EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
573 }
574
575 /// \brief This function is invoked when the backend needs
576 /// to report something to the user.
577 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
578   unsigned DiagID = diag::err_fe_inline_asm;
579   llvm::DiagnosticSeverity Severity = DI.getSeverity();
580   // Get the diagnostic ID based.
581   switch (DI.getKind()) {
582   case llvm::DK_InlineAsm:
583     if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
584       return;
585     ComputeDiagID(Severity, inline_asm, DiagID);
586     break;
587   case llvm::DK_StackSize:
588     if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
589       return;
590     ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
591     break;
592   case DK_Linker:
593     assert(CurLinkModule);
594     // FIXME: stop eating the warnings and notes.
595     if (Severity != DS_Error)
596       return;
597     DiagID = diag::err_fe_cannot_link_module;
598     break;
599   case llvm::DK_OptimizationRemark:
600     // Optimization remarks are always handled completely by this
601     // handler. There is no generic way of emitting them.
602     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
603     return;
604   case llvm::DK_OptimizationRemarkMissed:
605     // Optimization remarks are always handled completely by this
606     // handler. There is no generic way of emitting them.
607     OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
608     return;
609   case llvm::DK_OptimizationRemarkAnalysis:
610     // Optimization remarks are always handled completely by this
611     // handler. There is no generic way of emitting them.
612     OptimizationRemarkHandler(
613         cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
614     return;
615   case llvm::DK_OptimizationRemarkAnalysisFPCommute:
616     // Optimization remarks are always handled completely by this
617     // handler. There is no generic way of emitting them.
618     OptimizationRemarkHandler(
619         cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
620     return;
621   case llvm::DK_OptimizationRemarkAnalysisAliasing:
622     // Optimization remarks are always handled completely by this
623     // handler. There is no generic way of emitting them.
624     OptimizationRemarkHandler(
625         cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
626     return;
627   case llvm::DK_OptimizationFailure:
628     // Optimization failures are always handled completely by this
629     // handler.
630     OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
631     return;
632   case llvm::DK_Unsupported:
633     UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
634     return;
635   default:
636     // Plugin IDs are not bound to any value as they are set dynamically.
637     ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
638     break;
639   }
640   std::string MsgStorage;
641   {
642     raw_string_ostream Stream(MsgStorage);
643     DiagnosticPrinterRawOStream DP(Stream);
644     DI.print(DP);
645   }
646
647   if (DiagID == diag::err_fe_cannot_link_module) {
648     Diags.Report(diag::err_fe_cannot_link_module)
649         << CurLinkModule->getModuleIdentifier() << MsgStorage;
650     return;
651   }
652
653   // Report the backend message using the usual diagnostic mechanism.
654   FullSourceLoc Loc;
655   Diags.Report(Loc, DiagID).AddString(MsgStorage);
656 }
657 #undef ComputeDiagID
658
659 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
660     : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
661       OwnsVMContext(!_VMContext) {}
662
663 CodeGenAction::~CodeGenAction() {
664   TheModule.reset();
665   if (OwnsVMContext)
666     delete VMContext;
667 }
668
669 bool CodeGenAction::hasIRSupport() const { return true; }
670
671 void CodeGenAction::EndSourceFileAction() {
672   // If the consumer creation failed, do nothing.
673   if (!getCompilerInstance().hasASTConsumer())
674     return;
675
676   // Take back ownership of link modules we passed to consumer.
677   if (!LinkModules.empty())
678     BEConsumer->releaseLinkModules();
679
680   // Steal the module from the consumer.
681   TheModule = BEConsumer->takeModule();
682 }
683
684 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
685   return std::move(TheModule);
686 }
687
688 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
689   OwnsVMContext = false;
690   return VMContext;
691 }
692
693 static raw_pwrite_stream *
694 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
695   switch (Action) {
696   case Backend_EmitAssembly:
697     return CI.createDefaultOutputFile(false, InFile, "s");
698   case Backend_EmitLL:
699     return CI.createDefaultOutputFile(false, InFile, "ll");
700   case Backend_EmitBC:
701     return CI.createDefaultOutputFile(true, InFile, "bc");
702   case Backend_EmitNothing:
703     return nullptr;
704   case Backend_EmitMCNull:
705     return CI.createNullOutputFile();
706   case Backend_EmitObj:
707     return CI.createDefaultOutputFile(true, InFile, "o");
708   }
709
710   llvm_unreachable("Invalid action!");
711 }
712
713 std::unique_ptr<ASTConsumer>
714 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
715   BackendAction BA = static_cast<BackendAction>(Act);
716   raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
717   if (BA != Backend_EmitNothing && !OS)
718     return nullptr;
719
720   // Load bitcode modules to link with, if we need to.
721   if (LinkModules.empty())
722     for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
723       const std::string &LinkBCFile = I.second;
724
725       auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
726       if (!BCBuf) {
727         CI.getDiagnostics().Report(diag::err_cannot_open_file)
728             << LinkBCFile << BCBuf.getError().message();
729         LinkModules.clear();
730         return nullptr;
731       }
732
733       ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
734           getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
735       if (std::error_code EC = ModuleOrErr.getError()) {
736         CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
737                                                                << EC.message();
738         LinkModules.clear();
739         return nullptr;
740       }
741       addLinkModule(ModuleOrErr.get().release(), I.first);
742     }
743
744   CoverageSourceInfo *CoverageInfo = nullptr;
745   // Add the preprocessor callback only when the coverage mapping is generated.
746   if (CI.getCodeGenOpts().CoverageMapping) {
747     CoverageInfo = new CoverageSourceInfo;
748     CI.getPreprocessor().addPPCallbacks(
749                                     std::unique_ptr<PPCallbacks>(CoverageInfo));
750   }
751
752   std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
753       BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
754       CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
755       CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
756       OS, *VMContext, CoverageInfo));
757   BEConsumer = Result.get();
758   return std::move(Result);
759 }
760
761 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
762                                          void *Context,
763                                          unsigned LocCookie) {
764   SM.print(nullptr, llvm::errs());
765
766   auto Diags = static_cast<DiagnosticsEngine *>(Context);
767   unsigned DiagID;
768   switch (SM.getKind()) {
769   case llvm::SourceMgr::DK_Error:
770     DiagID = diag::err_fe_inline_asm;
771     break;
772   case llvm::SourceMgr::DK_Warning:
773     DiagID = diag::warn_fe_inline_asm;
774     break;
775   case llvm::SourceMgr::DK_Note:
776     DiagID = diag::note_fe_inline_asm;
777     break;
778   }
779
780   Diags->Report(DiagID).AddString("cannot compile inline asm");
781 }
782
783 void CodeGenAction::ExecuteAction() {
784   // If this is an IR file, we have to treat it specially.
785   if (getCurrentFileKind() == IK_LLVM_IR) {
786     BackendAction BA = static_cast<BackendAction>(Act);
787     CompilerInstance &CI = getCompilerInstance();
788     raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
789     if (BA != Backend_EmitNothing && !OS)
790       return;
791
792     bool Invalid;
793     SourceManager &SM = CI.getSourceManager();
794     FileID FID = SM.getMainFileID();
795     llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
796     if (Invalid)
797       return;
798
799     // For ThinLTO backend invocations, ensure that the context
800     // merges types based on ODR identifiers.
801     if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
802       VMContext->enableDebugTypeODRUniquing();
803
804     llvm::SMDiagnostic Err;
805     TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
806     if (!TheModule) {
807       // Translate from the diagnostic info to the SourceManager location if
808       // available.
809       // TODO: Unify this with ConvertBackendLocation()
810       SourceLocation Loc;
811       if (Err.getLineNo() > 0) {
812         assert(Err.getColumnNo() >= 0);
813         Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
814                                       Err.getLineNo(), Err.getColumnNo() + 1);
815       }
816
817       // Strip off a leading diagnostic code if there is one.
818       StringRef Msg = Err.getMessage();
819       if (Msg.startswith("error: "))
820         Msg = Msg.substr(7);
821
822       unsigned DiagID =
823           CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
824
825       CI.getDiagnostics().Report(Loc, DiagID) << Msg;
826       return;
827     }
828     const TargetOptions &TargetOpts = CI.getTargetOpts();
829     if (TheModule->getTargetTriple() != TargetOpts.Triple) {
830       CI.getDiagnostics().Report(SourceLocation(),
831                                  diag::warn_fe_override_module)
832           << TargetOpts.Triple;
833       TheModule->setTargetTriple(TargetOpts.Triple);
834     }
835
836     EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
837                  MainFile->getMemBufferRef());
838
839     LLVMContext &Ctx = TheModule->getContext();
840     Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
841                                       &CI.getDiagnostics());
842
843     EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
844                       CI.getLangOpts(), CI.getTarget().getDataLayout(),
845                       TheModule.get(), BA, OS);
846     return;
847   }
848
849   // Otherwise follow the normal AST path.
850   this->ASTFrontendAction::ExecuteAction();
851 }
852
853 //
854
855 void EmitAssemblyAction::anchor() { }
856 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
857   : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
858
859 void EmitBCAction::anchor() { }
860 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
861   : CodeGenAction(Backend_EmitBC, _VMContext) {}
862
863 void EmitLLVMAction::anchor() { }
864 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
865   : CodeGenAction(Backend_EmitLL, _VMContext) {}
866
867 void EmitLLVMOnlyAction::anchor() { }
868 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
869   : CodeGenAction(Backend_EmitNothing, _VMContext) {}
870
871 void EmitCodeGenOnlyAction::anchor() { }
872 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
873   : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
874
875 void EmitObjAction::anchor() { }
876 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
877   : CodeGenAction(Backend_EmitObj, _VMContext) {}