blob: 2fe984226e184e5a58292a86b8175e7cc0c8d75d [file] [log] [blame]
Daniel Dunbar4ee34612010-02-25 04:37:45 +00001//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
Daniel Dunbard69bacc2008-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
Daniel Dunbar9b414d32010-06-15 17:48:49 +000010#include "clang/CodeGen/CodeGenAction.h"
Chris Lattner682bf922009-03-29 16:50:03 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000012#include "clang/AST/ASTContext.h"
Chris Lattner682bf922009-03-29 16:50:03 +000013#include "clang/AST/DeclGroup.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070014#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Basic/TargetInfo.h"
Daniel Dunbar9b414d32010-06-15 17:48:49 +000018#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000019#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbar4ee34612010-02-25 04:37:45 +000020#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar3be0d192009-12-03 09:12:54 +000021#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "llvm/ADT/SmallString.h"
23#include "llvm/Bitcode/ReaderWriter.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070024#include "llvm/IR/DebugInfo.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070025#include "llvm/IR/DiagnosticInfo.h"
26#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000027#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
Chandler Carruth9cc935b2013-03-26 02:25:54 +000029#include "llvm/IRReader/IRReader.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070030#include "llvm/Linker/Linker.h"
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000031#include "llvm/Pass.h"
Chris Lattner6da9eb62010-04-06 18:38:50 +000032#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/SourceMgr.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000034#include "llvm/Support/Timer.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070035#include <memory>
Daniel Dunbard69bacc2008-10-21 23:49:24 +000036using namespace clang;
37using namespace llvm;
38
Nico Weber5aa74af2011-01-25 20:34:14 +000039namespace clang {
Benjamin Kramerbd218282009-11-28 10:07:24 +000040 class BackendConsumer : public ASTConsumer {
David Blaikie99ba9e32011-12-20 02:48:34 +000041 virtual void anchor();
David Blaikied6471f72011-09-25 23:23:43 +000042 DiagnosticsEngine &Diags;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000043 BackendAction Action;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000044 const CodeGenOptions &CodeGenOpts;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000045 const TargetOptions &TargetOpts;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000046 const LangOptions &LangOpts;
Chris Lattner5f9e2722011-07-23 10:55:15 +000047 raw_ostream *AsmOutStream;
Chris Lattner49f28ca2009-03-05 08:00:35 +000048 ASTContext *Context;
Daniel Dunbar90f41302008-10-29 08:50:02 +000049
Chris Lattner6f114eb2009-02-18 01:37:30 +000050 Timer LLVMIRGeneration;
Mike Stump1eb44332009-09-09 15:08:12 +000051
Stephen Hines651f13c2014-04-23 16:59:28 -070052 std::unique_ptr<CodeGenerator> Gen;
Mike Stump1eb44332009-09-09 15:08:12 +000053
Stephen Hines651f13c2014-04-23 16:59:28 -070054 std::unique_ptr<llvm::Module> TheModule, LinkModule;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000055
Mike Stump1eb44332009-09-09 15:08:12 +000056 public:
David Blaikied6471f72011-09-25 23:23:43 +000057 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
Daniel Dunbar6b0cf672010-06-07 23:19:17 +000058 const CodeGenOptions &compopts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000059 const TargetOptions &targetopts,
Stephen Hines651f13c2014-04-23 16:59:28 -070060 const LangOptions &langopts, bool TimePasses,
61 const std::string &infile, llvm::Module *LinkModule,
62 raw_ostream *OS, LLVMContext &C)
63 : Diags(_Diags), Action(action), CodeGenOpts(compopts),
64 TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
65 Context(), LLVMIRGeneration("LLVM IR Generation Time"),
66 Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
67 LinkModule(LinkModule) {
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000068 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattner44502662009-02-18 01:23:44 +000069 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000070
Stephen Hines651f13c2014-04-23 16:59:28 -070071 llvm::Module *takeModule() { return TheModule.release(); }
72 llvm::Module *takeLinkModule() { return LinkModule.release(); }
Daniel Dunbarb954e982010-02-25 04:37:50 +000073
Stephen Hines651f13c2014-04-23 16:59:28 -070074 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindola02503932012-03-08 15:51:03 +000075 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +000076 }
77
Stephen Hines651f13c2014-04-23 16:59:28 -070078 void Initialize(ASTContext &Ctx) override {
Chris Lattner7bb0da02009-03-28 02:18:25 +000079 Context = &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +000080
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000081 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000082 LLVMIRGeneration.startTimer();
Mike Stump1eb44332009-09-09 15:08:12 +000083
Chris Lattner7bb0da02009-03-28 02:18:25 +000084 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000085
Daniel Dunbarb954e982010-02-25 04:37:50 +000086 TheModule.reset(Gen->GetModule());
Mike Stump1eb44332009-09-09 15:08:12 +000087
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000088 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000089 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000090 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Stephen Hines651f13c2014-04-23 16:59:28 -070092 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner682bf922009-03-29 16:50:03 +000093 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +000094 Context->getSourceManager(),
95 "LLVM IR generation of declaration");
Mike Stump1eb44332009-09-09 15:08:12 +000096
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000097 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000098 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +000099
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000100 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +0000101
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000102 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000103 LLVMIRGeneration.stopTimer();
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000104
105 return true;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700108 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
109 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
110 Context->getSourceManager(),
111 "LLVM IR generation of inline method");
112 if (llvm::TimePassesIsEnabled)
113 LLVMIRGeneration.startTimer();
114
115 Gen->HandleInlineMethodDefinition(D);
116
117 if (llvm::TimePassesIsEnabled)
118 LLVMIRGeneration.stopTimer();
119 }
120
Stephen Hines651f13c2014-04-23 16:59:28 -0700121 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000122 {
Chris Lattner14f234e2009-03-06 06:46:31 +0000123 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000124 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000125 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +0000126
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000127 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000128
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000129 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000130 LLVMIRGeneration.stopTimer();
131 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000132
Daniel Dunbar897c6762010-06-07 23:20:08 +0000133 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000134 if (!TheModule)
Daniel Dunbar897c6762010-06-07 23:20:08 +0000135 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Daniel Dunbar897c6762010-06-07 23:20:08 +0000137 // Make sure IR generation is happy with the module. This is released by
138 // the module provider.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000139 llvm::Module *M = Gen->ReleaseModule();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000140 if (!M) {
141 // The module has been released by IR gen on failures, do not double
142 // free.
Stephen Hines651f13c2014-04-23 16:59:28 -0700143 TheModule.release();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000144 return;
145 }
146
147 assert(TheModule.get() == M &&
148 "Unexpected module change during IR generation");
149
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000150 // Link LinkModule into this module if present, preserving its validity.
151 if (LinkModule) {
152 std::string ErrorMsg;
153 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
154 &ErrorMsg)) {
155 Diags.Report(diag::err_fe_cannot_link_module)
156 << LinkModule->getModuleIdentifier() << ErrorMsg;
157 return;
158 }
159 }
160
Daniel Dunbar897c6762010-06-07 23:20:08 +0000161 // Install an inline asm handler so that diagnostics get printed through
162 // our diagnostics hooks.
163 LLVMContext &Ctx = TheModule->getContext();
Chris Lattner063e4762010-11-17 08:13:04 +0000164 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
165 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000166 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner063e4762010-11-17 08:13:04 +0000167 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000168
Stephen Hines651f13c2014-04-23 16:59:28 -0700169 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
170 Ctx.getDiagnosticHandler();
171 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
172 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
173
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000174 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Stephen Hines651f13c2014-04-23 16:59:28 -0700175 C.getTargetInfo().getTargetDescription(),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000176 TheModule.get(), Action, AsmOutStream);
Stephen Hines651f13c2014-04-23 16:59:28 -0700177
Daniel Dunbar897c6762010-06-07 23:20:08 +0000178 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Stephen Hines651f13c2014-04-23 16:59:28 -0700179
180 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000181 }
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Stephen Hines651f13c2014-04-23 16:59:28 -0700183 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000184 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
185 Context->getSourceManager(),
186 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000187 Gen->HandleTagDeclDefinition(D);
188 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000189
Stephen Hines651f13c2014-04-23 16:59:28 -0700190 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie658cd2c2013-07-13 21:08:14 +0000191 Gen->HandleTagDeclRequiredDefinition(D);
192 }
193
Stephen Hines651f13c2014-04-23 16:59:28 -0700194 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000195 Gen->CompleteTentativeDefinition(D);
196 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000197
Stephen Hines651f13c2014-04-23 16:59:28 -0700198 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000199 Gen->HandleVTable(RD, DefinitionRequired);
200 }
201
Stephen Hines651f13c2014-04-23 16:59:28 -0700202 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
Reid Kleckner3190ca92013-05-08 13:44:39 +0000203 Gen->HandleLinkerOptionPragma(Opts);
204 }
205
Stephen Hines651f13c2014-04-23 16:59:28 -0700206 void HandleDetectMismatch(llvm::StringRef Name,
207 llvm::StringRef Value) override {
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000208 Gen->HandleDetectMismatch(Name, Value);
209 }
210
Stephen Hines651f13c2014-04-23 16:59:28 -0700211 void HandleDependentLibrary(llvm::StringRef Opts) override {
Reid Kleckner3190ca92013-05-08 13:44:39 +0000212 Gen->HandleDependentLibrary(Opts);
213 }
214
Chris Lattner6da9eb62010-04-06 18:38:50 +0000215 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
216 unsigned LocCookie) {
217 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
218 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
219 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000220
Stephen Hines651f13c2014-04-23 16:59:28 -0700221 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
222 void *Context) {
223 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
224 }
225
Chris Lattner6da9eb62010-04-06 18:38:50 +0000226 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
227 SourceLocation LocCookie);
Stephen Hines651f13c2014-04-23 16:59:28 -0700228
229 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
230 /// \brief Specialized handler for InlineAsm diagnostic.
231 /// \return True if the diagnostic has been successfully reported, false
232 /// otherwise.
233 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
234 /// \brief Specialized handler for StackSize diagnostic.
235 /// \return True if the diagnostic has been successfully reported, false
236 /// otherwise.
237 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700238 /// \brief Specialized handler for the optimization diagnostic.
239 /// Note that this handler only accepts remarks and it always handles
240 /// them.
241 void
242 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
Mike Stump1eb44332009-09-09 15:08:12 +0000243 };
David Blaikie99ba9e32011-12-20 02:48:34 +0000244
245 void BackendConsumer::anchor() {}
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000246}
247
Chris Lattnerd6f19062010-04-08 00:23:06 +0000248/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
249/// buffer to be a valid FullSourceLoc.
250static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
251 SourceManager &CSM) {
252 // Get both the clang and llvm source managers. The location is relative to
253 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000254 // a copy to the Clang source manager.
Chris Lattnerd6f19062010-04-08 00:23:06 +0000255 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000256
Chris Lattnerd6f19062010-04-08 00:23:06 +0000257 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
258 // already owns its one and clang::SourceManager wants to own its one.
259 const MemoryBuffer *LBuf =
260 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000261
Chris Lattnerd6f19062010-04-08 00:23:06 +0000262 // Create the copy and transfer ownership to clang::SourceManager.
263 llvm::MemoryBuffer *CBuf =
264 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
265 LBuf->getBufferIdentifier());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700266 FileID FID = CSM.createFileID(CBuf);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000267
Chris Lattnerd6f19062010-04-08 00:23:06 +0000268 // Translate the offset into the file.
269 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000270 SourceLocation NewLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000271 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattnerd6f19062010-04-08 00:23:06 +0000272 return FullSourceLoc(NewLoc, CSM);
273}
274
Chris Lattnercabae682010-04-06 17:52:14 +0000275
Chris Lattner6da9eb62010-04-06 18:38:50 +0000276/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
277/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000278/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000279void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
280 SourceLocation LocCookie) {
281 // There are a couple of different kinds of errors we could get here. First,
282 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidis5d3a4bb2012-02-01 06:36:49 +0000283
284 // Strip "error: " off the start of the message string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000285 StringRef Message = D.getMessage();
Argyrios Kyrtzidis5d3a4bb2012-02-01 06:36:49 +0000286 if (Message.startswith("error: "))
287 Message = Message.substr(7);
Chris Lattner6da9eb62010-04-06 18:38:50 +0000288
Chris Lattner99e14a02010-06-15 00:03:12 +0000289 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000290 FullSourceLoc Loc;
Chris Lattnerd6f19062010-04-08 00:23:06 +0000291 if (D.getLoc() != SMLoc())
292 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattnerff8f9ec2012-01-31 06:13:55 +0000293
Argyrios Kyrtzidis5d3a4bb2012-02-01 06:36:49 +0000294
Chris Lattner99e14a02010-06-15 00:03:12 +0000295 // If this problem has clang-level source location information, report the
296 // issue as being an error in the source with a note showing the instantiated
297 // code.
298 if (LocCookie.isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000299 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner99e14a02010-06-15 00:03:12 +0000300
Benjamin Kramer96fda0c2011-10-16 10:48:28 +0000301 if (D.getLoc().isValid()) {
302 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
303 // Convert the SMDiagnostic ranges into SourceRange and attach them
304 // to the diagnostic.
305 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
306 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
307 unsigned Column = D.getColumnNo();
308 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
309 Loc.getLocWithOffset(Range.second - Column));
310 }
311 }
Chris Lattner99e14a02010-06-15 00:03:12 +0000312 return;
313 }
314
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000315 // Otherwise, report the backend error as occurring in the generated .s file.
Chris Lattner99e14a02010-06-15 00:03:12 +0000316 // If Loc is invalid, we still need to report the error, it just gets no
317 // location info.
318 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner6da9eb62010-04-06 18:38:50 +0000319}
320
Stephen Hines651f13c2014-04-23 16:59:28 -0700321#define ComputeDiagID(Severity, GroupName, DiagID) \
322 do { \
323 switch (Severity) { \
324 case llvm::DS_Error: \
325 DiagID = diag::err_fe_##GroupName; \
326 break; \
327 case llvm::DS_Warning: \
328 DiagID = diag::warn_fe_##GroupName; \
329 break; \
330 case llvm::DS_Remark: \
331 llvm_unreachable("'remark' severity not expected"); \
332 break; \
333 case llvm::DS_Note: \
334 DiagID = diag::note_fe_##GroupName; \
335 break; \
336 } \
337 } while (false)
338
339#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
340 do { \
341 switch (Severity) { \
342 case llvm::DS_Error: \
343 DiagID = diag::err_fe_##GroupName; \
344 break; \
345 case llvm::DS_Warning: \
346 DiagID = diag::warn_fe_##GroupName; \
347 break; \
348 case llvm::DS_Remark: \
349 DiagID = diag::remark_fe_##GroupName; \
350 break; \
351 case llvm::DS_Note: \
352 DiagID = diag::note_fe_##GroupName; \
353 break; \
354 } \
355 } while (false)
356
357bool
358BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
359 unsigned DiagID;
360 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
361 std::string Message = D.getMsgStr().str();
362
363 // If this problem has clang-level source location information, report the
364 // issue as being a problem in the source with a note showing the instantiated
365 // code.
366 SourceLocation LocCookie =
367 SourceLocation::getFromRawEncoding(D.getLocCookie());
368 if (LocCookie.isValid())
369 Diags.Report(LocCookie, DiagID).AddString(Message);
370 else {
371 // Otherwise, report the backend diagnostic as occurring in the generated
372 // .s file.
373 // If Loc is invalid, we still need to report the diagnostic, it just gets
374 // no location info.
375 FullSourceLoc Loc;
376 Diags.Report(Loc, DiagID).AddString(Message);
377 }
378 // We handled all the possible severities.
379 return true;
380}
381
382bool
383BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
384 if (D.getSeverity() != llvm::DS_Warning)
385 // For now, the only support we have for StackSize diagnostic is warning.
386 // We do not know how to format other severities.
387 return false;
388
389 // FIXME: We should demangle the function name.
390 // FIXME: Is there a way to get a location for that function?
391 FullSourceLoc Loc;
392 Diags.Report(Loc, diag::warn_fe_backend_frame_larger_than)
393 << D.getStackSize() << D.getFunction().getName();
394 return true;
395}
396
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700397void BackendConsumer::OptimizationRemarkHandler(
398 const llvm::DiagnosticInfoOptimizationRemark &D) {
399 // We only support remarks.
400 assert(D.getSeverity() == llvm::DS_Remark);
401
402 // Optimization remarks are active only if -Rpass=regexp is given and the
403 // regular expression pattern in 'regexp' matches the name of the pass
404 // name in \p D.
405 if (CodeGenOpts.OptimizationRemarkPattern &&
406 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) {
407 SourceManager &SourceMgr = Context->getSourceManager();
408 FileManager &FileMgr = SourceMgr.getFileManager();
409 StringRef Filename;
410 unsigned Line, Column;
411 D.getLocation(&Filename, &Line, &Column);
412 SourceLocation Loc;
413 const FileEntry *FE = FileMgr.getFile(Filename);
414 if (FE && Line > 0) {
415 // If -gcolumn-info was not used, Column will be 0. This upsets the
416 // source manager, so if Column is not set, set it to 1.
417 if (Column == 0)
418 Column = 1;
419 Loc = SourceMgr.translateFileLineCol(FE, Line, Column);
420 }
421 Diags.Report(Loc, diag::remark_fe_backend_optimization_remark)
422 << AddFlagValue(D.getPassName()) << D.getMsg().str();
423
424 if (Line == 0)
425 // If we could not extract a source location for the diagnostic,
426 // inform the user how they can get source locations back.
427 //
428 // FIXME: We should really be generating !srcloc annotations when
429 // -Rpass is used. !srcloc annotations need to be emitted in
430 // approximately the same spots as !dbg nodes.
431 Diags.Report(diag::note_fe_backend_optimization_remark_missing_loc);
432 else if (Loc.isInvalid())
433 // If we were not able to translate the file:line:col information
434 // back to a SourceLocation, at least emit a note stating that
435 // we could not translate this location. This can happen in the
436 // case of #line directives.
437 Diags.Report(diag::note_fe_backend_optimization_remark_invalid_loc)
438 << Filename << Line << Column;
439 }
440}
441
Stephen Hines651f13c2014-04-23 16:59:28 -0700442/// \brief This function is invoked when the backend needs
443/// to report something to the user.
444void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
445 unsigned DiagID = diag::err_fe_inline_asm;
446 llvm::DiagnosticSeverity Severity = DI.getSeverity();
447 // Get the diagnostic ID based.
448 switch (DI.getKind()) {
449 case llvm::DK_InlineAsm:
450 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
451 return;
452 ComputeDiagID(Severity, inline_asm, DiagID);
453 break;
454 case llvm::DK_StackSize:
455 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
456 return;
457 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
458 break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700459 case llvm::DK_OptimizationRemark:
460 // Optimization remarks are always handled completely by this
461 // handler. There is no generic way of emitting them.
462 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
463 return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700464 default:
465 // Plugin IDs are not bound to any value as they are set dynamically.
466 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
467 break;
468 }
469 std::string MsgStorage;
470 {
471 raw_string_ostream Stream(MsgStorage);
472 DiagnosticPrinterRawOStream DP(Stream);
473 DI.print(DP);
474 }
475
476 // Report the backend message using the usual diagnostic mechanism.
477 FullSourceLoc Loc;
478 Diags.Report(Loc, DiagID).AddString(MsgStorage);
479}
480#undef ComputeDiagID
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000481
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000482CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700483 : Act(_Act), LinkModule(nullptr),
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000484 VMContext(_VMContext ? _VMContext : new LLVMContext),
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000485 OwnsVMContext(!_VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000486
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000487CodeGenAction::~CodeGenAction() {
488 TheModule.reset();
489 if (OwnsVMContext)
490 delete VMContext;
491}
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000492
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000493bool CodeGenAction::hasIRSupport() const { return true; }
494
Daniel Dunbarb954e982010-02-25 04:37:50 +0000495void CodeGenAction::EndSourceFileAction() {
496 // If the consumer creation failed, do nothing.
497 if (!getCompilerInstance().hasASTConsumer())
498 return;
499
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000500 // If we were given a link module, release consumer's ownership of it.
501 if (LinkModule)
502 BEConsumer->takeLinkModule();
503
Daniel Dunbarb954e982010-02-25 04:37:50 +0000504 // Steal the module from the consumer.
Nico Weber5aa74af2011-01-25 20:34:14 +0000505 TheModule.reset(BEConsumer->takeModule());
Daniel Dunbarb954e982010-02-25 04:37:50 +0000506}
507
Stephen Hines651f13c2014-04-23 16:59:28 -0700508llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
Daniel Dunbarb954e982010-02-25 04:37:50 +0000509
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000510llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
511 OwnsVMContext = false;
512 return VMContext;
513}
514
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000515static raw_ostream *GetOutputStream(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000516 StringRef InFile,
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000517 BackendAction Action) {
518 switch (Action) {
519 case Backend_EmitAssembly:
520 return CI.createDefaultOutputFile(false, InFile, "s");
521 case Backend_EmitLL:
522 return CI.createDefaultOutputFile(false, InFile, "ll");
523 case Backend_EmitBC:
524 return CI.createDefaultOutputFile(true, InFile, "bc");
525 case Backend_EmitNothing:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700526 return nullptr;
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000527 case Backend_EmitMCNull:
528 case Backend_EmitObj:
529 return CI.createDefaultOutputFile(true, InFile, "o");
530 }
531
David Blaikieb219cfc2011-09-23 05:06:16 +0000532 llvm_unreachable("Invalid action!");
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000533}
534
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000535ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000536 StringRef InFile) {
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000537 BackendAction BA = static_cast<BackendAction>(Act);
Stephen Hines651f13c2014-04-23 16:59:28 -0700538 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000539 if (BA != Backend_EmitNothing && !OS)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700540 return nullptr;
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000541
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000542 llvm::Module *LinkModuleToUse = LinkModule;
543
544 // If we were not given a link module, and the user requested that one be
545 // loaded from bitcode, do so now.
546 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
547 if (!LinkModuleToUse && !LinkBCFile.empty()) {
548 std::string ErrorStr;
549
550 llvm::MemoryBuffer *BCBuf =
551 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
552 if (!BCBuf) {
553 CI.getDiagnostics().Report(diag::err_cannot_open_file)
554 << LinkBCFile << ErrorStr;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700555 return nullptr;
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000556 }
557
Stephen Hines651f13c2014-04-23 16:59:28 -0700558 ErrorOr<llvm::Module *> ModuleOrErr =
559 getLazyBitcodeModule(BCBuf, *VMContext);
560 if (error_code EC = ModuleOrErr.getError()) {
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000561 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Stephen Hines651f13c2014-04-23 16:59:28 -0700562 << LinkBCFile << EC.message();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700563 return nullptr;
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000564 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700565 LinkModuleToUse = ModuleOrErr.get();
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000566 }
567
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700568 StringRef MainFileName = getCompilerInstance().getCodeGenOpts().MainFileName;
569 if (MainFileName.empty())
570 MainFileName = InFile;
Stephen Hines651f13c2014-04-23 16:59:28 -0700571 BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
572 CI.getTargetOpts(), CI.getLangOpts(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700573 CI.getFrontendOpts().ShowTimers, MainFileName,
Stephen Hines651f13c2014-04-23 16:59:28 -0700574 LinkModuleToUse, OS.release(), *VMContext);
Nico Weber5aa74af2011-01-25 20:34:14 +0000575 return BEConsumer;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000576}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000577
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000578void CodeGenAction::ExecuteAction() {
579 // If this is an IR file, we have to treat it specially.
580 if (getCurrentFileKind() == IK_LLVM_IR) {
581 BackendAction BA = static_cast<BackendAction>(Act);
582 CompilerInstance &CI = getCompilerInstance();
583 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
584 if (BA != Backend_EmitNothing && !OS)
585 return;
586
587 bool Invalid;
588 SourceManager &SM = CI.getSourceManager();
589 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
590 &Invalid);
591 if (Invalid)
592 return;
593
594 // FIXME: This is stupid, IRReader shouldn't take ownership.
595 llvm::MemoryBuffer *MainFileCopy =
596 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +0000597 getCurrentFile());
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000598
599 llvm::SMDiagnostic Err;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000600 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000601 if (!TheModule) {
602 // Translate from the diagnostic info to the SourceManager location.
Argyrios Kyrtzidis5a9ee202011-09-19 20:40:38 +0000603 SourceLocation Loc = SM.translateFileLineCol(
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000604 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
605 Err.getColumnNo() + 1);
606
Stephen Hines651f13c2014-04-23 16:59:28 -0700607 // Strip off a leading diagnostic code if there is one.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000608 StringRef Msg = Err.getMessage();
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000609 if (Msg.startswith("error: "))
610 Msg = Msg.substr(7);
Benjamin Kramerc9b47f92012-03-16 22:31:42 +0000611
Stephen Hines651f13c2014-04-23 16:59:28 -0700612 unsigned DiagID =
613 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramerc9b47f92012-03-16 22:31:42 +0000614
Stephen Hines651f13c2014-04-23 16:59:28 -0700615 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000616 return;
617 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700618 const TargetOptions &TargetOpts = CI.getTargetOpts();
619 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
620 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
621 DiagnosticsEngine::Warning,
622 "overriding the module target triple with %0");
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000623
Stephen Hines651f13c2014-04-23 16:59:28 -0700624 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
625 TheModule->setTargetTriple(TargetOpts.Triple);
626 }
627
628 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
629 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
630 TheModule.get(), BA, OS);
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000631 return;
632 }
633
634 // Otherwise follow the normal AST path.
635 this->ASTFrontendAction::ExecuteAction();
636}
637
638//
639
David Blaikie99ba9e32011-12-20 02:48:34 +0000640void EmitAssemblyAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000641EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
642 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000643
David Blaikie99ba9e32011-12-20 02:48:34 +0000644void EmitBCAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000645EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
646 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000647
David Blaikie99ba9e32011-12-20 02:48:34 +0000648void EmitLLVMAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000649EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
650 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000651
David Blaikie99ba9e32011-12-20 02:48:34 +0000652void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000653EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
654 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000655
David Blaikie99ba9e32011-12-20 02:48:34 +0000656void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000657EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
658 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar32148ce2010-05-25 18:41:01 +0000659
David Blaikie99ba9e32011-12-20 02:48:34 +0000660void EmitObjAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000661EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
662 : CodeGenAction(Backend_EmitObj, _VMContext) {}