blob: 9897b1b1a028f50e31e85d381ca87f1350ff6e9c [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"
33using namespace clang;
34using namespace llvm;
35
36namespace {
37
38class EmitAssemblyHelper {
39 Diagnostic &Diags;
40 const CodeGenOptions &CodeGenOpts;
41 const TargetOptions &TargetOpts;
42 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000043
44 Timer CodeGenerationTime;
45
Daniel Dunbardb2f2372010-09-17 07:35:16 +000046 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000047 mutable PassManager *PerModulePasses;
48 mutable FunctionPassManager *PerFunctionPasses;
49
50private:
Daniel Dunbardb2f2372010-09-17 07:35:16 +000051 PassManager *getCodeGenPasses() const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000052 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000053 CodeGenPasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000054 CodeGenPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000055 }
56 return CodeGenPasses;
57 }
58
59 PassManager *getPerModulePasses() const {
60 if (!PerModulePasses) {
61 PerModulePasses = new PassManager();
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000062 PerModulePasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000063 }
64 return PerModulePasses;
65 }
66
67 FunctionPassManager *getPerFunctionPasses() const {
68 if (!PerFunctionPasses) {
69 PerFunctionPasses = new FunctionPassManager(TheModule);
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000070 PerFunctionPasses->add(new TargetData(TheModule));
Daniel Dunbar897c6762010-06-07 23:20:08 +000071 }
72 return PerFunctionPasses;
73 }
74
75 void CreatePasses();
76
77 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
78 ///
79 /// \return True on success.
80 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
81
82public:
83 EmitAssemblyHelper(Diagnostic &_Diags,
84 const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000085 Module *M)
Daniel Dunbar897c6762010-06-07 23:20:08 +000086 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000087 TheModule(M), CodeGenerationTime("Code Generation Time"),
Daniel Dunbar897c6762010-06-07 23:20:08 +000088 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
89
90 ~EmitAssemblyHelper() {
91 delete CodeGenPasses;
92 delete PerModulePasses;
93 delete PerFunctionPasses;
94 }
95
96 void EmitAssembly(BackendAction Action, raw_ostream *OS);
97};
98
99}
100
101void EmitAssemblyHelper::CreatePasses() {
102 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
103 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
104
105 // Handle disabling of LLVM optimization, where we want to preserve the
106 // internal module before any optimization.
107 if (CodeGenOpts.DisableLLVMOpts) {
108 OptLevel = 0;
109 Inlining = CodeGenOpts.NoInlining;
110 }
Chris Lattnerdf619762011-02-18 22:20:38 +0000111
112 FunctionPassManager *FPM = getPerFunctionPasses();
113
Chris Lattner98ec3f72011-02-18 22:34:47 +0000114 TargetLibraryInfo *TLI =
115 new TargetLibraryInfo(Triple(TheModule->getTargetTriple()));
116 if (!CodeGenOpts.SimplifyLibCalls)
117 TLI->disableAllFunctions();
118 FPM->add(TLI);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000119
120 // In -O0 if checking is disabled, we don't even have per-function passes.
121 if (CodeGenOpts.VerifyModule)
Chris Lattnerdf619762011-02-18 22:20:38 +0000122 FPM->add(createVerifierPass());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000123
124 // Assume that standard function passes aren't run for -O0.
125 if (OptLevel > 0)
Chris Lattnerdf619762011-02-18 22:20:38 +0000126 llvm::createStandardFunctionPasses(FPM, OptLevel);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000127
128 llvm::Pass *InliningPass = 0;
129 switch (Inlining) {
130 case CodeGenOptions::NoInlining: break;
131 case CodeGenOptions::NormalInlining: {
132 // Set the inline threshold following llvm-gcc.
133 //
134 // FIXME: Derive these constants in a principled fashion.
135 unsigned Threshold = 225;
136 if (CodeGenOpts.OptimizeSize)
137 Threshold = 75;
138 else if (OptLevel > 2)
139 Threshold = 275;
140 InliningPass = createFunctionInliningPass(Threshold);
141 break;
142 }
143 case CodeGenOptions::OnlyAlwaysInlining:
144 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
145 break;
146 }
147
Chris Lattnerdf619762011-02-18 22:20:38 +0000148 PassManager *MPM = getPerModulePasses();
149
Chris Lattner98ec3f72011-02-18 22:34:47 +0000150 TLI = new TargetLibraryInfo(Triple(TheModule->getTargetTriple()));
151 if (!CodeGenOpts.SimplifyLibCalls)
152 TLI->disableAllFunctions();
153 MPM->add(TLI);
Chris Lattnerdf619762011-02-18 22:20:38 +0000154
Daniel Dunbar897c6762010-06-07 23:20:08 +0000155 // For now we always create per module passes.
Chris Lattnerdf619762011-02-18 22:20:38 +0000156 llvm::createStandardModulePasses(MPM, OptLevel,
Daniel Dunbar897c6762010-06-07 23:20:08 +0000157 CodeGenOpts.OptimizeSize,
158 CodeGenOpts.UnitAtATime,
159 CodeGenOpts.UnrollLoops,
160 CodeGenOpts.SimplifyLibCalls,
161 /*HaveExceptions=*/true,
162 InliningPass);
163}
164
165bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
166 formatted_raw_ostream &OS) {
167 // Create the TargetMachine for generating code.
168 std::string Error;
169 std::string Triple = TheModule->getTargetTriple();
170 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
171 if (!TheTarget) {
172 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
173 return false;
174 }
175
176 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
177 // being gross, this is also totally broken if we ever care about
178 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000179
180 // Set frame pointer elimination mode.
181 if (!CodeGenOpts.DisableFPElim) {
182 llvm::NoFramePointerElim = false;
183 llvm::NoFramePointerElimNonLeaf = false;
184 } else if (CodeGenOpts.OmitLeafFramePointer) {
185 llvm::NoFramePointerElim = false;
186 llvm::NoFramePointerElimNonLeaf = true;
187 } else {
188 llvm::NoFramePointerElim = true;
189 llvm::NoFramePointerElimNonLeaf = true;
190 }
191
192 // Set float ABI type.
Daniel Dunbar897c6762010-06-07 23:20:08 +0000193 if (CodeGenOpts.FloatABI == "soft")
194 llvm::FloatABIType = llvm::FloatABI::Soft;
195 else if (CodeGenOpts.FloatABI == "hard")
196 llvm::FloatABIType = llvm::FloatABI::Hard;
197 else {
198 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
199 llvm::FloatABIType = llvm::FloatABI::Default;
200 }
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000201
Peter Collingbourne4400cb82010-12-04 01:51:33 +0000202 llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
Peter Collingbourne5d729a32010-12-04 01:51:05 +0000203 llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
204 llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000205 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
Peter Collingbourne5f67e132010-12-04 01:51:14 +0000206 llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000207 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
208 UnwindTablesMandatory = CodeGenOpts.UnwindTables;
209
210 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
211
212 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
213 TargetMachine::setDataSections (CodeGenOpts.DataSections);
214
215 // FIXME: Parse this earlier.
216 if (CodeGenOpts.RelocationModel == "static") {
217 TargetMachine::setRelocationModel(llvm::Reloc::Static);
218 } else if (CodeGenOpts.RelocationModel == "pic") {
219 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
220 } else {
221 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
222 "Invalid PIC model!");
223 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
224 }
225 // FIXME: Parse this earlier.
226 if (CodeGenOpts.CodeModel == "small") {
227 TargetMachine::setCodeModel(llvm::CodeModel::Small);
228 } else if (CodeGenOpts.CodeModel == "kernel") {
229 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
230 } else if (CodeGenOpts.CodeModel == "medium") {
231 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
232 } else if (CodeGenOpts.CodeModel == "large") {
233 TargetMachine::setCodeModel(llvm::CodeModel::Large);
234 } else {
235 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
236 TargetMachine::setCodeModel(llvm::CodeModel::Default);
237 }
238
239 std::vector<const char *> BackendArgs;
240 BackendArgs.push_back("clang"); // Fake program name.
241 if (!CodeGenOpts.DebugPass.empty()) {
242 BackendArgs.push_back("-debug-pass");
243 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
244 }
245 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
246 BackendArgs.push_back("-limit-float-precision");
247 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
248 }
249 if (llvm::TimePassesIsEnabled)
250 BackendArgs.push_back("-time-passes");
251 BackendArgs.push_back(0);
252 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
253 const_cast<char **>(&BackendArgs[0]));
254
255 std::string FeaturesStr;
256 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
257 SubtargetFeatures Features;
258 Features.setCPU(TargetOpts.CPU);
259 for (std::vector<std::string>::const_iterator
260 it = TargetOpts.Features.begin(),
261 ie = TargetOpts.Features.end(); it != ie; ++it)
262 Features.AddFeature(*it);
263 FeaturesStr = Features.getString();
264 }
265 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
266
267 if (CodeGenOpts.RelaxAll)
268 TM->setMCRelaxAll(true);
269
270 // Create the code generator passes.
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000271 PassManager *PM = getCodeGenPasses();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000272 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
273
274 switch (CodeGenOpts.OptimizationLevel) {
275 default: break;
276 case 0: OptLevel = CodeGenOpt::None; break;
277 case 3: OptLevel = CodeGenOpt::Aggressive; break;
278 }
279
280 // Normal mode, emit a .s or .o file by running the code generator. Note,
281 // this also adds codegenerator level optimization passes.
282 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
283 if (Action == Backend_EmitObj)
284 CGFT = TargetMachine::CGFT_ObjectFile;
285 else if (Action == Backend_EmitMCNull)
286 CGFT = TargetMachine::CGFT_Null;
287 else
288 assert(Action == Backend_EmitAssembly && "Invalid action!");
289 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
290 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
291 Diags.Report(diag::err_fe_unable_to_interface_with_target);
292 return false;
293 }
294
295 return true;
296}
297
298void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
299 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
300 llvm::formatted_raw_ostream FormattedOS;
301
302 CreatePasses();
303 switch (Action) {
304 case Backend_EmitNothing:
305 break;
306
307 case Backend_EmitBC:
308 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
309 break;
310
311 case Backend_EmitLL:
312 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
313 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
314 break;
315
316 default:
317 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
318 if (!AddEmitPasses(Action, FormattedOS))
319 return;
320 }
321
322 // Run passes. For now we do all passes at once, but eventually we
323 // would like to have the option of streaming code generation.
324
325 if (PerFunctionPasses) {
326 PrettyStackTraceString CrashInfo("Per-function optimization");
327
328 PerFunctionPasses->doInitialization();
329 for (Module::iterator I = TheModule->begin(),
330 E = TheModule->end(); I != E; ++I)
331 if (!I->isDeclaration())
332 PerFunctionPasses->run(*I);
333 PerFunctionPasses->doFinalization();
334 }
335
336 if (PerModulePasses) {
337 PrettyStackTraceString CrashInfo("Per-module optimization passes");
338 PerModulePasses->run(*TheModule);
339 }
340
341 if (CodeGenPasses) {
342 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000343 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000344 }
345}
346
347void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
348 const TargetOptions &TOpts, Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000349 BackendAction Action, raw_ostream *OS) {
350 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000351
352 AsmHelper.EmitAssembly(Action, OS);
353}