blob: d7326cdc7e370ee9d9f1f431993c855251d0fef4 [file] [log] [blame]
Daniel Dunbar897c6762010-06-07 23:20:08 +00001//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2//
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/BackendUtil.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
12#include "clang/Basic/TargetOptions.h"
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000013#include "clang/Basic/LangOptions.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000014#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000015#include "clang/Frontend/FrontendDiagnostic.h"
16#include "llvm/Module.h"
17#include "llvm/PassManager.h"
18#include "llvm/Assembly/PrintModulePass.h"
19#include "llvm/Bitcode/ReaderWriter.h"
20#include "llvm/CodeGen/RegAllocRegistry.h"
21#include "llvm/CodeGen/SchedulerRegistry.h"
Evan Cheng693769c2011-06-29 01:14:32 +000022#include "llvm/MC/SubtargetFeature.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000023#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/FormattedStream.h"
25#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner33c09d52011-05-21 20:40:11 +000026#include "llvm/Support/PassManagerBuilder.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000027#include "llvm/Support/Timer.h"
28#include "llvm/Support/raw_ostream.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000029#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Target/TargetOptions.h"
32#include "llvm/Target/TargetRegistry.h"
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000033#include "llvm/Transforms/Instrumentation.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000034using namespace clang;
35using namespace llvm;
36
37namespace {
38
39class EmitAssemblyHelper {
40 Diagnostic &Diags;
41 const CodeGenOptions &CodeGenOpts;
42 const TargetOptions &TargetOpts;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000043 const LangOptions &LangOpts;
Daniel Dunbar897c6762010-06-07 23:20:08 +000044 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000045
46 Timer CodeGenerationTime;
47
Daniel Dunbardb2f2372010-09-17 07:35:16 +000048 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000049 mutable PassManager *PerModulePasses;
50 mutable FunctionPassManager *PerFunctionPasses;
51
52private:
Daniel Dunbardb2f2372010-09-17 07:35:16 +000053 PassManager *getCodeGenPasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000054 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000055 CodeGenPasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000056 CodeGenPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000057 }
58 return CodeGenPasses;
59 }
60
61 PassManager *getPerModulePasses() const {
62 if (!PerModulePasses) {
63 PerModulePasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000064 PerModulePasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000065 }
66 return PerModulePasses;
67 }
68
69 FunctionPassManager *getPerFunctionPasses() const {
70 if (!PerFunctionPasses) {
71 PerFunctionPasses = new FunctionPassManager(TheModule);
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000072 PerFunctionPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000073 }
74 return PerFunctionPasses;
75 }
76
77 void CreatePasses();
78
79 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
80 ///
81 /// \return True on success.
82 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
83
84public:
85 EmitAssemblyHelper(Diagnostic &_Diags,
86 const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000087 const LangOptions &LOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000088 Module *M)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000089 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000090 TheModule(M), CodeGenerationTime("Code Generation Time"),
Daniel Dunbar897c6762010-06-07 23:20:08 +000091 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
92
93 ~EmitAssemblyHelper() {
94 delete CodeGenPasses;
95 delete PerModulePasses;
96 delete PerFunctionPasses;
97 }
98
99 void EmitAssembly(BackendAction Action, raw_ostream *OS);
100};
101
102}
103
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000104static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
105 if (Builder.OptLevel > 0)
106 PM.add(createObjCARCExpandPass());
107}
108
109static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
110 if (Builder.OptLevel > 0)
111 PM.add(createObjCARCOptPass());
112}
113
Daniel Dunbar897c6762010-06-07 23:20:08 +0000114void EmitAssemblyHelper::CreatePasses() {
115 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
116 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
117
118 // Handle disabling of LLVM optimization, where we want to preserve the
119 // internal module before any optimization.
120 if (CodeGenOpts.DisableLLVMOpts) {
121 OptLevel = 0;
122 Inlining = CodeGenOpts.NoInlining;
123 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000124
125 PassManagerBuilder PMBuilder;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000126 PMBuilder.OptLevel = OptLevel;
127 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Andrew Trick6445d622011-04-05 18:49:32 +0000128
Chris Lattner9ca02e52011-05-21 23:50:44 +0000129 PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
130 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
131 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000132
133 // In ObjC ARC mode, add the main ARC optimization passes.
134 if (LangOpts.ObjCAutoRefCount) {
135 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
136 addObjCARCExpandPass);
137 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
138 addObjCARCOptPass);
139 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000140
141 // Figure out TargetLibraryInfo.
Bill Wendling3621b312011-05-17 23:06:23 +0000142 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattner9ca02e52011-05-21 23:50:44 +0000143 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000144 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattner9ca02e52011-05-21 23:50:44 +0000145 PMBuilder.LibraryInfo->disableAllFunctions();
Chris Lattner33c09d52011-05-21 20:40:11 +0000146
Daniel Dunbar897c6762010-06-07 23:20:08 +0000147 switch (Inlining) {
148 case CodeGenOptions::NoInlining: break;
149 case CodeGenOptions::NormalInlining: {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000150 // FIXME: Derive these constants in a principled fashion.
151 unsigned Threshold = 225;
Chris Lattner33c09d52011-05-21 20:40:11 +0000152 if (CodeGenOpts.OptimizeSize == 1) // -Os
Daniel Dunbar897c6762010-06-07 23:20:08 +0000153 Threshold = 75;
Chris Lattner33c09d52011-05-21 20:40:11 +0000154 else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Bob Wilsona0fa2032011-04-29 22:49:50 +0000155 Threshold = 25;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000156 else if (OptLevel > 2)
157 Threshold = 275;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000158 PMBuilder.Inliner = createFunctionInliningPass(Threshold);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000159 break;
160 }
161 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner33c09d52011-05-21 20:40:11 +0000162 // Respect always_inline.
Chris Lattner9ca02e52011-05-21 23:50:44 +0000163 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000164 break;
165 }
166
Chris Lattner33c09d52011-05-21 20:40:11 +0000167
168 // Set up the per-function pass manager.
169 FunctionPassManager *FPM = getPerFunctionPasses();
170 if (CodeGenOpts.VerifyModule)
171 FPM->add(createVerifierPass());
172 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trick6445d622011-04-05 18:49:32 +0000173
Chris Lattner33c09d52011-05-21 20:40:11 +0000174 // Set up the per-module pass manager.
175 PassManager *MPM = getPerModulePasses();
Chris Lattnerdf619762011-02-18 22:20:38 +0000176
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000177 if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
178 MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
Bill Wendling3621b312011-05-17 23:06:23 +0000179 CodeGenOpts.EmitGcovArcs,
180 TargetTriple.isMacOSX()));
181
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000182 if (!CodeGenOpts.DebugInfo)
183 MPM->add(createStripSymbolsPass(true));
184 }
Chris Lattner33c09d52011-05-21 20:40:11 +0000185
186
187 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000188}
189
190bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
191 formatted_raw_ostream &OS) {
192 // Create the TargetMachine for generating code.
193 std::string Error;
194 std::string Triple = TheModule->getTargetTriple();
195 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
196 if (!TheTarget) {
197 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
198 return false;
199 }
200
201 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
202 // being gross, this is also totally broken if we ever care about
203 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000204
205 // Set frame pointer elimination mode.
206 if (!CodeGenOpts.DisableFPElim) {
207 llvm::NoFramePointerElim = false;
208 llvm::NoFramePointerElimNonLeaf = false;
209 } else if (CodeGenOpts.OmitLeafFramePointer) {
210 llvm::NoFramePointerElim = false;
211 llvm::NoFramePointerElimNonLeaf = true;
212 } else {
213 llvm::NoFramePointerElim = true;
214 llvm::NoFramePointerElimNonLeaf = true;
215 }
216
217 // Set float ABI type.
Sandeep Patel34c1af82011-04-05 00:23:47 +0000218 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
Daniel Dunbar897c6762010-06-07 23:20:08 +0000219 llvm::FloatABIType = llvm::FloatABI::Soft;
220 else if (CodeGenOpts.FloatABI == "hard")
221 llvm::FloatABIType = llvm::FloatABI::Hard;
222 else {
223 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
224 llvm::FloatABIType = llvm::FloatABI::Default;
225 }
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000226
Peter Collingbourne4400cb82010-12-04 01:51:33 +0000227 llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
Peter Collingbourne5d729a32010-12-04 01:51:05 +0000228 llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
229 llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000230 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
Peter Collingbourne5f67e132010-12-04 01:51:14 +0000231 llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000232 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000233
234 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
235
236 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
237 TargetMachine::setDataSections (CodeGenOpts.DataSections);
238
239 // FIXME: Parse this earlier.
Daniel Dunbar897c6762010-06-07 23:20:08 +0000240 if (CodeGenOpts.CodeModel == "small") {
241 TargetMachine::setCodeModel(llvm::CodeModel::Small);
242 } else if (CodeGenOpts.CodeModel == "kernel") {
243 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
244 } else if (CodeGenOpts.CodeModel == "medium") {
245 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
246 } else if (CodeGenOpts.CodeModel == "large") {
247 TargetMachine::setCodeModel(llvm::CodeModel::Large);
248 } else {
249 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
250 TargetMachine::setCodeModel(llvm::CodeModel::Default);
251 }
252
253 std::vector<const char *> BackendArgs;
254 BackendArgs.push_back("clang"); // Fake program name.
255 if (!CodeGenOpts.DebugPass.empty()) {
256 BackendArgs.push_back("-debug-pass");
257 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
258 }
259 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
260 BackendArgs.push_back("-limit-float-precision");
261 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
262 }
263 if (llvm::TimePassesIsEnabled)
264 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000265 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
266 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000267 BackendArgs.push_back(0);
268 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
269 const_cast<char **>(&BackendArgs[0]));
270
271 std::string FeaturesStr;
Evan Cheng368691e2011-06-30 02:06:32 +0000272 if (TargetOpts.Features.size()) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000273 SubtargetFeatures Features;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000274 for (std::vector<std::string>::const_iterator
275 it = TargetOpts.Features.begin(),
276 ie = TargetOpts.Features.end(); it != ie; ++it)
277 Features.AddFeature(*it);
278 FeaturesStr = Features.getString();
279 }
Evan Cheng2860e302011-07-19 06:37:41 +0000280
281 llvm::Reloc::Model RM = llvm::Reloc::Default;
282 if (CodeGenOpts.RelocationModel == "static") {
283 RM = llvm::Reloc::Static;
284 } else if (CodeGenOpts.RelocationModel == "pic") {
285 RM = llvm::Reloc::PIC_;
286 } else {
287 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
288 "Invalid PIC model!");
289 RM = llvm::Reloc::DynamicNoPIC;
290 }
291
Evan Cheng368691e2011-06-30 02:06:32 +0000292 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Evan Cheng2860e302011-07-19 06:37:41 +0000293 FeaturesStr, RM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000294
295 if (CodeGenOpts.RelaxAll)
296 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000297 if (CodeGenOpts.SaveTempLabels)
298 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000299 if (CodeGenOpts.NoDwarf2CFIAsm)
300 TM->setMCUseCFI(false);
Nick Lewyckyc3b90142011-06-21 00:14:18 +0000301 if (CodeGenOpts.NoExecStack)
302 TM->setMCNoExecStack(true);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000303
304 // Create the code generator passes.
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000305 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000306 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
307
308 switch (CodeGenOpts.OptimizationLevel) {
309 default: break;
310 case 0: OptLevel = CodeGenOpt::None; break;
311 case 3: OptLevel = CodeGenOpt::Aggressive; break;
312 }
313
314 // Normal mode, emit a .s or .o file by running the code generator. Note,
315 // this also adds codegenerator level optimization passes.
316 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
317 if (Action == Backend_EmitObj)
318 CGFT = TargetMachine::CGFT_ObjectFile;
319 else if (Action == Backend_EmitMCNull)
320 CGFT = TargetMachine::CGFT_Null;
321 else
322 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000323
324 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
325 // "codegen" passes so that it isn't run multiple times when there is
326 // inlining happening.
327 if (LangOpts.ObjCAutoRefCount)
328 PM->add(createObjCARCContractPass());
329
Daniel Dunbar897c6762010-06-07 23:20:08 +0000330 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
331 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
332 Diags.Report(diag::err_fe_unable_to_interface_with_target);
333 return false;
334 }
335
336 return true;
337}
338
339void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
340 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
341 llvm::formatted_raw_ostream FormattedOS;
342
343 CreatePasses();
344 switch (Action) {
345 case Backend_EmitNothing:
346 break;
347
348 case Backend_EmitBC:
349 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
350 break;
351
352 case Backend_EmitLL:
353 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
354 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
355 break;
356
357 default:
358 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
359 if (!AddEmitPasses(Action, FormattedOS))
360 return;
361 }
362
Andrew Trick92b5d942011-04-05 18:56:55 +0000363 // Before executing passes, print the final values of the LLVM options.
364 cl::PrintOptionValues();
365
Daniel Dunbar897c6762010-06-07 23:20:08 +0000366 // Run passes. For now we do all passes at once, but eventually we
367 // would like to have the option of streaming code generation.
368
369 if (PerFunctionPasses) {
370 PrettyStackTraceString CrashInfo("Per-function optimization");
371
372 PerFunctionPasses->doInitialization();
373 for (Module::iterator I = TheModule->begin(),
374 E = TheModule->end(); I != E; ++I)
375 if (!I->isDeclaration())
376 PerFunctionPasses->run(*I);
377 PerFunctionPasses->doFinalization();
378 }
379
380 if (PerModulePasses) {
381 PrettyStackTraceString CrashInfo("Per-module optimization passes");
382 PerModulePasses->run(*TheModule);
383 }
384
385 if (CodeGenPasses) {
386 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000387 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000388 }
389}
390
391void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000392 const TargetOptions &TOpts,
393 const LangOptions &LOpts,
394 Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000395 BackendAction Action, raw_ostream *OS) {
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000396 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000397
398 AsmHelper.EmitAssembly(Action, OS);
399}