blob: 86005f280ac7be1f4b90651f6ad50bb4ec5ba8e4 [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 Dunbar4ee34612010-02-25 04:37:45 +000010#include "clang/Frontend/CodeGenAction.h"
Chris Lattner6da9eb62010-04-06 18:38:50 +000011#include "clang/Basic/SourceManager.h"
12#include "clang/Basic/TargetInfo.h"
13#include "clang/Basic/TargetOptions.h"
Chris Lattner682bf922009-03-29 16:50:03 +000014#include "clang/AST/ASTConsumer.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000015#include "clang/AST/ASTContext.h"
Chris Lattner682bf922009-03-29 16:50:03 +000016#include "clang/AST/DeclGroup.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000017#include "clang/CodeGen/CodeGenOptions.h"
18#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbar4ee34612010-02-25 04:37:45 +000019#include "clang/Frontend/ASTConsumers.h"
20#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar3be0d192009-12-03 09:12:54 +000021#include "clang/Frontend/FrontendDiagnostic.h"
Chris Lattnercabae682010-04-06 17:52:14 +000022#include "llvm/LLVMContext.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000023#include "llvm/Module.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000024#include "llvm/PassManager.h"
25#include "llvm/ADT/OwningPtr.h"
26#include "llvm/Assembly/PrintModulePass.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000027#include "llvm/Analysis/CallGraph.h"
28#include "llvm/Analysis/Verifier.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000029#include "llvm/Bitcode/ReaderWriter.h"
30#include "llvm/CodeGen/RegAllocRegistry.h"
31#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner03eacc72009-07-14 20:39:15 +000032#include "llvm/Support/FormattedStream.h"
Chris Lattner6da9eb62010-04-06 18:38:50 +000033#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/SourceMgr.h"
Daniel Dunbar10d861e2009-06-03 18:01:18 +000035#include "llvm/Support/StandardPasses.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000036#include "llvm/Support/Timer.h"
Daniel Dunbara034ba82009-02-17 19:47:34 +000037#include "llvm/Target/SubtargetFeature.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetMachine.h"
Daniel Dunbar821e2eb2009-12-12 23:01:36 +000040#include "llvm/Target/TargetOptions.h"
Daniel Dunbarf7d47c02009-07-15 20:25:38 +000041#include "llvm/Target/TargetRegistry.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000042using namespace clang;
43using namespace llvm;
44
45namespace {
Daniel Dunbar4ee34612010-02-25 04:37:45 +000046 enum BackendAction {
47 Backend_EmitAssembly, ///< Emit native assembly files
48 Backend_EmitBC, ///< Emit LLVM bitcode files
49 Backend_EmitLL, ///< Emit human-readable LLVM assembly
50 Backend_EmitNothing, ///< Don't emit anything (benchmarking mode)
51 Backend_EmitObj ///< Emit native object files
52 };
53
Benjamin Kramerbd218282009-11-28 10:07:24 +000054 class BackendConsumer : public ASTConsumer {
Daniel Dunbar125bbbe2009-12-04 08:17:40 +000055 Diagnostic &Diags;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000056 BackendAction Action;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000057 const CodeGenOptions &CodeGenOpts;
58 const LangOptions &LangOpts;
59 const TargetOptions &TargetOpts;
Eli Friedman66d6f042009-05-18 22:20:00 +000060 llvm::raw_ostream *AsmOutStream;
Chris Lattner03eacc72009-07-14 20:39:15 +000061 llvm::formatted_raw_ostream FormattedOutStream;
Chris Lattner49f28ca2009-03-05 08:00:35 +000062 ASTContext *Context;
Daniel Dunbar90f41302008-10-29 08:50:02 +000063
Chris Lattner6f114eb2009-02-18 01:37:30 +000064 Timer LLVMIRGeneration;
65 Timer CodeGenerationTime;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Daniel Dunbard69bacc2008-10-21 23:49:24 +000067 llvm::OwningPtr<CodeGenerator> Gen;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Daniel Dunbarb954e982010-02-25 04:37:50 +000069 llvm::OwningPtr<llvm::Module> TheModule;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000070 llvm::TargetData *TheTargetData;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000071
72 mutable FunctionPassManager *CodeGenPasses;
73 mutable PassManager *PerModulePasses;
74 mutable FunctionPassManager *PerFunctionPasses;
75
76 FunctionPassManager *getCodeGenPasses() const;
77 PassManager *getPerModulePasses() const;
78 FunctionPassManager *getPerFunctionPasses() const;
79
80 void CreatePasses();
81
Daniel Dunbar125bbbe2009-12-04 08:17:40 +000082 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000083 ///
Daniel Dunbar3be0d192009-12-03 09:12:54 +000084 /// \return True on success.
85 bool AddEmitPasses();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000086
87 void EmitAssembly();
Mike Stump1eb44332009-09-09 15:08:12 +000088
89 public:
Daniel Dunbar3be0d192009-12-03 09:12:54 +000090 BackendConsumer(BackendAction action, Diagnostic &_Diags,
Chandler Carruth2811ccf2009-11-12 17:24:48 +000091 const LangOptions &langopts, const CodeGenOptions &compopts,
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000092 const TargetOptions &targetopts, bool TimePasses,
93 const std::string &infile, llvm::raw_ostream *OS,
Chris Lattnercabae682010-04-06 17:52:14 +000094 LLVMContext &C) :
Daniel Dunbar3be0d192009-12-03 09:12:54 +000095 Diags(_Diags),
Mike Stump1eb44332009-09-09 15:08:12 +000096 Action(action),
Chandler Carruth2811ccf2009-11-12 17:24:48 +000097 CodeGenOpts(compopts),
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000098 LangOpts(langopts),
Daniel Dunbard58c03f2009-11-15 06:48:46 +000099 TargetOpts(targetopts),
Chris Lattner03eacc72009-07-14 20:39:15 +0000100 AsmOutStream(OS),
Chris Lattner6f114eb2009-02-18 01:37:30 +0000101 LLVMIRGeneration("LLVM IR Generation Time"),
102 CodeGenerationTime("Code Generation Time"),
John McCall468ec6c2010-03-04 04:29:44 +0000103 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
104 TheTargetData(0),
Chris Lattner44502662009-02-18 01:23:44 +0000105 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner03eacc72009-07-14 20:39:15 +0000107 if (AsmOutStream)
108 FormattedOutStream.setStream(*AsmOutStream,
109 formatted_raw_ostream::PRESERVE_STREAM);
Mike Stump1eb44332009-09-09 15:08:12 +0000110
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000111 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattner44502662009-02-18 01:23:44 +0000112 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000113
114 ~BackendConsumer() {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000115 delete TheTargetData;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000116 delete CodeGenPasses;
117 delete PerModulePasses;
118 delete PerFunctionPasses;
119 }
120
Daniel Dunbarb954e982010-02-25 04:37:50 +0000121 llvm::Module *takeModule() { return TheModule.take(); }
122
Chris Lattner7bb0da02009-03-28 02:18:25 +0000123 virtual void Initialize(ASTContext &Ctx) {
124 Context = &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000126 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000127 LLVMIRGeneration.startTimer();
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Chris Lattner7bb0da02009-03-28 02:18:25 +0000129 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000130
Daniel Dunbarb954e982010-02-25 04:37:50 +0000131 TheModule.reset(Gen->GetModule());
Chris Lattner7bb0da02009-03-28 02:18:25 +0000132 TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription());
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000134 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000135 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000136 }
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner682bf922009-03-29 16:50:03 +0000138 virtual void HandleTopLevelDecl(DeclGroupRef D) {
139 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +0000140 Context->getSourceManager(),
141 "LLVM IR generation of declaration");
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000143 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000144 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +0000145
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000146 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +0000147
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000148 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000149 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000150 }
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000152 virtual void HandleTranslationUnit(ASTContext &C) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000153 {
Chris Lattner14f234e2009-03-06 06:46:31 +0000154 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000155 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000156 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +0000157
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000158 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000159
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000160 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000161 LLVMIRGeneration.stopTimer();
162 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000163
Chris Lattner49f28ca2009-03-05 08:00:35 +0000164 // EmitAssembly times and registers crash info itself.
Chris Lattner6f114eb2009-02-18 01:37:30 +0000165 EmitAssembly();
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000167 // Force a flush here in case we never get released.
168 if (AsmOutStream)
Chris Lattner03eacc72009-07-14 20:39:15 +0000169 FormattedOutStream.flush();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000170 }
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000172 virtual void HandleTagDeclDefinition(TagDecl *D) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000173 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
174 Context->getSourceManager(),
175 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000176 Gen->HandleTagDeclDefinition(D);
177 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000178
179 virtual void CompleteTentativeDefinition(VarDecl *D) {
180 Gen->CompleteTentativeDefinition(D);
181 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000182
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000183 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
184 Gen->HandleVTable(RD, DefinitionRequired);
185 }
186
Chris Lattner6da9eb62010-04-06 18:38:50 +0000187 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
188 unsigned LocCookie) {
189 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
190 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
191 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000192
Chris Lattner6da9eb62010-04-06 18:38:50 +0000193 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
194 SourceLocation LocCookie);
Mike Stump1eb44332009-09-09 15:08:12 +0000195 };
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000196}
197
198FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
199 if (!CodeGenPasses) {
Daniel Dunbarb954e982010-02-25 04:37:50 +0000200 CodeGenPasses = new FunctionPassManager(&*TheModule);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000201 CodeGenPasses->add(new TargetData(*TheTargetData));
202 }
203
204 return CodeGenPasses;
205}
206
207PassManager *BackendConsumer::getPerModulePasses() const {
208 if (!PerModulePasses) {
209 PerModulePasses = new PassManager();
210 PerModulePasses->add(new TargetData(*TheTargetData));
211 }
212
213 return PerModulePasses;
214}
215
216FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
217 if (!PerFunctionPasses) {
Daniel Dunbarb954e982010-02-25 04:37:50 +0000218 PerFunctionPasses = new FunctionPassManager(&*TheModule);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000219 PerFunctionPasses->add(new TargetData(*TheTargetData));
220 }
221
222 return PerFunctionPasses;
223}
224
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000225bool BackendConsumer::AddEmitPasses() {
Daniel Dunbare8e26002009-02-26 22:39:37 +0000226 if (Action == Backend_EmitNothing)
227 return true;
228
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000229 if (Action == Backend_EmitBC) {
Dan Gohmanb8d42392009-09-26 15:06:14 +0000230 getPerModulePasses()->add(createBitcodeWriterPass(FormattedOutStream));
Chris Lattnercabae682010-04-06 17:52:14 +0000231 return true;
232 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000233
Chris Lattnercabae682010-04-06 17:52:14 +0000234 if (Action == Backend_EmitLL) {
Dan Gohmanb8d42392009-09-26 15:06:14 +0000235 getPerModulePasses()->add(createPrintModulePass(&FormattedOutStream));
Chris Lattnercabae682010-04-06 17:52:14 +0000236 return true;
237 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000238
Chris Lattnercabae682010-04-06 17:52:14 +0000239 bool Fast = CodeGenOpts.OptimizationLevel == 0;
240
241 // Create the TargetMachine for generating code.
242 std::string Error;
243 std::string Triple = TheModule->getTargetTriple();
244 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
245 if (!TheTarget) {
246 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
247 return false;
248 }
249
250 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
251 // being gross, this is also totally broken if we ever care about
252 // concurrency.
253 llvm::NoFramePointerElim = CodeGenOpts.DisableFPElim;
254 if (CodeGenOpts.FloatABI == "soft")
255 llvm::FloatABIType = llvm::FloatABI::Soft;
256 else if (CodeGenOpts.FloatABI == "hard")
257 llvm::FloatABIType = llvm::FloatABI::Hard;
258 else {
259 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
260 llvm::FloatABIType = llvm::FloatABI::Default;
261 }
262 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
263 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
264 UnwindTablesMandatory = CodeGenOpts.UnwindTables;
265
266 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
267
Chris Lattnerbbea7162010-04-13 00:38:24 +0000268 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
269 TargetMachine::setDataSections (CodeGenOpts.DataSections);
270
Chris Lattnercabae682010-04-06 17:52:14 +0000271 // FIXME: Parse this earlier.
272 if (CodeGenOpts.RelocationModel == "static") {
273 TargetMachine::setRelocationModel(llvm::Reloc::Static);
274 } else if (CodeGenOpts.RelocationModel == "pic") {
275 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000276 } else {
Chris Lattnercabae682010-04-06 17:52:14 +0000277 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
278 "Invalid PIC model!");
279 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
280 }
281 // FIXME: Parse this earlier.
282 if (CodeGenOpts.CodeModel == "small") {
283 TargetMachine::setCodeModel(llvm::CodeModel::Small);
284 } else if (CodeGenOpts.CodeModel == "kernel") {
285 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
286 } else if (CodeGenOpts.CodeModel == "medium") {
287 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
288 } else if (CodeGenOpts.CodeModel == "large") {
289 TargetMachine::setCodeModel(llvm::CodeModel::Large);
290 } else {
291 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
292 TargetMachine::setCodeModel(llvm::CodeModel::Default);
293 }
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000294
Chris Lattnercabae682010-04-06 17:52:14 +0000295 std::vector<const char *> BackendArgs;
296 BackendArgs.push_back("clang"); // Fake program name.
297 if (!CodeGenOpts.DebugPass.empty()) {
298 BackendArgs.push_back("-debug-pass");
299 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
300 }
301 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
302 BackendArgs.push_back("-limit-float-precision");
303 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
304 }
305 if (llvm::TimePassesIsEnabled)
306 BackendArgs.push_back("-time-passes");
307 BackendArgs.push_back(0);
308 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
Dan Gohmancb421fa2010-04-19 16:39:44 +0000309 const_cast<char **>(&BackendArgs[0]));
John McCall468ec6c2010-03-04 04:29:44 +0000310
Chris Lattnercabae682010-04-06 17:52:14 +0000311 std::string FeaturesStr;
312 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
313 SubtargetFeatures Features;
314 Features.setCPU(TargetOpts.CPU);
315 for (std::vector<std::string>::const_iterator
316 it = TargetOpts.Features.begin(),
317 ie = TargetOpts.Features.end(); it != ie; ++it)
318 Features.AddFeature(*it);
319 FeaturesStr = Features.getString();
320 }
321 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
Daniel Dunbar821e2eb2009-12-12 23:01:36 +0000322
Chris Lattnercabae682010-04-06 17:52:14 +0000323 // Set register scheduler & allocation policy.
324 RegisterScheduler::setDefault(createDefaultScheduler);
325 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
326 createLinearScanRegisterAllocator);
John McCall468ec6c2010-03-04 04:29:44 +0000327
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000328 // Create the code generator passes.
Chris Lattnercabae682010-04-06 17:52:14 +0000329 FunctionPassManager *PM = getCodeGenPasses();
330 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
John McCall468ec6c2010-03-04 04:29:44 +0000331
Chris Lattnercabae682010-04-06 17:52:14 +0000332 switch (CodeGenOpts.OptimizationLevel) {
333 default: break;
334 case 0: OptLevel = CodeGenOpt::None; break;
335 case 3: OptLevel = CodeGenOpt::Aggressive; break;
336 }
Daniel Dunbarf219e7c2009-11-29 07:18:39 +0000337
Chris Lattnercabae682010-04-06 17:52:14 +0000338 // Normal mode, emit a .s or .o file by running the code generator. Note,
339 // this also adds codegenerator level optimization passes.
340 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
341 if (Action == Backend_EmitObj)
342 CGFT = TargetMachine::CGFT_ObjectFile;
343 if (TM->addPassesToEmitFile(*PM, FormattedOutStream, CGFT, OptLevel,
Daniel Dunbar8a5e83c2010-04-29 16:29:06 +0000344 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
Chris Lattnercabae682010-04-06 17:52:14 +0000345 Diags.Report(diag::err_fe_unable_to_interface_with_target);
346 return false;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000347 }
348
349 return true;
350}
351
352void BackendConsumer::CreatePasses() {
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000353 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
354 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000355
356 // Handle disabling of LLVM optimization, where we want to preserve the
357 // internal module before any optimization.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000358 if (CodeGenOpts.DisableLLVMOpts) {
Daniel Dunbar8d353142009-11-10 17:50:53 +0000359 OptLevel = 0;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000360 Inlining = CodeGenOpts.NoInlining;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000361 }
362
Daniel Dunbar70f92432008-10-23 05:50:47 +0000363 // In -O0 if checking is disabled, we don't even have per-function passes.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000364 if (CodeGenOpts.VerifyModule)
Daniel Dunbar70f92432008-10-23 05:50:47 +0000365 getPerFunctionPasses()->add(createVerifierPass());
366
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000367 // Assume that standard function passes aren't run for -O0.
Daniel Dunbar8d353142009-11-10 17:50:53 +0000368 if (OptLevel > 0)
369 llvm::createStandardFunctionPasses(getPerFunctionPasses(), OptLevel);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000370
371 llvm::Pass *InliningPass = 0;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000372 switch (Inlining) {
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000373 case CodeGenOptions::NoInlining: break;
374 case CodeGenOptions::NormalInlining: {
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000375 // Set the inline threshold following llvm-gcc.
376 //
377 // FIXME: Derive these constants in a principled fashion.
Daniel Dunbar9da55982010-02-05 07:32:37 +0000378 unsigned Threshold = 225;
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000379 if (CodeGenOpts.OptimizeSize)
Daniel Dunbar9da55982010-02-05 07:32:37 +0000380 Threshold = 75;
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000381 else if (OptLevel > 2)
Daniel Dunbar9da55982010-02-05 07:32:37 +0000382 Threshold = 275;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000383 InliningPass = createFunctionInliningPass(Threshold);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000384 break;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000385 }
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000386 case CodeGenOptions::OnlyAlwaysInlining:
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000387 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
388 break;
Daniel Dunbar70f92432008-10-23 05:50:47 +0000389 }
390
391 // For now we always create per module passes.
392 PassManager *PM = getPerModulePasses();
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000393 llvm::createStandardModulePasses(PM, OptLevel, CodeGenOpts.OptimizeSize,
394 CodeGenOpts.UnitAtATime,
395 CodeGenOpts.UnrollLoops,
Daniel Dunbar3636e1d2009-11-30 08:39:32 +0000396 /*SimplifyLibCalls=*/!LangOpts.NoBuiltin,
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000397 /*HaveExceptions=*/true,
398 InliningPass);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000399}
400
401/// EmitAssembly - Handle interaction with LLVM backend to generate
Mike Stump1eb44332009-09-09 15:08:12 +0000402/// actual machine code.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000403void BackendConsumer::EmitAssembly() {
404 // Silently ignore if we weren't initialized for some reason.
405 if (!TheModule || !TheTargetData)
406 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000408 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000409
Daniel Dunbard611bac2008-10-27 20:40:41 +0000410 // Make sure IR generation is happy with the module. This is
411 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000412 Module *M = Gen->ReleaseModule();
413 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000414 // The module has been released by IR gen on failures, do not
415 // double free.
Daniel Dunbarb954e982010-02-25 04:37:50 +0000416 TheModule.take();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000417 return;
418 }
419
Daniel Dunbarb954e982010-02-25 04:37:50 +0000420 assert(TheModule.get() == M &&
421 "Unexpected module change during IR generation");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000422
423 CreatePasses();
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000424 if (!AddEmitPasses())
425 return;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000426
427 // Run passes. For now we do all passes at once, but eventually we
428 // would like to have the option of streaming code generation.
429
430 if (PerFunctionPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000431 PrettyStackTraceString CrashInfo("Per-function optimization");
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000433 PerFunctionPasses->doInitialization();
434 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
435 if (!I->isDeclaration())
436 PerFunctionPasses->run(*I);
437 PerFunctionPasses->doFinalization();
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner49f28ca2009-03-05 08:00:35 +0000440 if (PerModulePasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000441 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000442 PerModulePasses->run(*M);
Chris Lattner49f28ca2009-03-05 08:00:35 +0000443 }
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000445 if (CodeGenPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000446 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000447
Chris Lattner6da9eb62010-04-06 18:38:50 +0000448 // Install an inline asm handler so that diagnostics get printed through our
449 // diagnostics hooks.
450 LLVMContext &Ctx = TheModule->getContext();
451 void *OldHandler = Ctx.getInlineAsmDiagnosticHandler();
452 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
453 Ctx.setInlineAsmDiagnosticHandler((void*)(intptr_t)InlineAsmDiagHandler,
454 this);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000455
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000456 CodeGenPasses->doInitialization();
457 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
458 if (!I->isDeclaration())
459 CodeGenPasses->run(*I);
460 CodeGenPasses->doFinalization();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000461
Chris Lattner6da9eb62010-04-06 18:38:50 +0000462 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000463 }
464}
465
Chris Lattnerd6f19062010-04-08 00:23:06 +0000466/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
467/// buffer to be a valid FullSourceLoc.
468static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
469 SourceManager &CSM) {
470 // Get both the clang and llvm source managers. The location is relative to
471 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000472 // a copy to the Clang source manager.
Chris Lattnerd6f19062010-04-08 00:23:06 +0000473 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000474
Chris Lattnerd6f19062010-04-08 00:23:06 +0000475 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
476 // already owns its one and clang::SourceManager wants to own its one.
477 const MemoryBuffer *LBuf =
478 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000479
Chris Lattnerd6f19062010-04-08 00:23:06 +0000480 // Create the copy and transfer ownership to clang::SourceManager.
481 llvm::MemoryBuffer *CBuf =
482 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
483 LBuf->getBufferIdentifier());
484 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000485
Chris Lattnerd6f19062010-04-08 00:23:06 +0000486 // Translate the offset into the file.
487 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000488 SourceLocation NewLoc =
Chris Lattnerd6f19062010-04-08 00:23:06 +0000489 CSM.getLocForStartOfFile(FID).getFileLocWithOffset(Offset);
490 return FullSourceLoc(NewLoc, CSM);
491}
492
Chris Lattnercabae682010-04-06 17:52:14 +0000493
Chris Lattner6da9eb62010-04-06 18:38:50 +0000494/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
495/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000496/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000497void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
498 SourceLocation LocCookie) {
499 // There are a couple of different kinds of errors we could get here. First,
500 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000501
Chris Lattner6da9eb62010-04-06 18:38:50 +0000502 // Strip "error: " off the start of the message string.
503 llvm::StringRef Message = D.getMessage();
504 if (Message.startswith("error: "))
505 Message = Message.substr(7);
506
507 // There are two cases: the SMDiagnostic could have a inline asm source
508 // location or it might not. If it does, translate the location.
509 FullSourceLoc Loc;
Chris Lattnerd6f19062010-04-08 00:23:06 +0000510 if (D.getLoc() != SMLoc())
511 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattner6da9eb62010-04-06 18:38:50 +0000512 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000513
Chris Lattner6da9eb62010-04-06 18:38:50 +0000514 // This could be a problem with no clang-level source location information.
515 // In this case, LocCookie is invalid. If there is source level information,
516 // print an "generated from" note.
517 if (LocCookie.isValid())
518 Diags.Report(FullSourceLoc(LocCookie, Context->getSourceManager()),
519 diag::note_fe_inline_asm_here);
520}
521
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000522//
523
524CodeGenAction::CodeGenAction(unsigned _Act) : Act(_Act) {}
525
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000526CodeGenAction::~CodeGenAction() {}
527
Daniel Dunbarb954e982010-02-25 04:37:50 +0000528void CodeGenAction::EndSourceFileAction() {
529 // If the consumer creation failed, do nothing.
530 if (!getCompilerInstance().hasASTConsumer())
531 return;
532
533 // Steal the module from the consumer.
534 BackendConsumer *Consumer = static_cast<BackendConsumer*>(
535 &getCompilerInstance().getASTConsumer());
536
537 TheModule.reset(Consumer->takeModule());
538}
539
540llvm::Module *CodeGenAction::takeModule() {
541 return TheModule.take();
542}
543
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000544ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
545 llvm::StringRef InFile) {
546 BackendAction BA = static_cast<BackendAction>(Act);
547 llvm::OwningPtr<llvm::raw_ostream> OS;
548 switch (BA) {
549 case Backend_EmitAssembly:
550 OS.reset(CI.createDefaultOutputFile(false, InFile, "s"));
551 break;
552 case Backend_EmitLL:
553 OS.reset(CI.createDefaultOutputFile(false, InFile, "ll"));
554 break;
555 case Backend_EmitBC:
556 OS.reset(CI.createDefaultOutputFile(true, InFile, "bc"));
557 break;
558 case Backend_EmitNothing:
559 break;
560 case Backend_EmitObj:
561 OS.reset(CI.createDefaultOutputFile(true, InFile, "o"));
562 break;
563 }
564 if (BA != Backend_EmitNothing && !OS)
565 return 0;
566
John McCall468ec6c2010-03-04 04:29:44 +0000567 return new BackendConsumer(BA, CI.getDiagnostics(), CI.getLangOpts(),
568 CI.getCodeGenOpts(), CI.getTargetOpts(),
569 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000570 CI.getLLVMContext());
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000571}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000572
573EmitAssemblyAction::EmitAssemblyAction()
574 : CodeGenAction(Backend_EmitAssembly) {}
575
576EmitBCAction::EmitBCAction() : CodeGenAction(Backend_EmitBC) {}
577
578EmitLLVMAction::EmitLLVMAction() : CodeGenAction(Backend_EmitLL) {}
579
580EmitLLVMOnlyAction::EmitLLVMOnlyAction() : CodeGenAction(Backend_EmitNothing) {}
581
582EmitObjAction::EmitObjAction() : CodeGenAction(Backend_EmitObj) {}