blob: b1795a3aa3b54db075426a59974dd89b56cdad66 [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"),
John McCall468ec6c2010-03-04 04:29:44 +000099 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)),
100 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
John McCall468ec6c2010-03-04 04:29:44 +0000219 // Create the TargetMachine for generating code.
220 std::string Error;
221 std::string Triple = TheModule->getTargetTriple();
222 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
223 if (!TheTarget) {
224 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
225 return false;
226 }
227
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
John McCall468ec6c2010-03-04 04:29:44 +0000244 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
John McCall468ec6c2010-03-04 04:29:44 +0000286 std::string FeaturesStr;
287 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
288 SubtargetFeatures Features;
289 Features.setCPU(TargetOpts.CPU);
290 for (std::vector<std::string>::const_iterator
291 it = TargetOpts.Features.begin(),
292 ie = TargetOpts.Features.end(); it != ie; ++it)
293 Features.AddFeature(*it);
294 FeaturesStr = Features.getString();
295 }
296 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
297
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
Dan Gohmand68fc052010-02-28 00:55:40 +0000317 // Request that addPassesToEmitFile run the Verifier after running
318 // passes which modify the IR.
319#ifndef NDEBUG
320 bool DisableVerify = false;
321#else
322 bool DisableVerify = true;
323#endif
324
Daniel Dunbarda1573f2010-02-03 01:18:43 +0000325 // Normal mode, emit a .s or .o file by running the code generator. Note,
326 // this also adds codegenerator level optimization passes.
327 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
328 if (Action == Backend_EmitObj)
329 CGFT = TargetMachine::CGFT_ObjectFile;
John McCall468ec6c2010-03-04 04:29:44 +0000330 if (TM->addPassesToEmitFile(*PM, FormattedOutStream, CGFT, OptLevel,
331 DisableVerify)) {
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000332 Diags.Report(diag::err_fe_unable_to_interface_with_target);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000333 return false;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000334 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000335 }
336
337 return true;
338}
339
340void BackendConsumer::CreatePasses() {
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000341 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
342 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000343
344 // Handle disabling of LLVM optimization, where we want to preserve the
345 // internal module before any optimization.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000346 if (CodeGenOpts.DisableLLVMOpts) {
Daniel Dunbar8d353142009-11-10 17:50:53 +0000347 OptLevel = 0;
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000348 Inlining = CodeGenOpts.NoInlining;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000349 }
350
Daniel Dunbar70f92432008-10-23 05:50:47 +0000351 // In -O0 if checking is disabled, we don't even have per-function passes.
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000352 if (CodeGenOpts.VerifyModule)
Daniel Dunbar70f92432008-10-23 05:50:47 +0000353 getPerFunctionPasses()->add(createVerifierPass());
354
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000355 // Assume that standard function passes aren't run for -O0.
Daniel Dunbar8d353142009-11-10 17:50:53 +0000356 if (OptLevel > 0)
357 llvm::createStandardFunctionPasses(getPerFunctionPasses(), OptLevel);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000358
359 llvm::Pass *InliningPass = 0;
Daniel Dunbar8d353142009-11-10 17:50:53 +0000360 switch (Inlining) {
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000361 case CodeGenOptions::NoInlining: break;
362 case CodeGenOptions::NormalInlining: {
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000363 // Set the inline threshold following llvm-gcc.
364 //
365 // FIXME: Derive these constants in a principled fashion.
Daniel Dunbar9da55982010-02-05 07:32:37 +0000366 unsigned Threshold = 225;
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000367 if (CodeGenOpts.OptimizeSize)
Daniel Dunbar9da55982010-02-05 07:32:37 +0000368 Threshold = 75;
Daniel Dunbar90de51f2009-12-08 23:15:55 +0000369 else if (OptLevel > 2)
Daniel Dunbar9da55982010-02-05 07:32:37 +0000370 Threshold = 275;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000371 InliningPass = createFunctionInliningPass(Threshold);
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000372 break;
Eli Friedmanb9b7dd62009-06-11 20:33:41 +0000373 }
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000374 case CodeGenOptions::OnlyAlwaysInlining:
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000375 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
376 break;
Daniel Dunbar70f92432008-10-23 05:50:47 +0000377 }
378
379 // For now we always create per module passes.
380 PassManager *PM = getPerModulePasses();
Chandler Carruth2811ccf2009-11-12 17:24:48 +0000381 llvm::createStandardModulePasses(PM, OptLevel, CodeGenOpts.OptimizeSize,
382 CodeGenOpts.UnitAtATime,
383 CodeGenOpts.UnrollLoops,
Daniel Dunbar3636e1d2009-11-30 08:39:32 +0000384 /*SimplifyLibCalls=*/!LangOpts.NoBuiltin,
Daniel Dunbar10d861e2009-06-03 18:01:18 +0000385 /*HaveExceptions=*/true,
386 InliningPass);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000387}
388
389/// EmitAssembly - Handle interaction with LLVM backend to generate
Mike Stump1eb44332009-09-09 15:08:12 +0000390/// actual machine code.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000391void BackendConsumer::EmitAssembly() {
392 // Silently ignore if we weren't initialized for some reason.
393 if (!TheModule || !TheTargetData)
394 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000396 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000397
Daniel Dunbard611bac2008-10-27 20:40:41 +0000398 // Make sure IR generation is happy with the module. This is
399 // released by the module provider.
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000400 Module *M = Gen->ReleaseModule();
401 if (!M) {
Daniel Dunbard611bac2008-10-27 20:40:41 +0000402 // The module has been released by IR gen on failures, do not
403 // double free.
Daniel Dunbarb954e982010-02-25 04:37:50 +0000404 TheModule.take();
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000405 return;
406 }
407
Daniel Dunbarb954e982010-02-25 04:37:50 +0000408 assert(TheModule.get() == M &&
409 "Unexpected module change during IR generation");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000410
411 CreatePasses();
Daniel Dunbar3be0d192009-12-03 09:12:54 +0000412 if (!AddEmitPasses())
413 return;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000414
415 // Run passes. For now we do all passes at once, but eventually we
416 // would like to have the option of streaming code generation.
417
418 if (PerFunctionPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000419 PrettyStackTraceString CrashInfo("Per-function optimization");
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000421 PerFunctionPasses->doInitialization();
422 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
423 if (!I->isDeclaration())
424 PerFunctionPasses->run(*I);
425 PerFunctionPasses->doFinalization();
426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattner49f28ca2009-03-05 08:00:35 +0000428 if (PerModulePasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000429 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000430 PerModulePasses->run(*M);
Chris Lattner49f28ca2009-03-05 08:00:35 +0000431 }
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000433 if (CodeGenPasses) {
Chris Lattner14f234e2009-03-06 06:46:31 +0000434 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000435 CodeGenPasses->doInitialization();
436 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
437 if (!I->isDeclaration())
438 CodeGenPasses->run(*I);
439 CodeGenPasses->doFinalization();
440 }
441}
442
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000443//
444
445CodeGenAction::CodeGenAction(unsigned _Act) : Act(_Act) {}
446
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000447CodeGenAction::~CodeGenAction() {}
448
Daniel Dunbarb954e982010-02-25 04:37:50 +0000449void CodeGenAction::EndSourceFileAction() {
450 // If the consumer creation failed, do nothing.
451 if (!getCompilerInstance().hasASTConsumer())
452 return;
453
454 // Steal the module from the consumer.
455 BackendConsumer *Consumer = static_cast<BackendConsumer*>(
456 &getCompilerInstance().getASTConsumer());
457
458 TheModule.reset(Consumer->takeModule());
459}
460
461llvm::Module *CodeGenAction::takeModule() {
462 return TheModule.take();
463}
464
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000465ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
466 llvm::StringRef InFile) {
467 BackendAction BA = static_cast<BackendAction>(Act);
468 llvm::OwningPtr<llvm::raw_ostream> OS;
469 switch (BA) {
470 case Backend_EmitAssembly:
471 OS.reset(CI.createDefaultOutputFile(false, InFile, "s"));
472 break;
473 case Backend_EmitLL:
474 OS.reset(CI.createDefaultOutputFile(false, InFile, "ll"));
475 break;
476 case Backend_EmitBC:
477 OS.reset(CI.createDefaultOutputFile(true, InFile, "bc"));
478 break;
479 case Backend_EmitNothing:
480 break;
481 case Backend_EmitObj:
482 OS.reset(CI.createDefaultOutputFile(true, InFile, "o"));
483 break;
484 }
485 if (BA != Backend_EmitNothing && !OS)
486 return 0;
487
John McCall468ec6c2010-03-04 04:29:44 +0000488 return new BackendConsumer(BA, CI.getDiagnostics(), CI.getLangOpts(),
489 CI.getCodeGenOpts(), CI.getTargetOpts(),
490 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000491 CI.getLLVMContext());
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000492}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000493
494EmitAssemblyAction::EmitAssemblyAction()
495 : CodeGenAction(Backend_EmitAssembly) {}
496
497EmitBCAction::EmitBCAction() : CodeGenAction(Backend_EmitBC) {}
498
499EmitLLVMAction::EmitLLVMAction() : CodeGenAction(Backend_EmitLL) {}
500
501EmitLLVMOnlyAction::EmitLLVMOnlyAction() : CodeGenAction(Backend_EmitNothing) {}
502
503EmitObjAction::EmitObjAction() : CodeGenAction(Backend_EmitObj) {}