blob: 9bdbacd63f6240f32488bd9b5515c1606668d8ef [file] [log] [blame]
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
Daniel Dunbarc13935e2008-10-21 23:49:24 +00002//
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
Alex Lorenzee024992014-08-04 18:41:51 +000010#include "CoverageMappingGen.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000012#include "clang/AST/ASTContext.h"
Hans Wennborga926d842014-05-23 20:37:38 +000013#include "clang/AST/DeclCXX.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000014#include "clang/AST/DeclGroup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Basic/TargetInfo.h"
Daniel Dunbarc1b17292010-06-15 17:48:49 +000018#include "clang/CodeGen/BackendUtil.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/CodeGen/CodeGenAction.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000020#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000021#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/ADT/SmallString.h"
25#include "llvm/Bitcode/ReaderWriter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000026#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000027#include "llvm/IR/DiagnosticInfo.h"
28#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000031#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000032#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000033#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000034#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000036#include "llvm/Support/Timer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000037#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000038using namespace clang;
39using namespace llvm;
40
Nico Weber2992efa2011-01-25 20:34:14 +000041namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000042 class BackendConsumer : public ASTConsumer {
David Blaikie68e081d2011-12-20 02:48:34 +000043 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000044 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000045 BackendAction Action;
Daniel Dunbarde182242009-11-30 08:39:32 +000046 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000047 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000048 const LangOptions &LangOpts;
Rafael Espindola2f16bc12015-04-14 15:15:49 +000049 raw_pwrite_stream *AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000050 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000051
Chris Lattner263d64c2009-02-18 01:37:30 +000052 Timer LLVMIRGeneration;
Mike Stump11289f42009-09-09 15:08:12 +000053
Ahmed Charlesb8984322014-03-07 20:03:18 +000054 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000055
Artem Belevich5d40ae32015-10-27 17:56:59 +000056 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
57 LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000058
Rafael Espindola8ce88a52015-12-14 23:17:07 +000059 // This is here so that the diagnostic printer knows the module a diagnostic
60 // refers to.
61 llvm::Module *CurLinkModule = nullptr;
62
Mike Stump11289f42009-09-09 15:08:12 +000063 public:
Artem Belevich5d40ae32015-10-27 17:56:59 +000064 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)
Justin Bognercb082992015-05-22 22:16:55 +000073 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
74 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
Yaron Keren2f5ec2f2014-12-25 12:21:56 +000075 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
Adrian Prantle74f5252015-06-30 02:26:03 +000076 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Artem Belevich5d40ae32015-10-27 17:56:59 +000077 CodeGenOpts, C, CoverageInfo)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000078 llvm::TimePassesIsEnabled = TimePasses;
Artem Belevich5d40ae32015-10-27 17:56:59 +000079 for (auto &I : LinkModules)
80 this->LinkModules.push_back(
81 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
Chris Lattnerdeffa132009-02-18 01:23:44 +000082 }
Serge Pavlov41c1f792016-02-18 16:42:09 +000083 llvm::Module *getModule() const { return Gen->GetModule(); }
84 std::unique_ptr<llvm::Module> takeModule() {
85 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
86 }
Artem Belevich5d40ae32015-10-27 17:56:59 +000087 void releaseLinkModules() {
88 for (auto &I : LinkModules)
89 I.second.release();
90 }
Daniel Dunbar400a6932010-02-25 04:37:50 +000091
Craig Topper4f12f102014-03-12 06:41:41 +000092 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +000093 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +000094 }
95
Craig Topper4f12f102014-03-12 06:41:41 +000096 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +000097 assert(!Context && "initialized multiple times");
98
Chris Lattner5cf49fe2009-03-28 02:18:25 +000099 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000100
Daniel Dunbar8e705052009-11-30 08:39:52 +0000101 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000102 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000103
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000104 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000105
Daniel Dunbar8e705052009-11-30 08:39:52 +0000106 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000107 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000108 }
Mike Stump11289f42009-09-09 15:08:12 +0000109
Craig Topper4f12f102014-03-12 06:41:41 +0000110 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000111 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000112 Context->getSourceManager(),
113 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000114
Daniel Dunbar8e705052009-11-30 08:39:52 +0000115 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000116 LLVMIRGeneration.startTimer();
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000117
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000118 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000119
Daniel Dunbar8e705052009-11-30 08:39:52 +0000120 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000121 LLVMIRGeneration.stopTimer();
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000122
123 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000126 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000127 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000129 "LLVM IR generation of inline function");
Hans Wennborga926d842014-05-23 20:37:38 +0000130 if (llvm::TimePassesIsEnabled)
131 LLVMIRGeneration.startTimer();
132
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000133 Gen->HandleInlineFunctionDefinition(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000134
135 if (llvm::TimePassesIsEnabled)
136 LLVMIRGeneration.stopTimer();
137 }
138
Craig Topper4f12f102014-03-12 06:41:41 +0000139 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000140 {
Chris Lattnere46de752009-03-06 06:46:31 +0000141 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbar8e705052009-11-30 08:39:52 +0000142 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000143 LLVMIRGeneration.startTimer();
Chris Lattner263d64c2009-02-18 01:37:30 +0000144
Chris Lattnercf169832009-03-28 04:11:33 +0000145 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000146
Daniel Dunbar8e705052009-11-30 08:39:52 +0000147 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000148 LLVMIRGeneration.stopTimer();
149 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000150
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000151 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000152 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000153 return;
Mike Stump11289f42009-09-09 15:08:12 +0000154
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000155 // Install an inline asm handler so that diagnostics get printed through
156 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000157 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000158 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
159 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000160 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000161 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000162
Quentin Colombet728c5542014-02-06 18:30:43 +0000163 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
164 Ctx.getDiagnosticHandler();
165 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
166 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
167
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000168 // 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();
Serge Pavlov41c1f792016-02-18 16:42:09 +0000172 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000173 return;
174 }
175
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000176 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000177 C.getTargetInfo().getDataLayout(),
Serge Pavlov41c1f792016-02-18 16:42:09 +0000178 getModule(), Action, AsmOutStream);
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000179
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000180 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000181
182 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000183 }
Mike Stump11289f42009-09-09 15:08:12 +0000184
Craig Topper4f12f102014-03-12 06:41:41 +0000185 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000186 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
187 Context->getSourceManager(),
188 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000189 Gen->HandleTagDeclDefinition(D);
190 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000191
Craig Topper4f12f102014-03-12 06:41:41 +0000192 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000193 Gen->HandleTagDeclRequiredDefinition(D);
194 }
195
Craig Topper4f12f102014-03-12 06:41:41 +0000196 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000197 Gen->CompleteTentativeDefinition(D);
198 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000199
David Majnemer929025d2016-01-26 19:30:26 +0000200 void AssignInheritanceModel(CXXRecordDecl *RD) override {
201 Gen->AssignInheritanceModel(RD);
202 }
203
Nico Weberb6a5d052015-01-15 04:07:35 +0000204 void HandleVTable(CXXRecordDecl *RD) override {
205 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000206 }
207
Chris Lattner5ec32e72010-04-06 18:38:50 +0000208 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
209 unsigned LocCookie) {
210 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
211 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
212 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000213
Quentin Colombet728c5542014-02-06 18:30:43 +0000214 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
215 void *Context) {
216 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
217 }
218
Oliver Stannard91817852016-02-02 13:52:52 +0000219 /// Get the best possible source location to represent a diagnostic that
220 /// may have associated debug info.
221 const FullSourceLoc
222 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
223 bool &BadDebugInfo, StringRef &Filename,
224 unsigned &Line, unsigned &Column) const;
225
Chris Lattner5ec32e72010-04-06 18:38:50 +0000226 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
227 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000228
229 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
230 /// \brief Specialized handler for InlineAsm diagnostic.
231 /// \return True if the diagnostic has been successfully reported, false
232 /// otherwise.
233 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
234 /// \brief Specialized handler for StackSize diagnostic.
235 /// \return True if the diagnostic has been successfully reported, false
236 /// otherwise.
237 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000238 /// \brief Specialized handler for unsupported backend feature diagnostic.
239 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000240 /// \brief Specialized handlers for optimization remarks.
241 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000242 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000243 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
244 unsigned DiagID);
Diego Novillod23ec942014-05-29 19:55:06 +0000245 void
Diego Novillo829b1702014-04-16 16:54:24 +0000246 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000247 void OptimizationRemarkHandler(
248 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
249 void OptimizationRemarkHandler(
250 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000251 void OptimizationRemarkHandler(
252 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
Tyler Nowicki034baf62015-08-10 23:05:16 +0000253 void OptimizationRemarkHandler(
254 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000255 void OptimizationFailureHandler(
256 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000257 };
David Blaikie68e081d2011-12-20 02:48:34 +0000258
259 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000260}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000261
Chris Lattner79f67a72010-04-08 00:23:06 +0000262/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
263/// buffer to be a valid FullSourceLoc.
264static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
265 SourceManager &CSM) {
266 // Get both the clang and llvm source managers. The location is relative to
267 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000268 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000269 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000270
Chris Lattner79f67a72010-04-08 00:23:06 +0000271 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
272 // already owns its one and clang::SourceManager wants to own its one.
273 const MemoryBuffer *LBuf =
274 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000275
Chris Lattner79f67a72010-04-08 00:23:06 +0000276 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000277 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000278 std::unique_ptr<llvm::MemoryBuffer> CBuf =
279 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
280 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000281 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000282 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000283
Chris Lattner79f67a72010-04-08 00:23:06 +0000284 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000285 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000286 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000287 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000288 return FullSourceLoc(NewLoc, CSM);
289}
290
Chris Lattner6d672132010-04-06 17:52:14 +0000291
Chris Lattner5ec32e72010-04-06 18:38:50 +0000292/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
293/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000294/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000295void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
296 SourceLocation LocCookie) {
297 // There are a couple of different kinds of errors we could get here. First,
298 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000299
300 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000301 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000302 if (Message.startswith("error: "))
303 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000304
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000305 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000306 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000307 if (D.getLoc() != SMLoc())
308 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000309
Joey Gouly5798b262014-06-05 21:23:42 +0000310 unsigned DiagID;
311 switch (D.getKind()) {
312 case llvm::SourceMgr::DK_Error:
313 DiagID = diag::err_fe_inline_asm;
314 break;
315 case llvm::SourceMgr::DK_Warning:
316 DiagID = diag::warn_fe_inline_asm;
317 break;
318 case llvm::SourceMgr::DK_Note:
319 DiagID = diag::note_fe_inline_asm;
320 break;
321 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000322 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000323 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000324 // code.
325 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000326 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000327
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000328 if (D.getLoc().isValid()) {
329 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
330 // Convert the SMDiagnostic ranges into SourceRange and attach them
331 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000332 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000333 unsigned Column = D.getColumnNo();
334 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
335 Loc.getLocWithOffset(Range.second - Column));
336 }
337 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000338 return;
339 }
340
Joey Gouly5798b262014-06-05 21:23:42 +0000341 // Otherwise, report the backend issue as occurring in the generated .s file.
342 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000343 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000344 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000345}
346
Quentin Colombet728c5542014-02-06 18:30:43 +0000347#define ComputeDiagID(Severity, GroupName, DiagID) \
348 do { \
349 switch (Severity) { \
350 case llvm::DS_Error: \
351 DiagID = diag::err_fe_##GroupName; \
352 break; \
353 case llvm::DS_Warning: \
354 DiagID = diag::warn_fe_##GroupName; \
355 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000356 case llvm::DS_Remark: \
357 llvm_unreachable("'remark' severity not expected"); \
358 break; \
359 case llvm::DS_Note: \
360 DiagID = diag::note_fe_##GroupName; \
361 break; \
362 } \
363 } while (false)
364
365#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
366 do { \
367 switch (Severity) { \
368 case llvm::DS_Error: \
369 DiagID = diag::err_fe_##GroupName; \
370 break; \
371 case llvm::DS_Warning: \
372 DiagID = diag::warn_fe_##GroupName; \
373 break; \
374 case llvm::DS_Remark: \
375 DiagID = diag::remark_fe_##GroupName; \
376 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000377 case llvm::DS_Note: \
378 DiagID = diag::note_fe_##GroupName; \
379 break; \
380 } \
381 } while (false)
382
383bool
384BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
385 unsigned DiagID;
386 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
387 std::string Message = D.getMsgStr().str();
388
389 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000390 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000391 // code.
392 SourceLocation LocCookie =
393 SourceLocation::getFromRawEncoding(D.getLocCookie());
394 if (LocCookie.isValid())
395 Diags.Report(LocCookie, DiagID).AddString(Message);
396 else {
397 // Otherwise, report the backend diagnostic as occurring in the generated
398 // .s file.
399 // If Loc is invalid, we still need to report the diagnostic, it just gets
400 // no location info.
401 FullSourceLoc Loc;
402 Diags.Report(Loc, DiagID).AddString(Message);
403 }
404 // We handled all the possible severities.
405 return true;
406}
407
408bool
409BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
410 if (D.getSeverity() != llvm::DS_Warning)
411 // For now, the only support we have for StackSize diagnostic is warning.
412 // We do not know how to format other severities.
413 return false;
414
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000415 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
416 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
417 diag::warn_fe_frame_larger_than)
418 << D.getStackSize() << Decl::castToDeclContext(ND);
419 return true;
420 }
421
422 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000423}
424
Oliver Stannard91817852016-02-02 13:52:52 +0000425const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
426 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
427 unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000428 SourceManager &SourceMgr = Context->getSourceManager();
429 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000430 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000431
432 if (D.isLocationAvailable()) {
433 D.getLocation(&Filename, &Line, &Column);
434 const FileEntry *FE = FileMgr.getFile(Filename);
435 if (FE && Line > 0) {
436 // If -gcolumn-info was not used, Column will be 0. This upsets the
437 // source manager, so pass 1 if Column is not set.
438 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
439 }
Oliver Stannard91817852016-02-02 13:52:52 +0000440 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000441 }
Alp Toker27506272014-06-05 22:11:12 +0000442
443 // If a location isn't available, try to approximate it using the associated
444 // function definition. We use the definition's right brace to differentiate
445 // from diagnostics that genuinely relate to the function itself.
446 FullSourceLoc Loc(DILoc, SourceMgr);
447 if (Loc.isInvalid())
448 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000449 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000450
Diego Novillo86f884e2015-05-08 20:59:56 +0000451 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000452 // If we were not able to translate the file:line:col information
453 // back to a SourceLocation, at least emit a note stating that
454 // we could not translate this location. This can happen in the
455 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000456 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
457 << Filename << Line;
458
459 return Loc;
460}
461
462void BackendConsumer::UnsupportedDiagHandler(
463 const llvm::DiagnosticInfoUnsupported &D) {
464 // We only support errors.
465 assert(D.getSeverity() == llvm::DS_Error);
466
467 StringRef Filename;
468 unsigned Line, Column;
469 bool BadDebugInfo;
470 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
471 Line, Column);
472
473 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
474
475 if (BadDebugInfo)
476 // If we were not able to translate the file:line:col information
477 // back to a SourceLocation, at least emit a note stating that
478 // we could not translate this location. This can happen in the
479 // case of #line directives.
480 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
481 << Filename << Line << Column;
482}
483
484void BackendConsumer::EmitOptimizationMessage(
485 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
486 // We only support warnings and remarks.
487 assert(D.getSeverity() == llvm::DS_Remark ||
488 D.getSeverity() == llvm::DS_Warning);
489
490 StringRef Filename;
491 unsigned Line, Column;
492 bool BadDebugInfo = false;
493 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
494 Line, Column);
495
496 Diags.Report(Loc, DiagID)
497 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
498 << D.getMsg().str();
499
500 if (BadDebugInfo)
501 // If we were not able to translate the file:line:col information
502 // back to a SourceLocation, at least emit a note stating that
503 // we could not translate this location. This can happen in the
504 // case of #line directives.
505 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000506 << Filename << Line << Column;
507}
508
509void BackendConsumer::OptimizationRemarkHandler(
510 const llvm::DiagnosticInfoOptimizationRemark &D) {
511 // Optimization remarks are active only if the -Rpass flag has a regular
512 // expression that matches the name of the pass name in \p D.
513 if (CodeGenOpts.OptimizationRemarkPattern &&
514 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000515 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
Diego Novillod23ec942014-05-29 19:55:06 +0000516}
517
518void BackendConsumer::OptimizationRemarkHandler(
519 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
520 // Missed optimization remarks are active only if the -Rpass-missed
521 // flag has a regular expression that matches the name of the pass
522 // name in \p D.
523 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
524 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000525 EmitOptimizationMessage(D,
526 diag::remark_fe_backend_optimization_remark_missed);
Diego Novillod23ec942014-05-29 19:55:06 +0000527}
528
529void BackendConsumer::OptimizationRemarkHandler(
530 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000531 // Optimization analysis remarks are active if the pass name is set to
532 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
533 // regular expression that matches the name of the pass name in \p D.
534
535 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
536 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
537 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000538 EmitOptimizationMessage(
Diego Novillod23ec942014-05-29 19:55:06 +0000539 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000540}
541
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000542void BackendConsumer::OptimizationRemarkHandler(
543 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000544 // Optimization analysis remarks are active if the pass name is set to
545 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
546 // regular expression that matches the name of the pass name in \p D.
547
548 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
549 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
550 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000551 EmitOptimizationMessage(
552 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
553}
554
Tyler Nowicki034baf62015-08-10 23:05:16 +0000555void BackendConsumer::OptimizationRemarkHandler(
556 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000557 // Optimization analysis remarks are active if the pass name is set to
558 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
559 // regular expression that matches the name of the pass name in \p D.
560
561 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
562 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
563 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000564 EmitOptimizationMessage(
565 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
566}
567
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000568void BackendConsumer::OptimizationFailureHandler(
569 const llvm::DiagnosticInfoOptimizationFailure &D) {
570 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
571}
572
Quentin Colombet728c5542014-02-06 18:30:43 +0000573/// \brief This function is invoked when the backend needs
574/// to report something to the user.
575void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
576 unsigned DiagID = diag::err_fe_inline_asm;
577 llvm::DiagnosticSeverity Severity = DI.getSeverity();
578 // Get the diagnostic ID based.
579 switch (DI.getKind()) {
580 case llvm::DK_InlineAsm:
581 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
582 return;
583 ComputeDiagID(Severity, inline_asm, DiagID);
584 break;
585 case llvm::DK_StackSize:
586 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
587 return;
588 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
589 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000590 case DK_Linker:
591 assert(CurLinkModule);
592 // FIXME: stop eating the warnings and notes.
593 if (Severity != DS_Error)
594 return;
595 DiagID = diag::err_fe_cannot_link_module;
596 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000597 case llvm::DK_OptimizationRemark:
598 // Optimization remarks are always handled completely by this
599 // handler. There is no generic way of emitting them.
600 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
601 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000602 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000603 // Optimization remarks are always handled completely by this
604 // handler. There is no generic way of emitting them.
605 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
606 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000607 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000608 // Optimization remarks are always handled completely by this
609 // handler. There is no generic way of emitting them.
610 OptimizationRemarkHandler(
611 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000612 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000613 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
614 // Optimization remarks are always handled completely by this
615 // handler. There is no generic way of emitting them.
616 OptimizationRemarkHandler(
617 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
618 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000619 case llvm::DK_OptimizationRemarkAnalysisAliasing:
620 // Optimization remarks are always handled completely by this
621 // handler. There is no generic way of emitting them.
622 OptimizationRemarkHandler(
623 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
624 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000625 case llvm::DK_OptimizationFailure:
626 // Optimization failures are always handled completely by this
627 // handler.
628 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
629 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000630 case llvm::DK_Unsupported:
631 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
632 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000633 default:
634 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000635 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000636 break;
637 }
638 std::string MsgStorage;
639 {
640 raw_string_ostream Stream(MsgStorage);
641 DiagnosticPrinterRawOStream DP(Stream);
642 DI.print(DP);
643 }
644
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000645 if (DiagID == diag::err_fe_cannot_link_module) {
646 Diags.Report(diag::err_fe_cannot_link_module)
647 << CurLinkModule->getModuleIdentifier() << MsgStorage;
648 return;
649 }
650
Quentin Colombet728c5542014-02-06 18:30:43 +0000651 // Report the backend message using the usual diagnostic mechanism.
652 FullSourceLoc Loc;
653 Diags.Report(Loc, DiagID).AddString(MsgStorage);
654}
655#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000656
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000657CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000658 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000659 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000660
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000661CodeGenAction::~CodeGenAction() {
662 TheModule.reset();
663 if (OwnsVMContext)
664 delete VMContext;
665}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000666
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000667bool CodeGenAction::hasIRSupport() const { return true; }
668
Daniel Dunbar400a6932010-02-25 04:37:50 +0000669void CodeGenAction::EndSourceFileAction() {
670 // If the consumer creation failed, do nothing.
671 if (!getCompilerInstance().hasASTConsumer())
672 return;
673
Artem Belevich5d40ae32015-10-27 17:56:59 +0000674 // Take back ownership of link modules we passed to consumer.
675 if (!LinkModules.empty())
676 BEConsumer->releaseLinkModules();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000677
Daniel Dunbar400a6932010-02-25 04:37:50 +0000678 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000679 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000680}
681
Rafael Espindolae8337302014-08-19 14:36:35 +0000682std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
683 return std::move(TheModule);
684}
685
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000686llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
687 OwnsVMContext = false;
688 return VMContext;
689}
690
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000691static raw_pwrite_stream *
692GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000693 switch (Action) {
694 case Backend_EmitAssembly:
695 return CI.createDefaultOutputFile(false, InFile, "s");
696 case Backend_EmitLL:
697 return CI.createDefaultOutputFile(false, InFile, "ll");
698 case Backend_EmitBC:
699 return CI.createDefaultOutputFile(true, InFile, "bc");
700 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000701 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000702 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000703 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000704 case Backend_EmitObj:
705 return CI.createDefaultOutputFile(true, InFile, "o");
706 }
707
David Blaikie83d382b2011-09-23 05:06:16 +0000708 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000709}
710
David Blaikie6beb6aa2014-08-10 19:56:51 +0000711std::unique_ptr<ASTConsumer>
712CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000713 BackendAction BA = static_cast<BackendAction>(Act);
Artem Beleviched0577c2015-05-12 17:44:15 +0000714 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000715 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000716 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000717
Artem Belevich5d40ae32015-10-27 17:56:59 +0000718 // Load bitcode modules to link with, if we need to.
719 if (LinkModules.empty())
720 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
721 const std::string &LinkBCFile = I.second;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000722
Artem Belevich5d40ae32015-10-27 17:56:59 +0000723 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
724 if (!BCBuf) {
725 CI.getDiagnostics().Report(diag::err_cannot_open_file)
726 << LinkBCFile << BCBuf.getError().message();
727 LinkModules.clear();
728 return nullptr;
729 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000730
Artem Belevich5d40ae32015-10-27 17:56:59 +0000731 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
732 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
733 if (std::error_code EC = ModuleOrErr.getError()) {
734 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
735 << EC.message();
736 LinkModules.clear();
737 return nullptr;
738 }
739 addLinkModule(ModuleOrErr.get().release(), I.first);
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000740 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000741
Alex Lorenzee024992014-08-04 18:41:51 +0000742 CoverageSourceInfo *CoverageInfo = nullptr;
743 // Add the preprocessor callback only when the coverage mapping is generated.
744 if (CI.getCodeGenOpts().CoverageMapping) {
745 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000746 CI.getPreprocessor().addPPCallbacks(
747 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000748 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000749
David Blaikie037e75b2014-08-10 21:06:17 +0000750 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000751 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
752 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Artem Belevich5d40ae32015-10-27 17:56:59 +0000753 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
754 OS, *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000755 BEConsumer = Result.get();
756 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000757}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000758
Tim Northover1390b442016-04-06 19:58:07 +0000759static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
760 void *Context,
761 unsigned LocCookie) {
762 SM.print(nullptr, llvm::errs());
763
764 auto Diags = static_cast<DiagnosticsEngine *>(Context);
765 unsigned DiagID;
766 switch (SM.getKind()) {
767 case llvm::SourceMgr::DK_Error:
768 DiagID = diag::err_fe_inline_asm;
769 break;
770 case llvm::SourceMgr::DK_Warning:
771 DiagID = diag::warn_fe_inline_asm;
772 break;
773 case llvm::SourceMgr::DK_Note:
774 DiagID = diag::note_fe_inline_asm;
775 break;
776 }
777
778 Diags->Report(DiagID).AddString("cannot compile inline asm");
779}
780
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000781void CodeGenAction::ExecuteAction() {
782 // If this is an IR file, we have to treat it specially.
783 if (getCurrentFileKind() == IK_LLVM_IR) {
784 BackendAction BA = static_cast<BackendAction>(Act);
785 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000786 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000787 if (BA != Backend_EmitNothing && !OS)
788 return;
789
790 bool Invalid;
791 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000792 FileID FID = SM.getMainFileID();
793 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000794 if (Invalid)
795 return;
796
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000797 llvm::SMDiagnostic Err;
Rafael Espindola32327732014-08-26 21:49:29 +0000798 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000799 if (!TheModule) {
Alp Toker7b463d52014-06-30 01:33:59 +0000800 // Translate from the diagnostic info to the SourceManager location if
801 // available.
802 // TODO: Unify this with ConvertBackendLocation()
803 SourceLocation Loc;
804 if (Err.getLineNo() > 0) {
805 assert(Err.getColumnNo() >= 0);
806 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
807 Err.getLineNo(), Err.getColumnNo() + 1);
808 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000809
Alp Tokerbc043f22013-12-21 05:20:03 +0000810 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000811 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000812 if (Msg.startswith("error: "))
813 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000814
Alp Tokerbc043f22013-12-21 05:20:03 +0000815 unsigned DiagID =
816 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000817
Alp Tokerbc043f22013-12-21 05:20:03 +0000818 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000819 return;
820 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000821 const TargetOptions &TargetOpts = CI.getTargetOpts();
822 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000823 CI.getDiagnostics().Report(SourceLocation(),
824 diag::warn_fe_override_module)
825 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000826 TheModule->setTargetTriple(TargetOpts.Triple);
827 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000828
Tim Northover1390b442016-04-06 19:58:07 +0000829 LLVMContext &Ctx = TheModule->getContext();
830 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
831 &CI.getDiagnostics());
Alp Tokere83b9062014-01-02 15:08:04 +0000832 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000833 CI.getLangOpts(), CI.getTarget().getDataLayout(),
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000834 TheModule.get(), BA, OS);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000835 return;
836 }
837
838 // Otherwise follow the normal AST path.
839 this->ASTFrontendAction::ExecuteAction();
840}
841
842//
843
David Blaikie68e081d2011-12-20 02:48:34 +0000844void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000845EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
846 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000847
David Blaikie68e081d2011-12-20 02:48:34 +0000848void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000849EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
850 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000851
David Blaikie68e081d2011-12-20 02:48:34 +0000852void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000853EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
854 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000855
David Blaikie68e081d2011-12-20 02:48:34 +0000856void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000857EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
858 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000859
David Blaikie68e081d2011-12-20 02:48:34 +0000860void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000861EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
862 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000863
David Blaikie68e081d2011-12-20 02:48:34 +0000864void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000865EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
866 : CodeGenAction(Backend_EmitObj, _VMContext) {}