blob: 15e4f4883e8d4549d46e4af7c2ff937356adcb74 [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/Bitcode/ReaderWriter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000025#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000026#include "llvm/IR/DiagnosticInfo.h"
27#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000030#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000031#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000032#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000033#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000035#include "llvm/Support/Timer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000036#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000037using namespace clang;
38using namespace llvm;
39
Nico Weber2992efa2011-01-25 20:34:14 +000040namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000041 class BackendConsumer : public ASTConsumer {
David Blaikie68e081d2011-12-20 02:48:34 +000042 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000043 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000044 BackendAction Action;
Daniel Dunbarde182242009-11-30 08:39:32 +000045 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000046 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000047 const LangOptions &LangOpts;
Peter Collingbourne03f89072016-07-15 00:55:40 +000048 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000049 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000050
Chris Lattner263d64c2009-02-18 01:37:30 +000051 Timer LLVMIRGeneration;
Davide Italianob99fabd2016-07-21 06:28:48 +000052 unsigned LLVMIRGenerationRefCount;
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,
Peter Collingbourne03f89072016-07-15 00:55:40 +000071 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
Artem Belevich5d40ae32015-10-27 17:56:59 +000072 CoverageSourceInfo *CoverageInfo = nullptr)
Justin Bognercb082992015-05-22 22:16:55 +000073 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
Peter Collingbourne03f89072016-07-15 00:55:40 +000074 TargetOpts(TargetOpts), LangOpts(LangOpts),
75 AsmOutStream(std::move(OS)), Context(nullptr),
76 LLVMIRGeneration("LLVM IR Generation Time"),
Davide Italianob99fabd2016-07-21 06:28:48 +000077 LLVMIRGenerationRefCount(0),
Adrian Prantle74f5252015-06-30 02:26:03 +000078 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Artem Belevich5d40ae32015-10-27 17:56:59 +000079 CodeGenOpts, C, CoverageInfo)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000080 llvm::TimePassesIsEnabled = TimePasses;
Artem Belevich5d40ae32015-10-27 17:56:59 +000081 for (auto &I : LinkModules)
82 this->LinkModules.push_back(
83 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
Chris Lattnerdeffa132009-02-18 01:23:44 +000084 }
Serge Pavlov41c1f792016-02-18 16:42:09 +000085 llvm::Module *getModule() const { return Gen->GetModule(); }
86 std::unique_ptr<llvm::Module> takeModule() {
87 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
88 }
Artem Belevich5d40ae32015-10-27 17:56:59 +000089 void releaseLinkModules() {
90 for (auto &I : LinkModules)
91 I.second.release();
92 }
Daniel Dunbar400a6932010-02-25 04:37:50 +000093
Craig Topper4f12f102014-03-12 06:41:41 +000094 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +000095 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +000096 }
97
Craig Topper4f12f102014-03-12 06:41:41 +000098 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +000099 assert(!Context && "initialized multiple times");
100
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000101 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000102
Daniel Dunbar8e705052009-11-30 08:39:52 +0000103 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000104 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000105
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000106 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000107
Daniel Dunbar8e705052009-11-30 08:39:52 +0000108 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000109 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000110 }
Mike Stump11289f42009-09-09 15:08:12 +0000111
Craig Topper4f12f102014-03-12 06:41:41 +0000112 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000113 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000114 Context->getSourceManager(),
115 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000116
Davide Italianob99fabd2016-07-21 06:28:48 +0000117 // Recurse.
118 if (llvm::TimePassesIsEnabled) {
119 LLVMIRGenerationRefCount += 1;
120 if (LLVMIRGenerationRefCount == 1)
121 LLVMIRGeneration.startTimer();
122 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000123
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000124 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000125
Davide Italianob99fabd2016-07-21 06:28:48 +0000126 if (llvm::TimePassesIsEnabled) {
127 LLVMIRGenerationRefCount -= 1;
128 if (LLVMIRGenerationRefCount == 0)
129 LLVMIRGeneration.stopTimer();
130 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000131
132 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000133 }
Mike Stump11289f42009-09-09 15:08:12 +0000134
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000135 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000136 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
137 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000138 "LLVM IR generation of inline function");
Hans Wennborga926d842014-05-23 20:37:38 +0000139 if (llvm::TimePassesIsEnabled)
140 LLVMIRGeneration.startTimer();
141
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000142 Gen->HandleInlineFunctionDefinition(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000143
144 if (llvm::TimePassesIsEnabled)
145 LLVMIRGeneration.stopTimer();
146 }
147
Craig Topper4f12f102014-03-12 06:41:41 +0000148 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000149 {
Chris Lattnere46de752009-03-06 06:46:31 +0000150 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Davide Italianob99fabd2016-07-21 06:28:48 +0000151 if (llvm::TimePassesIsEnabled) {
152 LLVMIRGenerationRefCount += 1;
153 if (LLVMIRGenerationRefCount == 1)
154 LLVMIRGeneration.startTimer();
155 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000156
Chris Lattnercf169832009-03-28 04:11:33 +0000157 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000158
Davide Italianob99fabd2016-07-21 06:28:48 +0000159 if (llvm::TimePassesIsEnabled) {
160 LLVMIRGenerationRefCount -= 1;
161 if (LLVMIRGenerationRefCount == 0)
162 LLVMIRGeneration.stopTimer();
163 }
Chris Lattnereae6cb62009-03-05 08:00:35 +0000164 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000165
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000166 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000167 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000168 return;
Mike Stump11289f42009-09-09 15:08:12 +0000169
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000170 // Install an inline asm handler so that diagnostics get printed through
171 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000172 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000173 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
174 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000175 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000176 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000177
Quentin Colombet728c5542014-02-06 18:30:43 +0000178 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
179 Ctx.getDiagnosticHandler();
180 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
181 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
Adam Nemet1eea3e52016-09-13 04:32:40 +0000182 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
Quentin Colombet728c5542014-02-06 18:30:43 +0000183
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000184 // Link LinkModule into this module if present, preserving its validity.
185 for (auto &I : LinkModules) {
186 unsigned LinkFlags = I.first;
187 CurLinkModule = I.second.get();
Serge Pavlov41c1f792016-02-18 16:42:09 +0000188 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000189 return;
190 }
191
Steven Wu27fb5222016-05-11 16:26:03 +0000192 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
193
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000194 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000195 C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000196 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000197
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000198 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000199
200 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000201 }
Mike Stump11289f42009-09-09 15:08:12 +0000202
Craig Topper4f12f102014-03-12 06:41:41 +0000203 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000204 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
205 Context->getSourceManager(),
206 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000207 Gen->HandleTagDeclDefinition(D);
208 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000209
Craig Topper4f12f102014-03-12 06:41:41 +0000210 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000211 Gen->HandleTagDeclRequiredDefinition(D);
212 }
213
Craig Topper4f12f102014-03-12 06:41:41 +0000214 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000215 Gen->CompleteTentativeDefinition(D);
216 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000217
David Majnemer929025d2016-01-26 19:30:26 +0000218 void AssignInheritanceModel(CXXRecordDecl *RD) override {
219 Gen->AssignInheritanceModel(RD);
220 }
221
Nico Weberb6a5d052015-01-15 04:07:35 +0000222 void HandleVTable(CXXRecordDecl *RD) override {
223 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000224 }
225
Chris Lattner5ec32e72010-04-06 18:38:50 +0000226 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
227 unsigned LocCookie) {
228 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
229 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
230 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000231
Quentin Colombet728c5542014-02-06 18:30:43 +0000232 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
233 void *Context) {
234 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
235 }
236
Oliver Stannard91817852016-02-02 13:52:52 +0000237 /// Get the best possible source location to represent a diagnostic that
238 /// may have associated debug info.
239 const FullSourceLoc
240 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
241 bool &BadDebugInfo, StringRef &Filename,
242 unsigned &Line, unsigned &Column) const;
243
Chris Lattner5ec32e72010-04-06 18:38:50 +0000244 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
245 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000246
247 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
248 /// \brief Specialized handler for InlineAsm diagnostic.
249 /// \return True if the diagnostic has been successfully reported, false
250 /// otherwise.
251 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
252 /// \brief Specialized handler for StackSize diagnostic.
253 /// \return True if the diagnostic has been successfully reported, false
254 /// otherwise.
255 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000256 /// \brief Specialized handler for unsupported backend feature diagnostic.
257 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000258 /// \brief Specialized handlers for optimization remarks.
259 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000260 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000261 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
262 unsigned DiagID);
Adam Nemetb4e64a72016-09-27 22:19:29 +0000263 void OptimizationRemarkHandler(const llvm::OptimizationRemark &D);
264 void OptimizationRemarkHandler(const llvm::OptimizationRemarkMissed &D);
265 void OptimizationRemarkHandler(const llvm::OptimizationRemarkAnalysis &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000266 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000267 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000268 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000269 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000270 void OptimizationFailureHandler(
271 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000272 };
David Blaikie68e081d2011-12-20 02:48:34 +0000273
274 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000275}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000276
Chris Lattner79f67a72010-04-08 00:23:06 +0000277/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
278/// buffer to be a valid FullSourceLoc.
279static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
280 SourceManager &CSM) {
281 // Get both the clang and llvm source managers. The location is relative to
282 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000283 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000284 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000285
Chris Lattner79f67a72010-04-08 00:23:06 +0000286 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
287 // already owns its one and clang::SourceManager wants to own its one.
288 const MemoryBuffer *LBuf =
289 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000290
Chris Lattner79f67a72010-04-08 00:23:06 +0000291 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000292 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000293 std::unique_ptr<llvm::MemoryBuffer> CBuf =
294 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
295 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000296 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000297 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000298
Chris Lattner79f67a72010-04-08 00:23:06 +0000299 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000300 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000301 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000302 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000303 return FullSourceLoc(NewLoc, CSM);
304}
305
Chris Lattner6d672132010-04-06 17:52:14 +0000306
Chris Lattner5ec32e72010-04-06 18:38:50 +0000307/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
308/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000309/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000310void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
311 SourceLocation LocCookie) {
312 // There are a couple of different kinds of errors we could get here. First,
313 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000314
315 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000316 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000317 if (Message.startswith("error: "))
318 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000319
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000320 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000321 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000322 if (D.getLoc() != SMLoc())
323 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000324
Joey Gouly5798b262014-06-05 21:23:42 +0000325 unsigned DiagID;
326 switch (D.getKind()) {
327 case llvm::SourceMgr::DK_Error:
328 DiagID = diag::err_fe_inline_asm;
329 break;
330 case llvm::SourceMgr::DK_Warning:
331 DiagID = diag::warn_fe_inline_asm;
332 break;
333 case llvm::SourceMgr::DK_Note:
334 DiagID = diag::note_fe_inline_asm;
335 break;
336 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000337 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000338 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000339 // code.
340 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000341 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000342
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000343 if (D.getLoc().isValid()) {
344 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
345 // Convert the SMDiagnostic ranges into SourceRange and attach them
346 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000347 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000348 unsigned Column = D.getColumnNo();
349 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
350 Loc.getLocWithOffset(Range.second - Column));
351 }
352 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000353 return;
354 }
355
Joey Gouly5798b262014-06-05 21:23:42 +0000356 // Otherwise, report the backend issue as occurring in the generated .s file.
357 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000358 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000359 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000360}
361
Quentin Colombet728c5542014-02-06 18:30:43 +0000362#define ComputeDiagID(Severity, GroupName, DiagID) \
363 do { \
364 switch (Severity) { \
365 case llvm::DS_Error: \
366 DiagID = diag::err_fe_##GroupName; \
367 break; \
368 case llvm::DS_Warning: \
369 DiagID = diag::warn_fe_##GroupName; \
370 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000371 case llvm::DS_Remark: \
372 llvm_unreachable("'remark' severity not expected"); \
373 break; \
374 case llvm::DS_Note: \
375 DiagID = diag::note_fe_##GroupName; \
376 break; \
377 } \
378 } while (false)
379
380#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
381 do { \
382 switch (Severity) { \
383 case llvm::DS_Error: \
384 DiagID = diag::err_fe_##GroupName; \
385 break; \
386 case llvm::DS_Warning: \
387 DiagID = diag::warn_fe_##GroupName; \
388 break; \
389 case llvm::DS_Remark: \
390 DiagID = diag::remark_fe_##GroupName; \
391 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000392 case llvm::DS_Note: \
393 DiagID = diag::note_fe_##GroupName; \
394 break; \
395 } \
396 } while (false)
397
398bool
399BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
400 unsigned DiagID;
401 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
402 std::string Message = D.getMsgStr().str();
403
404 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000405 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000406 // code.
407 SourceLocation LocCookie =
408 SourceLocation::getFromRawEncoding(D.getLocCookie());
409 if (LocCookie.isValid())
410 Diags.Report(LocCookie, DiagID).AddString(Message);
411 else {
412 // Otherwise, report the backend diagnostic as occurring in the generated
413 // .s file.
414 // If Loc is invalid, we still need to report the diagnostic, it just gets
415 // no location info.
416 FullSourceLoc Loc;
417 Diags.Report(Loc, DiagID).AddString(Message);
418 }
419 // We handled all the possible severities.
420 return true;
421}
422
423bool
424BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
425 if (D.getSeverity() != llvm::DS_Warning)
426 // For now, the only support we have for StackSize diagnostic is warning.
427 // We do not know how to format other severities.
428 return false;
429
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000430 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000431 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000432 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
433 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000434 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000435 return true;
436 }
437
438 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000439}
440
Oliver Stannard91817852016-02-02 13:52:52 +0000441const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
442 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
443 unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000444 SourceManager &SourceMgr = Context->getSourceManager();
445 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000446 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000447
448 if (D.isLocationAvailable()) {
449 D.getLocation(&Filename, &Line, &Column);
450 const FileEntry *FE = FileMgr.getFile(Filename);
451 if (FE && Line > 0) {
452 // If -gcolumn-info was not used, Column will be 0. This upsets the
453 // source manager, so pass 1 if Column is not set.
454 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
455 }
Oliver Stannard91817852016-02-02 13:52:52 +0000456 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000457 }
Alp Toker27506272014-06-05 22:11:12 +0000458
459 // If a location isn't available, try to approximate it using the associated
460 // function definition. We use the definition's right brace to differentiate
461 // from diagnostics that genuinely relate to the function itself.
462 FullSourceLoc Loc(DILoc, SourceMgr);
463 if (Loc.isInvalid())
464 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000465 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000466
Diego Novillo86f884e2015-05-08 20:59:56 +0000467 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000468 // If we were not able to translate the file:line:col information
469 // back to a SourceLocation, at least emit a note stating that
470 // we could not translate this location. This can happen in the
471 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000472 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000473 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000474
475 return Loc;
476}
477
478void BackendConsumer::UnsupportedDiagHandler(
479 const llvm::DiagnosticInfoUnsupported &D) {
480 // We only support errors.
481 assert(D.getSeverity() == llvm::DS_Error);
482
483 StringRef Filename;
484 unsigned Line, Column;
485 bool BadDebugInfo;
486 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
487 Line, Column);
488
489 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
490
491 if (BadDebugInfo)
492 // If we were not able to translate the file:line:col information
493 // back to a SourceLocation, at least emit a note stating that
494 // we could not translate this location. This can happen in the
495 // case of #line directives.
496 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
497 << Filename << Line << Column;
498}
499
500void BackendConsumer::EmitOptimizationMessage(
501 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
502 // We only support warnings and remarks.
503 assert(D.getSeverity() == llvm::DS_Remark ||
504 D.getSeverity() == llvm::DS_Warning);
505
506 StringRef Filename;
507 unsigned Line, Column;
508 bool BadDebugInfo = false;
509 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
510 Line, Column);
511
Adam Nemet1eea3e52016-09-13 04:32:40 +0000512 std::string Msg;
513 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000514 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000515
516 if (D.getHotness())
517 MsgStream << " (hotness: " << *D.getHotness() << ")";
518
Oliver Stannard91817852016-02-02 13:52:52 +0000519 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000520 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000521 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000522
523 if (BadDebugInfo)
524 // If we were not able to translate the file:line:col information
525 // back to a SourceLocation, at least emit a note stating that
526 // we could not translate this location. This can happen in the
527 // case of #line directives.
528 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000529 << Filename << Line << Column;
530}
531
532void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000533 const llvm::OptimizationRemark &D) {
Diego Novillod23ec942014-05-29 19:55:06 +0000534 // Optimization remarks are active only if the -Rpass flag has a regular
535 // expression that matches the name of the pass name in \p D.
536 if (CodeGenOpts.OptimizationRemarkPattern &&
537 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000538 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
Diego Novillod23ec942014-05-29 19:55:06 +0000539}
540
541void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000542 const llvm::OptimizationRemarkMissed &D) {
Diego Novillod23ec942014-05-29 19:55:06 +0000543 // Missed optimization remarks are active only if the -Rpass-missed
544 // flag has a regular expression that matches the name of the pass
545 // name in \p D.
546 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
547 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000548 EmitOptimizationMessage(D,
549 diag::remark_fe_backend_optimization_remark_missed);
Diego Novillod23ec942014-05-29 19:55:06 +0000550}
551
552void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000553 const llvm::OptimizationRemarkAnalysis &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000554 // Optimization analysis remarks are active if the pass name is set to
555 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
556 // regular expression that matches the name of the pass name in \p D.
557
Adam Nemetb5beb972016-06-29 04:55:31 +0000558 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000559 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
560 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000561 EmitOptimizationMessage(
Diego Novillod23ec942014-05-29 19:55:06 +0000562 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000563}
564
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000565void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000566 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000567 // Optimization analysis remarks are active if the pass name is set to
568 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
569 // regular expression that matches the name of the pass name in \p D.
570
Adam Nemetb5beb972016-06-29 04:55:31 +0000571 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000572 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
573 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000574 EmitOptimizationMessage(
575 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
576}
577
Tyler Nowicki034baf62015-08-10 23:05:16 +0000578void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000579 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000580 // Optimization analysis remarks are active if the pass name is set to
581 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
582 // regular expression that matches the name of the pass name in \p D.
583
Adam Nemetb5beb972016-06-29 04:55:31 +0000584 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000585 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
586 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000587 EmitOptimizationMessage(
588 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
589}
590
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000591void BackendConsumer::OptimizationFailureHandler(
592 const llvm::DiagnosticInfoOptimizationFailure &D) {
593 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
594}
595
Quentin Colombet728c5542014-02-06 18:30:43 +0000596/// \brief This function is invoked when the backend needs
597/// to report something to the user.
598void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
599 unsigned DiagID = diag::err_fe_inline_asm;
600 llvm::DiagnosticSeverity Severity = DI.getSeverity();
601 // Get the diagnostic ID based.
602 switch (DI.getKind()) {
603 case llvm::DK_InlineAsm:
604 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
605 return;
606 ComputeDiagID(Severity, inline_asm, DiagID);
607 break;
608 case llvm::DK_StackSize:
609 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
610 return;
611 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
612 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000613 case DK_Linker:
614 assert(CurLinkModule);
615 // FIXME: stop eating the warnings and notes.
616 if (Severity != DS_Error)
617 return;
618 DiagID = diag::err_fe_cannot_link_module;
619 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000620 case llvm::DK_OptimizationRemark:
621 // Optimization remarks are always handled completely by this
622 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000623 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000624 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000625 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000626 // Optimization remarks are always handled completely by this
627 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000628 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000629 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000630 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000631 // Optimization remarks are always handled completely by this
632 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000633 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000634 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000635 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
636 // Optimization remarks are always handled completely by this
637 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000638 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000639 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000640 case llvm::DK_OptimizationRemarkAnalysisAliasing:
641 // Optimization remarks are always handled completely by this
642 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000643 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000644 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000645 case llvm::DK_OptimizationFailure:
646 // Optimization failures are always handled completely by this
647 // handler.
648 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
649 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000650 case llvm::DK_Unsupported:
651 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
652 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000653 default:
654 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000655 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000656 break;
657 }
658 std::string MsgStorage;
659 {
660 raw_string_ostream Stream(MsgStorage);
661 DiagnosticPrinterRawOStream DP(Stream);
662 DI.print(DP);
663 }
664
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000665 if (DiagID == diag::err_fe_cannot_link_module) {
666 Diags.Report(diag::err_fe_cannot_link_module)
667 << CurLinkModule->getModuleIdentifier() << MsgStorage;
668 return;
669 }
670
Quentin Colombet728c5542014-02-06 18:30:43 +0000671 // Report the backend message using the usual diagnostic mechanism.
672 FullSourceLoc Loc;
673 Diags.Report(Loc, DiagID).AddString(MsgStorage);
674}
675#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000676
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000677CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000678 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000679 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000680
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000681CodeGenAction::~CodeGenAction() {
682 TheModule.reset();
683 if (OwnsVMContext)
684 delete VMContext;
685}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000686
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000687bool CodeGenAction::hasIRSupport() const { return true; }
688
Daniel Dunbar400a6932010-02-25 04:37:50 +0000689void CodeGenAction::EndSourceFileAction() {
690 // If the consumer creation failed, do nothing.
691 if (!getCompilerInstance().hasASTConsumer())
692 return;
693
Artem Belevich5d40ae32015-10-27 17:56:59 +0000694 // Take back ownership of link modules we passed to consumer.
695 if (!LinkModules.empty())
696 BEConsumer->releaseLinkModules();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000697
Daniel Dunbar400a6932010-02-25 04:37:50 +0000698 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000699 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000700}
701
Rafael Espindolae8337302014-08-19 14:36:35 +0000702std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
703 return std::move(TheModule);
704}
705
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000706llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
707 OwnsVMContext = false;
708 return VMContext;
709}
710
Peter Collingbourne03f89072016-07-15 00:55:40 +0000711static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000712GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000713 switch (Action) {
714 case Backend_EmitAssembly:
715 return CI.createDefaultOutputFile(false, InFile, "s");
716 case Backend_EmitLL:
717 return CI.createDefaultOutputFile(false, InFile, "ll");
718 case Backend_EmitBC:
719 return CI.createDefaultOutputFile(true, InFile, "bc");
720 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000721 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000722 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000723 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000724 case Backend_EmitObj:
725 return CI.createDefaultOutputFile(true, InFile, "o");
726 }
727
David Blaikie83d382b2011-09-23 05:06:16 +0000728 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000729}
730
David Blaikie6beb6aa2014-08-10 19:56:51 +0000731std::unique_ptr<ASTConsumer>
732CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000733 BackendAction BA = static_cast<BackendAction>(Act);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000734 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000735 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000736 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000737
Artem Belevich5d40ae32015-10-27 17:56:59 +0000738 // Load bitcode modules to link with, if we need to.
739 if (LinkModules.empty())
740 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
741 const std::string &LinkBCFile = I.second;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000742
Artem Belevich5d40ae32015-10-27 17:56:59 +0000743 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
744 if (!BCBuf) {
745 CI.getDiagnostics().Report(diag::err_cannot_open_file)
746 << LinkBCFile << BCBuf.getError().message();
747 LinkModules.clear();
748 return nullptr;
749 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000750
Artem Belevich5d40ae32015-10-27 17:56:59 +0000751 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
752 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
753 if (std::error_code EC = ModuleOrErr.getError()) {
754 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
755 << EC.message();
756 LinkModules.clear();
757 return nullptr;
758 }
759 addLinkModule(ModuleOrErr.get().release(), I.first);
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000760 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000761
Alex Lorenzee024992014-08-04 18:41:51 +0000762 CoverageSourceInfo *CoverageInfo = nullptr;
763 // Add the preprocessor callback only when the coverage mapping is generated.
764 if (CI.getCodeGenOpts().CoverageMapping) {
765 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000766 CI.getPreprocessor().addPPCallbacks(
767 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000768 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000769
David Blaikie037e75b2014-08-10 21:06:17 +0000770 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000771 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
772 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Artem Belevich5d40ae32015-10-27 17:56:59 +0000773 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000774 std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000775 BEConsumer = Result.get();
776 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000777}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000778
Tim Northover1390b442016-04-06 19:58:07 +0000779static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
780 void *Context,
781 unsigned LocCookie) {
782 SM.print(nullptr, llvm::errs());
783
784 auto Diags = static_cast<DiagnosticsEngine *>(Context);
785 unsigned DiagID;
786 switch (SM.getKind()) {
787 case llvm::SourceMgr::DK_Error:
788 DiagID = diag::err_fe_inline_asm;
789 break;
790 case llvm::SourceMgr::DK_Warning:
791 DiagID = diag::warn_fe_inline_asm;
792 break;
793 case llvm::SourceMgr::DK_Note:
794 DiagID = diag::note_fe_inline_asm;
795 break;
796 }
797
798 Diags->Report(DiagID).AddString("cannot compile inline asm");
799}
800
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000801void CodeGenAction::ExecuteAction() {
802 // If this is an IR file, we have to treat it specially.
803 if (getCurrentFileKind() == IK_LLVM_IR) {
804 BackendAction BA = static_cast<BackendAction>(Act);
805 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000806 std::unique_ptr<raw_pwrite_stream> OS =
807 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000808 if (BA != Backend_EmitNothing && !OS)
809 return;
810
811 bool Invalid;
812 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000813 FileID FID = SM.getMainFileID();
814 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000815 if (Invalid)
816 return;
817
Teresa Johnsonb1047492016-04-20 02:23:52 +0000818 // For ThinLTO backend invocations, ensure that the context
819 // merges types based on ODR identifiers.
820 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
821 VMContext->enableDebugTypeODRUniquing();
822
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000823 llvm::SMDiagnostic Err;
Rafael Espindola32327732014-08-26 21:49:29 +0000824 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000825 if (!TheModule) {
Alp Toker7b463d52014-06-30 01:33:59 +0000826 // Translate from the diagnostic info to the SourceManager location if
827 // available.
828 // TODO: Unify this with ConvertBackendLocation()
829 SourceLocation Loc;
830 if (Err.getLineNo() > 0) {
831 assert(Err.getColumnNo() >= 0);
832 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
833 Err.getLineNo(), Err.getColumnNo() + 1);
834 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000835
Alp Tokerbc043f22013-12-21 05:20:03 +0000836 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000837 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000838 if (Msg.startswith("error: "))
839 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000840
Alp Tokerbc043f22013-12-21 05:20:03 +0000841 unsigned DiagID =
842 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000843
Alp Tokerbc043f22013-12-21 05:20:03 +0000844 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000845 return;
846 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000847 const TargetOptions &TargetOpts = CI.getTargetOpts();
848 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000849 CI.getDiagnostics().Report(SourceLocation(),
850 diag::warn_fe_override_module)
851 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000852 TheModule->setTargetTriple(TargetOpts.Triple);
853 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000854
Steven Wu27fb5222016-05-11 16:26:03 +0000855 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
856 MainFile->getMemBufferRef());
857
Tim Northover1390b442016-04-06 19:58:07 +0000858 LLVMContext &Ctx = TheModule->getContext();
859 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
860 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000861
Alp Tokere83b9062014-01-02 15:08:04 +0000862 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
James Y Knightb214cbc2016-03-04 19:00:41 +0000863 CI.getLangOpts(), CI.getTarget().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000864 TheModule.get(), BA, std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000865 return;
866 }
867
868 // Otherwise follow the normal AST path.
869 this->ASTFrontendAction::ExecuteAction();
870}
871
872//
873
David Blaikie68e081d2011-12-20 02:48:34 +0000874void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000875EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
876 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000877
David Blaikie68e081d2011-12-20 02:48:34 +0000878void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000879EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
880 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000881
David Blaikie68e081d2011-12-20 02:48:34 +0000882void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000883EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
884 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000885
David Blaikie68e081d2011-12-20 02:48:34 +0000886void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000887EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
888 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000889
David Blaikie68e081d2011-12-20 02:48:34 +0000890void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000891EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
892 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000893
David Blaikie68e081d2011-12-20 02:48:34 +0000894void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000895EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
896 : CodeGenAction(Backend_EmitObj, _VMContext) {}