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