blob: eb2990405d53988a81a489c5021421025e52e830 [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 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"
14#include "clang/Basic/TargetInfo.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000015#include "clang/Basic/TargetOptions.h"
16#include "clang/CodeGen/CodeGenOptions.h"
17#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbar4ee34612010-02-25 04:37:45 +000018#include "clang/Frontend/ASTConsumers.h"
19#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar3be0d192009-12-03 09:12:54 +000020#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000021#include "llvm/Module.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000022#include "llvm/PassManager.h"
23#include "llvm/ADT/OwningPtr.h"
24#include "llvm/Assembly/PrintModulePass.h"
Daniel Dunbar70f92432008-10-23 05:50:47 +000025#include "llvm/Analysis/CallGraph.h"
26#include "llvm/Analysis/Verifier.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000027#include "llvm/Bitcode/ReaderWriter.h"
28#include "llvm/CodeGen/RegAllocRegistry.h"
29#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner03eacc72009-07-14 20:39:15 +000030#include "llvm/Support/FormattedStream.h"
Daniel Dunbar10d861e2009-06-03 18:01:18 +000031#include "llvm/Support/StandardPasses.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000032#include "llvm/Support/Timer.h"
Daniel Dunbara034ba82009-02-17 19:47:34 +000033#include "llvm/Target/SubtargetFeature.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000034#include "llvm/Target/TargetData.h"
35#include "llvm/Target/TargetMachine.h"
Daniel Dunbar821e2eb2009-12-12 23:01:36 +000036#include "llvm/Target/TargetOptions.h"
Daniel Dunbarf7d47c02009-07-15 20:25:38 +000037#include "llvm/Target/TargetRegistry.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000038using namespace clang;
39using namespace llvm;
40
41namespace {
Daniel Dunbar4ee34612010-02-25 04:37:45 +000042 enum BackendAction {
43 Backend_EmitAssembly, ///< Emit native assembly files
44 Backend_EmitBC, ///< Emit LLVM bitcode files
45 Backend_EmitLL, ///< Emit human-readable LLVM assembly
46 Backend_EmitNothing, ///< Don't emit anything (benchmarking mode)
47 Backend_EmitObj ///< Emit native object files
48 };
49
Benjamin Kramerbd218282009-11-28 10:07:24 +000050 class BackendConsumer : public ASTConsumer {
Daniel Dunbar125bbbe2009-12-04 08:17:40 +000051 Diagnostic &Diags;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000052 BackendAction Action;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000053 const CodeGenOptions &CodeGenOpts;
54 const LangOptions &LangOpts;
55 const TargetOptions &TargetOpts;
Eli Friedman66d6f042009-05-18 22:20:00 +000056 llvm::raw_ostream *AsmOutStream;
Chris Lattner03eacc72009-07-14 20:39:15 +000057 llvm::formatted_raw_ostream FormattedOutStream;
Chris Lattner49f28ca2009-03-05 08:00:35 +000058 ASTContext *Context;
Daniel Dunbar90f41302008-10-29 08:50:02 +000059
Chris Lattner6f114eb2009-02-18 01:37:30 +000060 Timer LLVMIRGeneration;
61 Timer CodeGenerationTime;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Daniel Dunbard69bacc2008-10-21 23:49:24 +000063 llvm::OwningPtr<CodeGenerator> Gen;
Mike Stump1eb44332009-09-09 15:08:12 +000064
Daniel Dunbarb954e982010-02-25 04:37:50 +000065 llvm::OwningPtr<llvm::Module> TheModule;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000066 llvm::TargetData *TheTargetData;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000067
68 mutable FunctionPassManager *CodeGenPasses;
69 mutable PassManager *PerModulePasses;
70 mutable FunctionPassManager *PerFunctionPasses;
71
72 FunctionPassManager *getCodeGenPasses() const;
73 PassManager *getPerModulePasses() const;
74 FunctionPassManager *getPerFunctionPasses() const;
75
76 void CreatePasses();
77
Daniel Dunbar125bbbe2009-12-04 08:17:40 +000078 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbard69bacc2008-10-21 23:49:24 +000079 ///
Daniel Dunbar3be0d192009-12-03 09:12:54 +000080 /// \return True on success.
81 bool AddEmitPasses();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000082
83 void EmitAssembly();
Mike Stump1eb44332009-09-09 15:08:12 +000084
85 public:
Daniel Dunbar3be0d192009-12-03 09:12:54 +000086 BackendConsumer(BackendAction action, Diagnostic &_Diags,
Chandler Carruth2811ccf2009-11-12 17:24:48 +000087 const LangOptions &langopts, const CodeGenOptions &compopts,
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000088 const TargetOptions &targetopts, bool TimePasses,
89 const std::string &infile, llvm::raw_ostream *OS,
90 LLVMContext& C) :
Daniel Dunbar3be0d192009-12-03 09:12:54 +000091 Diags(_Diags),
Mike Stump1eb44332009-09-09 15:08:12 +000092 Action(action),
Chandler Carruth2811ccf2009-11-12 17:24:48 +000093 CodeGenOpts(compopts),
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000094 LangOpts(langopts),
Daniel Dunbard58c03f2009-11-15 06:48:46 +000095 TargetOpts(targetopts),
Chris Lattner03eacc72009-07-14 20:39:15 +000096 AsmOutStream(OS),
Chris Lattner6f114eb2009-02-18 01:37:30 +000097 LLVMIRGeneration("LLVM IR Generation Time"),
98 CodeGenerationTime("Code Generation Time"),
Owen Anderson42253cc2009-07-01 17:00:06 +000099 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
Daniel Dunbarb954e982010-02-25 04:37:50 +0000100 TheTargetData(0),
Chris Lattner44502662009-02-18 01:23:44 +0000101 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Chris Lattner03eacc72009-07-14 20:39:15 +0000103 if (AsmOutStream)
104 FormattedOutStream.setStream(*AsmOutStream,
105 formatted_raw_ostream::PRESERVE_STREAM);
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000107 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattner44502662009-02-18 01:23:44 +0000108 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000109
110 ~BackendConsumer() {
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000111 delete TheTargetData;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000112 delete CodeGenPasses;
113 delete PerModulePasses;
114 delete PerFunctionPasses;
115 }
116
Daniel Dunbarb954e982010-02-25 04:37:50 +0000117 llvm::Module *takeModule() { return TheModule.take(); }
118
Chris Lattner7bb0da02009-03-28 02:18:25 +0000119 virtual void Initialize(ASTContext &Ctx) {
120 Context = &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000122 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000123 LLVMIRGeneration.startTimer();
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Chris Lattner7bb0da02009-03-28 02:18:25 +0000125 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000126
Daniel Dunbarb954e982010-02-25 04:37:50 +0000127 TheModule.reset(Gen->GetModule());
Chris Lattner7bb0da02009-03-28 02:18:25 +0000128 TheTargetData = new llvm::TargetData(Ctx.Target.getTargetDescription());
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000130 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000131 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000132 }
Mike Stump1eb44332009-09-09 15:08:12 +0000133
Chris Lattner682bf922009-03-29 16:50:03 +0000134 virtual void HandleTopLevelDecl(DeclGroupRef D) {
135 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +0000136 Context->getSourceManager(),
137 "LLVM IR generation of declaration");
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000139 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000140 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +0000141
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000142 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +0000143
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000144 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000145 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000146 }
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000148 virtual void HandleTranslationUnit(ASTContext &C) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000149 {
Chris Lattner14f234e2009-03-06 06:46:31 +0000150 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000151 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000152 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +0000153
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000154 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000155
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000156 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000157 LLVMIRGeneration.stopTimer();
158 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000159
Chris Lattner49f28ca2009-03-05 08:00:35 +0000160 // EmitAssembly times and registers crash info itself.
Chris Lattner6f114eb2009-02-18 01:37:30 +0000161 EmitAssembly();
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000163 // Force a flush here in case we never get released.
164 if (AsmOutStream)
Chris Lattner03eacc72009-07-14 20:39:15 +0000165 FormattedOutStream.flush();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000168 virtual void HandleTagDeclDefinition(TagDecl *D) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000169 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
170 Context->getSourceManager(),
171 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000172 Gen->HandleTagDeclDefinition(D);
173 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000174
175 virtual void CompleteTentativeDefinition(VarDecl *D) {
176 Gen->CompleteTentativeDefinition(D);
177 }
Mike Stump1eb44332009-09-09 15:08:12 +0000178 };
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000179}
180
181FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
182 if (!CodeGenPasses) {
Daniel Dunbarb954e982010-02-25 04:37:50 +0000183 CodeGenPasses = new FunctionPassManager(&*TheModule);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000184 CodeGenPasses->add(new TargetData(*TheTargetData));
185 }
186
187 return CodeGenPasses;
188}
189
190PassManager *BackendConsumer::getPerModulePasses() const {
191 if (!PerModulePasses) {
192 PerModulePasses = new PassManager();
193 PerModulePasses->add(new TargetData(*TheTargetData));
194 }
195
196 return PerModulePasses;
197}
198
199FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
200 if (!PerFunctionPasses) {
Daniel Dunbarb954e982010-02-25 04:37:50 +0000201 PerFunctionPasses = new FunctionPassManager(&*TheModule);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000202 PerFunctionPasses->add(new TargetData(*TheTargetData));
203 }
204
205 return PerFunctionPasses;
206}
207
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000208bool BackendConsumer::AddEmitPasses() {
Daniel Dunbare8e26002009-02-26 22:39:37 +0000209 if (Action == Backend_EmitNothing)
210 return true;
211
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000212 if (Action == Backend_EmitBC) {
Dan Gohmanb8d42392009-09-26 15:06:14 +0000213 getPerModulePasses()->add(createBitcodeWriterPass(FormattedOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000214 } else if (Action == Backend_EmitLL) {
Dan Gohmanb8d42392009-09-26 15:06:14 +0000215 getPerModulePasses()->add(createPrintModulePass(&FormattedOutStream));
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000216 } else {
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000217 bool Fast = CodeGenOpts.OptimizationLevel == 0;
Daniel Dunbar4c877cc2008-10-23 05:59:43 +0000218
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000219 // Create the TargetMachine for generating code.
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000220 std::string Error;
Daniel Dunbar82cfa7a2009-07-26 01:27:26 +0000221 std::string Triple = TheModule->getTargetTriple();
Daniel Dunbar9ab76fa2009-08-03 04:21:41 +0000222 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
Daniel Dunbarf7d47c02009-07-15 20:25:38 +0000223 if (!TheTarget) {
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000224 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000225 return false;
226 }
Daniel Dunbara034ba82009-02-17 19:47:34 +0000227
Daniel Dunbarf219e7c2009-11-29 07:18:39 +0000228 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
229 // being gross, this is also totally broken if we ever care about
230 // concurrency.
Daniel Dunbar821e2eb2009-12-12 23:01:36 +0000231 llvm::NoFramePointerElim = CodeGenOpts.DisableFPElim;
232 if (CodeGenOpts.FloatABI == "soft")
233 llvm::FloatABIType = llvm::FloatABI::Soft;
234 else if (CodeGenOpts.FloatABI == "hard")
235 llvm::FloatABIType = llvm::FloatABI::Hard;
236 else {
237 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
238 llvm::FloatABIType = llvm::FloatABI::Default;
239 }
240 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
241 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
242 UnwindTablesMandatory = CodeGenOpts.UnwindTables;
243
244 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
245
246 // FIXME: Parse this earlier.
247 if (CodeGenOpts.RelocationModel == "static") {
248 TargetMachine::setRelocationModel(llvm::Reloc::Static);
249 } else if (CodeGenOpts.RelocationModel == "pic") {
250 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
251 } else {
252 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
253 "Invalid PIC model!");
254 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
255 }
256 // FIXME: Parse this earlier.
257 if (CodeGenOpts.CodeModel == "small") {
258 TargetMachine::setCodeModel(llvm::CodeModel::Small);
259 } else if (CodeGenOpts.CodeModel == "kernel") {
260 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
261 } else if (CodeGenOpts.CodeModel == "medium") {
262 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
263 } else if (CodeGenOpts.CodeModel == "large") {
264 TargetMachine::setCodeModel(llvm::CodeModel::Large);
265 } else {
266 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
267 TargetMachine::setCodeModel(llvm::CodeModel::Default);
268 }
269
Daniel Dunbarf219e7c2009-11-29 07:18:39 +0000270 std::vector<const char *> BackendArgs;
271 BackendArgs.push_back("clang"); // Fake program name.
Daniel Dunbarf219e7c2009-11-29 07:18:39 +0000272 if (!CodeGenOpts.DebugPass.empty()) {
273 BackendArgs.push_back("-debug-pass");
274 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
275 }
Daniel Dunbarf219e7c2009-11-29 07:18:39 +0000276 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
277 BackendArgs.push_back("-limit-float-precision");
278 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
279 }
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000280 if (llvm::TimePassesIsEnabled)
Daniel Dunbarf219e7c2009-11-29 07:18:39 +0000281 BackendArgs.push_back("-time-passes");
Daniel Dunbarf219e7c2009-11-29 07:18:39 +0000282 BackendArgs.push_back(0);
283 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
284 (char**) &BackendArgs[0]);
285
Daniel Dunbara034ba82009-02-17 19:47:34 +0000286 std::string FeaturesStr;
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000287 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
Daniel Dunbara034ba82009-02-17 19:47:34 +0000288 SubtargetFeatures Features;
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000289 Features.setCPU(TargetOpts.CPU);
Daniel Dunbar3636e1d2009-11-30 08:39:32 +0000290 for (std::vector<std::string>::const_iterator
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000291 it = TargetOpts.Features.begin(),
292 ie = TargetOpts.Features.end(); it != ie; ++it)
Daniel Dunbara034ba82009-02-17 19:47:34 +0000293 Features.AddFeature(*it);
294 FeaturesStr = Features.getString();
295 }
Daniel Dunbar2b1f59f2009-08-04 04:02:57 +0000296 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000298 // Set register scheduler & allocation policy.
299 RegisterScheduler::setDefault(createDefaultScheduler);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
301 createLinearScanRegisterAllocator);
Daniel Dunbar8b7650e2008-10-22 18:29:51 +0000302
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000303 // From llvm-gcc:
304 // If there are passes we have to run on the entire module, we do codegen
305 // as a separate "pass" after that happens.
306 // FIXME: This is disabled right now until bugs can be worked out. Reenable
307 // this for fast -O0 compiles!
308 FunctionPassManager *PM = getCodeGenPasses();
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000309 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
310
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000311 switch (CodeGenOpts.OptimizationLevel) {
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000312 default: break;
313 case 0: OptLevel = CodeGenOpt::None; break;
Bill Wendling6e9b8f62009-04-29 23:53:23 +0000314 case 3: OptLevel = CodeGenOpt::Aggressive; break;
315 }
316
Daniel Dunbarda1573f2010-02-03 01:18:43 +0000317 // Normal mode, emit a .s or .o file by running the code generator. Note,
318 // this also adds codegenerator level optimization passes.
319 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
320 if (Action == Backend_EmitObj)
321 CGFT = TargetMachine::CGFT_ObjectFile;
Chris Lattnercd0507c2010-02-03 05:55:22 +0000322 if (TM->addPassesToEmitFile(*PM, FormattedOutStream, CGFT, OptLevel)) {
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000323 Diags.Report(diag::err_fe_unable_to_interface_with_target);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000324 return false;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000325 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000326 }
327
328 return true;
329}
330
331void BackendConsumer::CreatePasses() {
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000332 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
333 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000334
335 // Handle disabling of LLVM optimization, where we want to preserve the
336 // internal module before any optimization.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000337 if (CodeGenOpts.DisableLLVMOpts) {
Daniel Dunbar8d353142009-11-10 17:50:53 +0000338 OptLevel = 0;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000339 Inlining = CodeGenOpts.NoInlining;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000340 }
341
Daniel Dunbar70f92432008-10-23 05:50:47 +0000342 // In -O0 if checking is disabled, we don't even have per-function passes.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000343 if (CodeGenOpts.VerifyModule)
Daniel Dunbar70f92432008-10-23 05:50:47 +0000344 getPerFunctionPasses()->add(createVerifierPass());
345
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000346 // Assume that standard function passes aren't run for -O0.
Daniel Dunbar8d353142009-11-10 17:50:53 +0000347 if (OptLevel > 0)
348 llvm::createStandardFunctionPasses(getPerFunctionPasses(), OptLevel);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000349
350 llvm::Pass *InliningPass = 0;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000351 switch (Inlining) {
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000352 case CodeGenOptions::NoInlining: break;
353 case CodeGenOptions::NormalInlining: {
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000354 // Set the inline threshold following llvm-gcc.
355 //
356 // FIXME: Derive these constants in a principled fashion.
Daniel Dunbar9da55982010-02-05 07:32:37 +0000357 unsigned Threshold = 225;
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000358 if (CodeGenOpts.OptimizeSize)
Daniel Dunbar9da55982010-02-05 07:32:37 +0000359 Threshold = 75;
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000360 else if (OptLevel > 2)
Daniel Dunbar9da55982010-02-05 07:32:37 +0000361 Threshold = 275;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000362 InliningPass = createFunctionInliningPass(Threshold);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000363 break;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000364 }
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000365 case CodeGenOptions::OnlyAlwaysInlining:
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000366 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
367 break;
Daniel Dunbar70f92432008-10-23 05:50:47 +0000368 }
369
370 // For now we always create per module passes.
371 PassManager *PM = getPerModulePasses();
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000372 llvm::createStandardModulePasses(PM, OptLevel, CodeGenOpts.OptimizeSize,
373 CodeGenOpts.UnitAtATime,
374 CodeGenOpts.UnrollLoops,
Daniel Dunbar3636e1d2009-11-30 08:39:32 +0000375 /*SimplifyLibCalls=*/!LangOpts.NoBuiltin,
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000376 /*HaveExceptions=*/true,
377 InliningPass);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000378}
379
380/// EmitAssembly - Handle interaction with LLVM backend to generate
Mike Stump1eb44332009-09-09 15:08:12 +0000381/// actual machine code.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000382void BackendConsumer::EmitAssembly() {
383 // Silently ignore if we weren't initialized for some reason.
384 if (!TheModule || !TheTargetData)
385 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000387 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000388
Daniel Dunbard611bac2008-10-27 20:40:41 +0000389 // Make sure IR generation is happy with the module. This is
390 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000391 Module *M = Gen->ReleaseModule();
392 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000393 // The module has been released by IR gen on failures, do not
394 // double free.
Daniel Dunbarb954e982010-02-25 04:37:50 +0000395 TheModule.take();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000396 return;
397 }
398
Daniel Dunbarb954e982010-02-25 04:37:50 +0000399 assert(TheModule.get() == M &&
400 "Unexpected module change during IR generation");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000401
402 CreatePasses();
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000403 if (!AddEmitPasses())
404 return;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000405
406 // Run passes. For now we do all passes at once, but eventually we
407 // would like to have the option of streaming code generation.
408
409 if (PerFunctionPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000410 PrettyStackTraceString CrashInfo("Per-function optimization");
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000412 PerFunctionPasses->doInitialization();
413 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
414 if (!I->isDeclaration())
415 PerFunctionPasses->run(*I);
416 PerFunctionPasses->doFinalization();
417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattner49f28ca2009-03-05 08:00:35 +0000419 if (PerModulePasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000420 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000421 PerModulePasses->run(*M);
Chris Lattner49f28ca2009-03-05 08:00:35 +0000422 }
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000424 if (CodeGenPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000425 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000426 CodeGenPasses->doInitialization();
427 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
428 if (!I->isDeclaration())
429 CodeGenPasses->run(*I);
430 CodeGenPasses->doFinalization();
431 }
432}
433
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000434//
435
436CodeGenAction::CodeGenAction(unsigned _Act) : Act(_Act) {}
437
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000438CodeGenAction::~CodeGenAction() {}
439
Daniel Dunbarb954e982010-02-25 04:37:50 +0000440void CodeGenAction::EndSourceFileAction() {
441 // If the consumer creation failed, do nothing.
442 if (!getCompilerInstance().hasASTConsumer())
443 return;
444
445 // Steal the module from the consumer.
446 BackendConsumer *Consumer = static_cast<BackendConsumer*>(
447 &getCompilerInstance().getASTConsumer());
448
449 TheModule.reset(Consumer->takeModule());
450}
451
452llvm::Module *CodeGenAction::takeModule() {
453 return TheModule.take();
454}
455
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000456ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
457 llvm::StringRef InFile) {
458 BackendAction BA = static_cast<BackendAction>(Act);
459 llvm::OwningPtr<llvm::raw_ostream> OS;
460 switch (BA) {
461 case Backend_EmitAssembly:
462 OS.reset(CI.createDefaultOutputFile(false, InFile, "s"));
463 break;
464 case Backend_EmitLL:
465 OS.reset(CI.createDefaultOutputFile(false, InFile, "ll"));
466 break;
467 case Backend_EmitBC:
468 OS.reset(CI.createDefaultOutputFile(true, InFile, "bc"));
469 break;
470 case Backend_EmitNothing:
471 break;
472 case Backend_EmitObj:
473 OS.reset(CI.createDefaultOutputFile(true, InFile, "o"));
474 break;
475 }
476 if (BA != Backend_EmitNothing && !OS)
477 return 0;
478
479 return new BackendConsumer(BA, CI.getDiagnostics(), CI.getLangOpts(),
480 CI.getCodeGenOpts(), CI.getTargetOpts(),
481 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
482 CI.getLLVMContext());
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000483}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000484
485EmitAssemblyAction::EmitAssemblyAction()
486 : CodeGenAction(Backend_EmitAssembly) {}
487
488EmitBCAction::EmitBCAction() : CodeGenAction(Backend_EmitBC) {}
489
490EmitLLVMAction::EmitLLVMAction() : CodeGenAction(Backend_EmitLL) {}
491
492EmitLLVMOnlyAction::EmitLLVMOnlyAction() : CodeGenAction(Backend_EmitNothing) {}
493
494EmitObjAction::EmitObjAction() : CodeGenAction(Backend_EmitObj) {}