blob: 8861840516549cbf802c9673433c76afe4a6ddb4 [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
Steven Wu27fb5222016-05-11 16:26:03 +0000176 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
177
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000178 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000179 C.getTargetInfo().getDataLayout(),
Serge Pavlov41c1f792016-02-18 16:42:09 +0000180 getModule(), Action, AsmOutStream);
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000181
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000182 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000183
184 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000185 }
Mike Stump11289f42009-09-09 15:08:12 +0000186
Craig Topper4f12f102014-03-12 06:41:41 +0000187 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000188 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
189 Context->getSourceManager(),
190 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000191 Gen->HandleTagDeclDefinition(D);
192 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000193
Craig Topper4f12f102014-03-12 06:41:41 +0000194 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000195 Gen->HandleTagDeclRequiredDefinition(D);
196 }
197
Craig Topper4f12f102014-03-12 06:41:41 +0000198 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000199 Gen->CompleteTentativeDefinition(D);
200 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000201
David Majnemer929025d2016-01-26 19:30:26 +0000202 void AssignInheritanceModel(CXXRecordDecl *RD) override {
203 Gen->AssignInheritanceModel(RD);
204 }
205
Nico Weberb6a5d052015-01-15 04:07:35 +0000206 void HandleVTable(CXXRecordDecl *RD) override {
207 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000208 }
209
Chris Lattner5ec32e72010-04-06 18:38:50 +0000210 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 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000215
Quentin Colombet728c5542014-02-06 18:30:43 +0000216 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
217 void *Context) {
218 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
219 }
220
Oliver Stannard91817852016-02-02 13:52:52 +0000221 /// 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
Chris Lattner5ec32e72010-04-06 18:38:50 +0000228 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
229 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000230
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);
Oliver Stannard91817852016-02-02 13:52:52 +0000240 /// \brief Specialized handler for unsupported backend feature diagnostic.
241 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000242 /// \brief Specialized handlers for optimization remarks.
243 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000244 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000245 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
246 unsigned DiagID);
Diego Novillod23ec942014-05-29 19:55:06 +0000247 void
Diego Novillo829b1702014-04-16 16:54:24 +0000248 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000249 void OptimizationRemarkHandler(
250 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
251 void OptimizationRemarkHandler(
252 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000253 void OptimizationRemarkHandler(
254 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
Tyler Nowicki034baf62015-08-10 23:05:16 +0000255 void OptimizationRemarkHandler(
256 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000257 void OptimizationFailureHandler(
258 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000259 };
David Blaikie68e081d2011-12-20 02:48:34 +0000260
261 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000262}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000263
Chris Lattner79f67a72010-04-08 00:23:06 +0000264/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
265/// buffer to be a valid FullSourceLoc.
266static 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
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000270 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000271 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000272
Chris Lattner79f67a72010-04-08 00:23:06 +0000273 // 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()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000277
Chris Lattner79f67a72010-04-08 00:23:06 +0000278 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000279 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000280 std::unique_ptr<llvm::MemoryBuffer> CBuf =
281 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
282 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000283 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000284 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000285
Chris Lattner79f67a72010-04-08 00:23:06 +0000286 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000287 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000288 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000289 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000290 return FullSourceLoc(NewLoc, CSM);
291}
292
Chris Lattner6d672132010-04-06 17:52:14 +0000293
Chris Lattner5ec32e72010-04-06 18:38:50 +0000294/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
295/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000296/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000297void 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.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000301
302 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000304 if (Message.startswith("error: "))
305 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000306
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000307 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000308 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000309 if (D.getLoc() != SMLoc())
310 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000311
Joey Gouly5798b262014-06-05 21:23:42 +0000312 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 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000324 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000325 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000326 // code.
327 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000328 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000329
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000330 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.
Yaron Kerenede60302015-08-01 19:11:36 +0000334 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000335 unsigned Column = D.getColumnNo();
336 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
337 Loc.getLocWithOffset(Range.second - Column));
338 }
339 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000340 return;
341 }
342
Joey Gouly5798b262014-06-05 21:23:42 +0000343 // 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
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000345 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000346 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000347}
348
Quentin Colombet728c5542014-02-06 18:30:43 +0000349#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; \
Tobias Grosser74160242014-02-28 09:11:08 +0000358 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; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000379 case llvm::DS_Note: \
380 DiagID = diag::note_fe_##GroupName; \
381 break; \
382 } \
383 } while (false)
384
385bool
386BackendConsumer::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
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000392 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000393 // 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
410bool
411BackendConsumer::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
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000417 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000418 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000419 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
420 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000421 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000422 return true;
423 }
424
425 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000426}
427
Oliver Stannard91817852016-02-02 13:52:52 +0000428const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
429 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
430 unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000431 SourceManager &SourceMgr = Context->getSourceManager();
432 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000433 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000434
435 if (D.isLocationAvailable()) {
436 D.getLocation(&Filename, &Line, &Column);
437 const FileEntry *FE = FileMgr.getFile(Filename);
438 if (FE && Line > 0) {
439 // If -gcolumn-info was not used, Column will be 0. This upsets the
440 // source manager, so pass 1 if Column is not set.
441 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
442 }
Oliver Stannard91817852016-02-02 13:52:52 +0000443 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000444 }
Alp Toker27506272014-06-05 22:11:12 +0000445
446 // If a location isn't available, try to approximate it using the associated
447 // function definition. We use the definition's right brace to differentiate
448 // from diagnostics that genuinely relate to the function itself.
449 FullSourceLoc Loc(DILoc, SourceMgr);
450 if (Loc.isInvalid())
451 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000452 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000453
Diego Novillo86f884e2015-05-08 20:59:56 +0000454 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000455 // If we were not able to translate the file:line:col information
456 // back to a SourceLocation, at least emit a note stating that
457 // we could not translate this location. This can happen in the
458 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000459 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000460 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000461
462 return Loc;
463}
464
465void BackendConsumer::UnsupportedDiagHandler(
466 const llvm::DiagnosticInfoUnsupported &D) {
467 // We only support errors.
468 assert(D.getSeverity() == llvm::DS_Error);
469
470 StringRef Filename;
471 unsigned Line, Column;
472 bool BadDebugInfo;
473 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
474 Line, Column);
475
476 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
477
478 if (BadDebugInfo)
479 // If we were not able to translate the file:line:col information
480 // back to a SourceLocation, at least emit a note stating that
481 // we could not translate this location. This can happen in the
482 // case of #line directives.
483 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
484 << Filename << Line << Column;
485}
486
487void BackendConsumer::EmitOptimizationMessage(
488 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
489 // We only support warnings and remarks.
490 assert(D.getSeverity() == llvm::DS_Remark ||
491 D.getSeverity() == llvm::DS_Warning);
492
493 StringRef Filename;
494 unsigned Line, Column;
495 bool BadDebugInfo = false;
496 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
497 Line, Column);
498
499 Diags.Report(Loc, DiagID)
500 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
501 << D.getMsg().str();
502
503 if (BadDebugInfo)
504 // If we were not able to translate the file:line:col information
505 // back to a SourceLocation, at least emit a note stating that
506 // we could not translate this location. This can happen in the
507 // case of #line directives.
508 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000509 << Filename << Line << Column;
510}
511
512void BackendConsumer::OptimizationRemarkHandler(
513 const llvm::DiagnosticInfoOptimizationRemark &D) {
514 // Optimization remarks are active only if the -Rpass flag has a regular
515 // expression that matches the name of the pass name in \p D.
516 if (CodeGenOpts.OptimizationRemarkPattern &&
517 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000518 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
Diego Novillod23ec942014-05-29 19:55:06 +0000519}
520
521void BackendConsumer::OptimizationRemarkHandler(
522 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
523 // Missed optimization remarks are active only if the -Rpass-missed
524 // flag has a regular expression that matches the name of the pass
525 // name in \p D.
526 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
527 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000528 EmitOptimizationMessage(D,
529 diag::remark_fe_backend_optimization_remark_missed);
Diego Novillod23ec942014-05-29 19:55:06 +0000530}
531
532void BackendConsumer::OptimizationRemarkHandler(
533 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000534 // Optimization analysis remarks are active if the pass name is set to
535 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
536 // regular expression that matches the name of the pass name in \p D.
537
538 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
539 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
540 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000541 EmitOptimizationMessage(
Diego Novillod23ec942014-05-29 19:55:06 +0000542 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000543}
544
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000545void BackendConsumer::OptimizationRemarkHandler(
546 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000547 // Optimization analysis remarks are active if the pass name is set to
548 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
549 // regular expression that matches the name of the pass name in \p D.
550
551 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
552 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
553 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000554 EmitOptimizationMessage(
555 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
556}
557
Tyler Nowicki034baf62015-08-10 23:05:16 +0000558void BackendConsumer::OptimizationRemarkHandler(
559 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000560 // Optimization analysis remarks are active if the pass name is set to
561 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
562 // regular expression that matches the name of the pass name in \p D.
563
564 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
565 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
566 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000567 EmitOptimizationMessage(
568 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
569}
570
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000571void BackendConsumer::OptimizationFailureHandler(
572 const llvm::DiagnosticInfoOptimizationFailure &D) {
573 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
574}
575
Quentin Colombet728c5542014-02-06 18:30:43 +0000576/// \brief This function is invoked when the backend needs
577/// to report something to the user.
578void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
579 unsigned DiagID = diag::err_fe_inline_asm;
580 llvm::DiagnosticSeverity Severity = DI.getSeverity();
581 // Get the diagnostic ID based.
582 switch (DI.getKind()) {
583 case llvm::DK_InlineAsm:
584 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
585 return;
586 ComputeDiagID(Severity, inline_asm, DiagID);
587 break;
588 case llvm::DK_StackSize:
589 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
590 return;
591 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
592 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000593 case DK_Linker:
594 assert(CurLinkModule);
595 // FIXME: stop eating the warnings and notes.
596 if (Severity != DS_Error)
597 return;
598 DiagID = diag::err_fe_cannot_link_module;
599 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000600 case llvm::DK_OptimizationRemark:
601 // Optimization remarks are always handled completely by this
602 // handler. There is no generic way of emitting them.
603 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
604 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000605 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000606 // Optimization remarks are always handled completely by this
607 // handler. There is no generic way of emitting them.
608 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
609 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000610 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000611 // Optimization remarks are always handled completely by this
612 // handler. There is no generic way of emitting them.
613 OptimizationRemarkHandler(
614 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000615 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000616 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
617 // Optimization remarks are always handled completely by this
618 // handler. There is no generic way of emitting them.
619 OptimizationRemarkHandler(
620 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
621 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000622 case llvm::DK_OptimizationRemarkAnalysisAliasing:
623 // Optimization remarks are always handled completely by this
624 // handler. There is no generic way of emitting them.
625 OptimizationRemarkHandler(
626 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
627 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000628 case llvm::DK_OptimizationFailure:
629 // Optimization failures are always handled completely by this
630 // handler.
631 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
632 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000633 case llvm::DK_Unsupported:
634 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
635 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000636 default:
637 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000638 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000639 break;
640 }
641 std::string MsgStorage;
642 {
643 raw_string_ostream Stream(MsgStorage);
644 DiagnosticPrinterRawOStream DP(Stream);
645 DI.print(DP);
646 }
647
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000648 if (DiagID == diag::err_fe_cannot_link_module) {
649 Diags.Report(diag::err_fe_cannot_link_module)
650 << CurLinkModule->getModuleIdentifier() << MsgStorage;
651 return;
652 }
653
Quentin Colombet728c5542014-02-06 18:30:43 +0000654 // Report the backend message using the usual diagnostic mechanism.
655 FullSourceLoc Loc;
656 Diags.Report(Loc, DiagID).AddString(MsgStorage);
657}
658#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000659
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000660CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000661 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000662 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000663
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000664CodeGenAction::~CodeGenAction() {
665 TheModule.reset();
666 if (OwnsVMContext)
667 delete VMContext;
668}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000669
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000670bool CodeGenAction::hasIRSupport() const { return true; }
671
Daniel Dunbar400a6932010-02-25 04:37:50 +0000672void CodeGenAction::EndSourceFileAction() {
673 // If the consumer creation failed, do nothing.
674 if (!getCompilerInstance().hasASTConsumer())
675 return;
676
Artem Belevich5d40ae32015-10-27 17:56:59 +0000677 // Take back ownership of link modules we passed to consumer.
678 if (!LinkModules.empty())
679 BEConsumer->releaseLinkModules();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000680
Daniel Dunbar400a6932010-02-25 04:37:50 +0000681 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000682 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000683}
684
Rafael Espindolae8337302014-08-19 14:36:35 +0000685std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
686 return std::move(TheModule);
687}
688
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000689llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
690 OwnsVMContext = false;
691 return VMContext;
692}
693
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000694static raw_pwrite_stream *
695GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000696 switch (Action) {
697 case Backend_EmitAssembly:
698 return CI.createDefaultOutputFile(false, InFile, "s");
699 case Backend_EmitLL:
700 return CI.createDefaultOutputFile(false, InFile, "ll");
701 case Backend_EmitBC:
702 return CI.createDefaultOutputFile(true, InFile, "bc");
703 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000704 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000705 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000706 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000707 case Backend_EmitObj:
708 return CI.createDefaultOutputFile(true, InFile, "o");
709 }
710
David Blaikie83d382b2011-09-23 05:06:16 +0000711 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000712}
713
David Blaikie6beb6aa2014-08-10 19:56:51 +0000714std::unique_ptr<ASTConsumer>
715CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000716 BackendAction BA = static_cast<BackendAction>(Act);
Artem Beleviched0577c2015-05-12 17:44:15 +0000717 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000718 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000719 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000720
Artem Belevich5d40ae32015-10-27 17:56:59 +0000721 // Load bitcode modules to link with, if we need to.
722 if (LinkModules.empty())
723 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
724 const std::string &LinkBCFile = I.second;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000725
Artem Belevich5d40ae32015-10-27 17:56:59 +0000726 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
727 if (!BCBuf) {
728 CI.getDiagnostics().Report(diag::err_cannot_open_file)
729 << LinkBCFile << BCBuf.getError().message();
730 LinkModules.clear();
731 return nullptr;
732 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000733
Artem Belevich5d40ae32015-10-27 17:56:59 +0000734 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
735 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
736 if (std::error_code EC = ModuleOrErr.getError()) {
737 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
738 << EC.message();
739 LinkModules.clear();
740 return nullptr;
741 }
742 addLinkModule(ModuleOrErr.get().release(), I.first);
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000743 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000744
Alex Lorenzee024992014-08-04 18:41:51 +0000745 CoverageSourceInfo *CoverageInfo = nullptr;
746 // Add the preprocessor callback only when the coverage mapping is generated.
747 if (CI.getCodeGenOpts().CoverageMapping) {
748 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000749 CI.getPreprocessor().addPPCallbacks(
750 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000751 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000752
David Blaikie037e75b2014-08-10 21:06:17 +0000753 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000754 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
755 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Artem Belevich5d40ae32015-10-27 17:56:59 +0000756 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
757 OS, *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000758 BEConsumer = Result.get();
759 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000760}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000761
Tim Northover1390b442016-04-06 19:58:07 +0000762static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
763 void *Context,
764 unsigned LocCookie) {
765 SM.print(nullptr, llvm::errs());
766
767 auto Diags = static_cast<DiagnosticsEngine *>(Context);
768 unsigned DiagID;
769 switch (SM.getKind()) {
770 case llvm::SourceMgr::DK_Error:
771 DiagID = diag::err_fe_inline_asm;
772 break;
773 case llvm::SourceMgr::DK_Warning:
774 DiagID = diag::warn_fe_inline_asm;
775 break;
776 case llvm::SourceMgr::DK_Note:
777 DiagID = diag::note_fe_inline_asm;
778 break;
779 }
780
781 Diags->Report(DiagID).AddString("cannot compile inline asm");
782}
783
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000784void CodeGenAction::ExecuteAction() {
785 // If this is an IR file, we have to treat it specially.
786 if (getCurrentFileKind() == IK_LLVM_IR) {
787 BackendAction BA = static_cast<BackendAction>(Act);
788 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000789 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000790 if (BA != Backend_EmitNothing && !OS)
791 return;
792
793 bool Invalid;
794 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000795 FileID FID = SM.getMainFileID();
796 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000797 if (Invalid)
798 return;
799
Teresa Johnsonb1047492016-04-20 02:23:52 +0000800 // For ThinLTO backend invocations, ensure that the context
801 // merges types based on ODR identifiers.
802 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
803 VMContext->enableDebugTypeODRUniquing();
804
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000805 llvm::SMDiagnostic Err;
Rafael Espindola32327732014-08-26 21:49:29 +0000806 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000807 if (!TheModule) {
Alp Toker7b463d52014-06-30 01:33:59 +0000808 // Translate from the diagnostic info to the SourceManager location if
809 // available.
810 // TODO: Unify this with ConvertBackendLocation()
811 SourceLocation Loc;
812 if (Err.getLineNo() > 0) {
813 assert(Err.getColumnNo() >= 0);
814 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
815 Err.getLineNo(), Err.getColumnNo() + 1);
816 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000817
Alp Tokerbc043f22013-12-21 05:20:03 +0000818 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000819 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000820 if (Msg.startswith("error: "))
821 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000822
Alp Tokerbc043f22013-12-21 05:20:03 +0000823 unsigned DiagID =
824 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000825
Alp Tokerbc043f22013-12-21 05:20:03 +0000826 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000827 return;
828 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000829 const TargetOptions &TargetOpts = CI.getTargetOpts();
830 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000831 CI.getDiagnostics().Report(SourceLocation(),
832 diag::warn_fe_override_module)
833 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000834 TheModule->setTargetTriple(TargetOpts.Triple);
835 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000836
Steven Wu27fb5222016-05-11 16:26:03 +0000837 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
838 MainFile->getMemBufferRef());
839
Tim Northover1390b442016-04-06 19:58:07 +0000840 LLVMContext &Ctx = TheModule->getContext();
841 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
842 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000843
Alp Tokere83b9062014-01-02 15:08:04 +0000844 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000845 CI.getLangOpts(), CI.getTarget().getDataLayout(),
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000846 TheModule.get(), BA, OS);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000847 return;
848 }
849
850 // Otherwise follow the normal AST path.
851 this->ASTFrontendAction::ExecuteAction();
852}
853
854//
855
David Blaikie68e081d2011-12-20 02:48:34 +0000856void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000857EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
858 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000859
David Blaikie68e081d2011-12-20 02:48:34 +0000860void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000861EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
862 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000863
David Blaikie68e081d2011-12-20 02:48:34 +0000864void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000865EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
866 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000867
David Blaikie68e081d2011-12-20 02:48:34 +0000868void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000869EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
870 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000871
David Blaikie68e081d2011-12-20 02:48:34 +0000872void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000873EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
874 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000875
David Blaikie68e081d2011-12-20 02:48:34 +0000876void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000877EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
878 : CodeGenAction(Backend_EmitObj, _VMContext) {}