blob: e6570d4086677982855e66233878688a8520dc96 [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"
Chandler Carruth06057ce2010-06-15 23:19:56 +000013#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000014#include "clang/Frontend/FrontendDiagnostic.h"
15#include "llvm/Module.h"
16#include "llvm/PassManager.h"
17#include "llvm/Assembly/PrintModulePass.h"
18#include "llvm/Bitcode/ReaderWriter.h"
19#include "llvm/CodeGen/RegAllocRegistry.h"
20#include "llvm/CodeGen/SchedulerRegistry.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/FormattedStream.h"
23#include "llvm/Support/PrettyStackTrace.h"
24#include "llvm/Support/StandardPasses.h"
25#include "llvm/Support/Timer.h"
26#include "llvm/Support/raw_ostream.h"
27#include "llvm/Target/SubtargetFeature.h"
28#include "llvm/Target/TargetData.h"
Chris Lattnerdf619762011-02-18 22:20:38 +000029#include "llvm/Target/TargetLibraryInfo.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000030#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;
43 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000044
45 Timer CodeGenerationTime;
46
Daniel Dunbardb2f2372010-09-17 07:35:16 +000047 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000048 mutable PassManager *PerModulePasses;
49 mutable FunctionPassManager *PerFunctionPasses;
50
51private:
Daniel Dunbardb2f2372010-09-17 07:35:16 +000052 PassManager *getCodeGenPasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000053 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000054 CodeGenPasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000055 CodeGenPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000056 }
57 return CodeGenPasses;
58 }
59
60 PassManager *getPerModulePasses() const {
61 if (!PerModulePasses) {
62 PerModulePasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000063 PerModulePasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000064 }
65 return PerModulePasses;
66 }
67
68 FunctionPassManager *getPerFunctionPasses() const {
69 if (!PerFunctionPasses) {
70 PerFunctionPasses = new FunctionPassManager(TheModule);
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000071 PerFunctionPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000072 }
73 return PerFunctionPasses;
74 }
75
76 void CreatePasses();
77
78 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
79 ///
80 /// \return True on success.
81 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
82
83public:
84 EmitAssemblyHelper(Diagnostic &_Diags,
85 const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000086 Module *M)
Daniel Dunbar897c6762010-06-07 23:20:08 +000087 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000088 TheModule(M), CodeGenerationTime("Code Generation Time"),
Daniel Dunbar897c6762010-06-07 23:20:08 +000089 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
90
91 ~EmitAssemblyHelper() {
92 delete CodeGenPasses;
93 delete PerModulePasses;
94 delete PerFunctionPasses;
95 }
96
97 void EmitAssembly(BackendAction Action, raw_ostream *OS);
98};
99
100}
101
102void EmitAssemblyHelper::CreatePasses() {
103 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
104 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
105
106 // Handle disabling of LLVM optimization, where we want to preserve the
107 // internal module before any optimization.
108 if (CodeGenOpts.DisableLLVMOpts) {
109 OptLevel = 0;
110 Inlining = CodeGenOpts.NoInlining;
111 }
Andrew Trick6445d622011-04-05 18:49:32 +0000112
Chris Lattnerdf619762011-02-18 22:20:38 +0000113 FunctionPassManager *FPM = getPerFunctionPasses();
Andrew Trick6445d622011-04-05 18:49:32 +0000114
Bill Wendling3621b312011-05-17 23:06:23 +0000115 Triple TargetTriple(TheModule->getTargetTriple());
116 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000117 if (!CodeGenOpts.SimplifyLibCalls)
118 TLI->disableAllFunctions();
119 FPM->add(TLI);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000120
121 // In -O0 if checking is disabled, we don't even have per-function passes.
122 if (CodeGenOpts.VerifyModule)
Chris Lattnerdf619762011-02-18 22:20:38 +0000123 FPM->add(createVerifierPass());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000124
125 // Assume that standard function passes aren't run for -O0.
126 if (OptLevel > 0)
Chris Lattnerdf619762011-02-18 22:20:38 +0000127 llvm::createStandardFunctionPasses(FPM, OptLevel);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000128
129 llvm::Pass *InliningPass = 0;
130 switch (Inlining) {
131 case CodeGenOptions::NoInlining: break;
132 case CodeGenOptions::NormalInlining: {
133 // Set the inline threshold following llvm-gcc.
134 //
135 // FIXME: Derive these constants in a principled fashion.
136 unsigned Threshold = 225;
Bob Wilsona0fa2032011-04-29 22:49:50 +0000137 if (CodeGenOpts.OptimizeSize == 1) //-Os
Daniel Dunbar897c6762010-06-07 23:20:08 +0000138 Threshold = 75;
Bob Wilsona0fa2032011-04-29 22:49:50 +0000139 else if (CodeGenOpts.OptimizeSize == 2) //-Oz
140 Threshold = 25;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000141 else if (OptLevel > 2)
142 Threshold = 275;
143 InliningPass = createFunctionInliningPass(Threshold);
144 break;
145 }
146 case CodeGenOptions::OnlyAlwaysInlining:
147 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
148 break;
149 }
150
Chris Lattnerdf619762011-02-18 22:20:38 +0000151 PassManager *MPM = getPerModulePasses();
Andrew Trick6445d622011-04-05 18:49:32 +0000152
Bill Wendling3621b312011-05-17 23:06:23 +0000153 TLI = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000154 if (!CodeGenOpts.SimplifyLibCalls)
155 TLI->disableAllFunctions();
156 MPM->add(TLI);
Chris Lattnerdf619762011-02-18 22:20:38 +0000157
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000158 if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
159 MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
Bill Wendling3621b312011-05-17 23:06:23 +0000160 CodeGenOpts.EmitGcovArcs,
161 TargetTriple.isMacOSX()));
162
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000163 if (!CodeGenOpts.DebugInfo)
164 MPM->add(createStripSymbolsPass(true));
165 }
166
Daniel Dunbar897c6762010-06-07 23:20:08 +0000167 // For now we always create per module passes.
Chris Lattnerdf619762011-02-18 22:20:38 +0000168 llvm::createStandardModulePasses(MPM, OptLevel,
Daniel Dunbar897c6762010-06-07 23:20:08 +0000169 CodeGenOpts.OptimizeSize,
170 CodeGenOpts.UnitAtATime,
171 CodeGenOpts.UnrollLoops,
172 CodeGenOpts.SimplifyLibCalls,
173 /*HaveExceptions=*/true,
174 InliningPass);
175}
176
177bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
178 formatted_raw_ostream &OS) {
179 // Create the TargetMachine for generating code.
180 std::string Error;
181 std::string Triple = TheModule->getTargetTriple();
182 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
183 if (!TheTarget) {
184 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
185 return false;
186 }
187
188 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
189 // being gross, this is also totally broken if we ever care about
190 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000191
192 // Set frame pointer elimination mode.
193 if (!CodeGenOpts.DisableFPElim) {
194 llvm::NoFramePointerElim = false;
195 llvm::NoFramePointerElimNonLeaf = false;
196 } else if (CodeGenOpts.OmitLeafFramePointer) {
197 llvm::NoFramePointerElim = false;
198 llvm::NoFramePointerElimNonLeaf = true;
199 } else {
200 llvm::NoFramePointerElim = true;
201 llvm::NoFramePointerElimNonLeaf = true;
202 }
203
204 // Set float ABI type.
Sandeep Patel34c1af82011-04-05 00:23:47 +0000205 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
Daniel Dunbar897c6762010-06-07 23:20:08 +0000206 llvm::FloatABIType = llvm::FloatABI::Soft;
207 else if (CodeGenOpts.FloatABI == "hard")
208 llvm::FloatABIType = llvm::FloatABI::Hard;
209 else {
210 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
211 llvm::FloatABIType = llvm::FloatABI::Default;
212 }
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000213
Peter Collingbourne4400cb82010-12-04 01:51:33 +0000214 llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
Peter Collingbourne5d729a32010-12-04 01:51:05 +0000215 llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
216 llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000217 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
Peter Collingbourne5f67e132010-12-04 01:51:14 +0000218 llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000219 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
220 UnwindTablesMandatory = CodeGenOpts.UnwindTables;
221
222 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
223
224 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
225 TargetMachine::setDataSections (CodeGenOpts.DataSections);
226
227 // FIXME: Parse this earlier.
228 if (CodeGenOpts.RelocationModel == "static") {
229 TargetMachine::setRelocationModel(llvm::Reloc::Static);
230 } else if (CodeGenOpts.RelocationModel == "pic") {
231 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
232 } else {
233 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
234 "Invalid PIC model!");
235 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
236 }
237 // FIXME: Parse this earlier.
238 if (CodeGenOpts.CodeModel == "small") {
239 TargetMachine::setCodeModel(llvm::CodeModel::Small);
240 } else if (CodeGenOpts.CodeModel == "kernel") {
241 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
242 } else if (CodeGenOpts.CodeModel == "medium") {
243 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
244 } else if (CodeGenOpts.CodeModel == "large") {
245 TargetMachine::setCodeModel(llvm::CodeModel::Large);
246 } else {
247 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
248 TargetMachine::setCodeModel(llvm::CodeModel::Default);
249 }
250
251 std::vector<const char *> BackendArgs;
252 BackendArgs.push_back("clang"); // Fake program name.
253 if (!CodeGenOpts.DebugPass.empty()) {
254 BackendArgs.push_back("-debug-pass");
255 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
256 }
257 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
258 BackendArgs.push_back("-limit-float-precision");
259 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
260 }
261 if (llvm::TimePassesIsEnabled)
262 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000263 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
264 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000265 BackendArgs.push_back(0);
266 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
267 const_cast<char **>(&BackendArgs[0]));
268
269 std::string FeaturesStr;
270 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
271 SubtargetFeatures Features;
272 Features.setCPU(TargetOpts.CPU);
273 for (std::vector<std::string>::const_iterator
274 it = TargetOpts.Features.begin(),
275 ie = TargetOpts.Features.end(); it != ie; ++it)
276 Features.AddFeature(*it);
277 FeaturesStr = Features.getString();
278 }
279 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
280
281 if (CodeGenOpts.RelaxAll)
282 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000283 if (CodeGenOpts.SaveTempLabels)
284 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000285 if (CodeGenOpts.NoDwarf2CFIAsm)
286 TM->setMCUseCFI(false);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000287
288 // Create the code generator passes.
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000289 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000290 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
291
292 switch (CodeGenOpts.OptimizationLevel) {
293 default: break;
294 case 0: OptLevel = CodeGenOpt::None; break;
295 case 3: OptLevel = CodeGenOpt::Aggressive; break;
296 }
297
298 // Normal mode, emit a .s or .o file by running the code generator. Note,
299 // this also adds codegenerator level optimization passes.
300 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
301 if (Action == Backend_EmitObj)
302 CGFT = TargetMachine::CGFT_ObjectFile;
303 else if (Action == Backend_EmitMCNull)
304 CGFT = TargetMachine::CGFT_Null;
305 else
306 assert(Action == Backend_EmitAssembly && "Invalid action!");
307 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
308 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
309 Diags.Report(diag::err_fe_unable_to_interface_with_target);
310 return false;
311 }
312
313 return true;
314}
315
316void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
317 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
318 llvm::formatted_raw_ostream FormattedOS;
319
320 CreatePasses();
321 switch (Action) {
322 case Backend_EmitNothing:
323 break;
324
325 case Backend_EmitBC:
326 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
327 break;
328
329 case Backend_EmitLL:
330 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
331 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
332 break;
333
334 default:
335 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
336 if (!AddEmitPasses(Action, FormattedOS))
337 return;
338 }
339
Andrew Trick92b5d942011-04-05 18:56:55 +0000340 // Before executing passes, print the final values of the LLVM options.
341 cl::PrintOptionValues();
342
Daniel Dunbar897c6762010-06-07 23:20:08 +0000343 // Run passes. For now we do all passes at once, but eventually we
344 // would like to have the option of streaming code generation.
345
346 if (PerFunctionPasses) {
347 PrettyStackTraceString CrashInfo("Per-function optimization");
348
349 PerFunctionPasses->doInitialization();
350 for (Module::iterator I = TheModule->begin(),
351 E = TheModule->end(); I != E; ++I)
352 if (!I->isDeclaration())
353 PerFunctionPasses->run(*I);
354 PerFunctionPasses->doFinalization();
355 }
356
357 if (PerModulePasses) {
358 PrettyStackTraceString CrashInfo("Per-module optimization passes");
359 PerModulePasses->run(*TheModule);
360 }
361
362 if (CodeGenPasses) {
363 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000364 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000365 }
366}
367
368void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
369 const TargetOptions &TOpts, Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000370 BackendAction Action, raw_ostream *OS) {
371 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000372
373 AsmHelper.EmitAssembly(Action, OS);
374}