blob: 6b389a6a3bd97cec4e55c2026deb6069309c1315 [file] [log] [blame]
Daniel Dunbarf976d1b2010-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
10#include "clang/Frontend/BackendUtil.h"
11#include "clang/Basic/Diagnostic.h"
12#include "clang/Basic/TargetOptions.h"
13#include "clang/CodeGen/CodeGenOptions.h"
14#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;
42 TargetData *TheTargetData;
43
44 Timer CodeGenerationTime;
45
46 mutable FunctionPassManager *CodeGenPasses;
47 mutable PassManager *PerModulePasses;
48 mutable FunctionPassManager *PerFunctionPasses;
49
50private:
51 FunctionPassManager *getCodeGenPasses() const {
52 if (!CodeGenPasses) {
53 CodeGenPasses = new FunctionPassManager(TheModule);
54 CodeGenPasses->add(new TargetData(*TheTargetData));
55 }
56 return CodeGenPasses;
57 }
58
59 PassManager *getPerModulePasses() const {
60 if (!PerModulePasses) {
61 PerModulePasses = new PassManager();
62 PerModulePasses->add(new TargetData(*TheTargetData));
63 }
64 return PerModulePasses;
65 }
66
67 FunctionPassManager *getPerFunctionPasses() const {
68 if (!PerFunctionPasses) {
69 PerFunctionPasses = new FunctionPassManager(TheModule);
70 PerFunctionPasses->add(new TargetData(*TheTargetData));
71 }
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,
85 Module *M, TargetData *TD)
86 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
87 TheModule(M), TheTargetData(TD),
88 CodeGenerationTime("Code Generation Time"),
89 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 }
112
113 // In -O0 if checking is disabled, we don't even have per-function passes.
114 if (CodeGenOpts.VerifyModule)
115 getPerFunctionPasses()->add(createVerifierPass());
116
117 // Assume that standard function passes aren't run for -O0.
118 if (OptLevel > 0)
119 llvm::createStandardFunctionPasses(getPerFunctionPasses(), OptLevel);
120
121 llvm::Pass *InliningPass = 0;
122 switch (Inlining) {
123 case CodeGenOptions::NoInlining: break;
124 case CodeGenOptions::NormalInlining: {
125 // Set the inline threshold following llvm-gcc.
126 //
127 // FIXME: Derive these constants in a principled fashion.
128 unsigned Threshold = 225;
129 if (CodeGenOpts.OptimizeSize)
130 Threshold = 75;
131 else if (OptLevel > 2)
132 Threshold = 275;
133 InliningPass = createFunctionInliningPass(Threshold);
134 break;
135 }
136 case CodeGenOptions::OnlyAlwaysInlining:
137 InliningPass = createAlwaysInlinerPass(); // Respect always_inline
138 break;
139 }
140
141 // For now we always create per module passes.
142 llvm::createStandardModulePasses(getPerModulePasses(), OptLevel,
143 CodeGenOpts.OptimizeSize,
144 CodeGenOpts.UnitAtATime,
145 CodeGenOpts.UnrollLoops,
146 CodeGenOpts.SimplifyLibCalls,
147 /*HaveExceptions=*/true,
148 InliningPass);
149}
150
151bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
152 formatted_raw_ostream &OS) {
153 // Create the TargetMachine for generating code.
154 std::string Error;
155 std::string Triple = TheModule->getTargetTriple();
156 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
157 if (!TheTarget) {
158 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
159 return false;
160 }
161
162 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
163 // being gross, this is also totally broken if we ever care about
164 // concurrency.
165 llvm::NoFramePointerElim = CodeGenOpts.DisableFPElim;
166 if (CodeGenOpts.FloatABI == "soft")
167 llvm::FloatABIType = llvm::FloatABI::Soft;
168 else if (CodeGenOpts.FloatABI == "hard")
169 llvm::FloatABIType = llvm::FloatABI::Hard;
170 else {
171 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
172 llvm::FloatABIType = llvm::FloatABI::Default;
173 }
174 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
175 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
176 UnwindTablesMandatory = CodeGenOpts.UnwindTables;
177
178 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
179
180 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
181 TargetMachine::setDataSections (CodeGenOpts.DataSections);
182
183 // FIXME: Parse this earlier.
184 if (CodeGenOpts.RelocationModel == "static") {
185 TargetMachine::setRelocationModel(llvm::Reloc::Static);
186 } else if (CodeGenOpts.RelocationModel == "pic") {
187 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
188 } else {
189 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
190 "Invalid PIC model!");
191 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
192 }
193 // FIXME: Parse this earlier.
194 if (CodeGenOpts.CodeModel == "small") {
195 TargetMachine::setCodeModel(llvm::CodeModel::Small);
196 } else if (CodeGenOpts.CodeModel == "kernel") {
197 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
198 } else if (CodeGenOpts.CodeModel == "medium") {
199 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
200 } else if (CodeGenOpts.CodeModel == "large") {
201 TargetMachine::setCodeModel(llvm::CodeModel::Large);
202 } else {
203 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
204 TargetMachine::setCodeModel(llvm::CodeModel::Default);
205 }
206
207 std::vector<const char *> BackendArgs;
208 BackendArgs.push_back("clang"); // Fake program name.
209 if (!CodeGenOpts.DebugPass.empty()) {
210 BackendArgs.push_back("-debug-pass");
211 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
212 }
213 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
214 BackendArgs.push_back("-limit-float-precision");
215 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
216 }
217 if (llvm::TimePassesIsEnabled)
218 BackendArgs.push_back("-time-passes");
219 BackendArgs.push_back(0);
220 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
221 const_cast<char **>(&BackendArgs[0]));
222
223 std::string FeaturesStr;
224 if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
225 SubtargetFeatures Features;
226 Features.setCPU(TargetOpts.CPU);
227 for (std::vector<std::string>::const_iterator
228 it = TargetOpts.Features.begin(),
229 ie = TargetOpts.Features.end(); it != ie; ++it)
230 Features.AddFeature(*it);
231 FeaturesStr = Features.getString();
232 }
233 TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
234
235 if (CodeGenOpts.RelaxAll)
236 TM->setMCRelaxAll(true);
237
238 // Create the code generator passes.
239 FunctionPassManager *PM = getCodeGenPasses();
240 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
241
242 switch (CodeGenOpts.OptimizationLevel) {
243 default: break;
244 case 0: OptLevel = CodeGenOpt::None; break;
245 case 3: OptLevel = CodeGenOpt::Aggressive; break;
246 }
247
248 // Normal mode, emit a .s or .o file by running the code generator. Note,
249 // this also adds codegenerator level optimization passes.
250 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
251 if (Action == Backend_EmitObj)
252 CGFT = TargetMachine::CGFT_ObjectFile;
253 else if (Action == Backend_EmitMCNull)
254 CGFT = TargetMachine::CGFT_Null;
255 else
256 assert(Action == Backend_EmitAssembly && "Invalid action!");
257 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
258 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
259 Diags.Report(diag::err_fe_unable_to_interface_with_target);
260 return false;
261 }
262
263 return true;
264}
265
266void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
267 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
268 llvm::formatted_raw_ostream FormattedOS;
269
270 CreatePasses();
271 switch (Action) {
272 case Backend_EmitNothing:
273 break;
274
275 case Backend_EmitBC:
276 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
277 break;
278
279 case Backend_EmitLL:
280 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
281 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
282 break;
283
284 default:
285 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
286 if (!AddEmitPasses(Action, FormattedOS))
287 return;
288 }
289
290 // Run passes. For now we do all passes at once, but eventually we
291 // would like to have the option of streaming code generation.
292
293 if (PerFunctionPasses) {
294 PrettyStackTraceString CrashInfo("Per-function optimization");
295
296 PerFunctionPasses->doInitialization();
297 for (Module::iterator I = TheModule->begin(),
298 E = TheModule->end(); I != E; ++I)
299 if (!I->isDeclaration())
300 PerFunctionPasses->run(*I);
301 PerFunctionPasses->doFinalization();
302 }
303
304 if (PerModulePasses) {
305 PrettyStackTraceString CrashInfo("Per-module optimization passes");
306 PerModulePasses->run(*TheModule);
307 }
308
309 if (CodeGenPasses) {
310 PrettyStackTraceString CrashInfo("Code generation");
311
312 CodeGenPasses->doInitialization();
313 for (Module::iterator I = TheModule->begin(),
314 E = TheModule->end(); I != E; ++I)
315 if (!I->isDeclaration())
316 CodeGenPasses->run(*I);
317 CodeGenPasses->doFinalization();
318 }
319}
320
321void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
322 const TargetOptions &TOpts, Module *M,
323 TargetData *TD, BackendAction Action,
324 raw_ostream *OS) {
325 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M, TD);
326
327 AsmHelper.EmitAssembly(Action, OS);
328}