1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/TargetOptions.h"
13 #include "clang/Basic/LangOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #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"
22 #include "llvm/MC/SubtargetFeature.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FormattedStream.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/PassManagerBuilder.h"
27 #include "llvm/Support/Timer.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/Transforms/Instrumentation.h"
34 using namespace clang;
39 class EmitAssemblyHelper {
41 const CodeGenOptions &CodeGenOpts;
42 const TargetOptions &TargetOpts;
43 const LangOptions &LangOpts;
46 Timer CodeGenerationTime;
48 mutable PassManager *CodeGenPasses;
49 mutable PassManager *PerModulePasses;
50 mutable FunctionPassManager *PerFunctionPasses;
53 PassManager *getCodeGenPasses() const {
55 CodeGenPasses = new PassManager();
56 CodeGenPasses->add(new TargetData(TheModule));
61 PassManager *getPerModulePasses() const {
62 if (!PerModulePasses) {
63 PerModulePasses = new PassManager();
64 PerModulePasses->add(new TargetData(TheModule));
66 return PerModulePasses;
69 FunctionPassManager *getPerFunctionPasses() const {
70 if (!PerFunctionPasses) {
71 PerFunctionPasses = new FunctionPassManager(TheModule);
72 PerFunctionPasses->add(new TargetData(TheModule));
74 return PerFunctionPasses;
79 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
81 /// \return True on success.
82 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
85 EmitAssemblyHelper(Diagnostic &_Diags,
86 const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
87 const LangOptions &LOpts,
89 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
90 TheModule(M), CodeGenerationTime("Code Generation Time"),
91 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
93 ~EmitAssemblyHelper() {
95 delete PerModulePasses;
96 delete PerFunctionPasses;
99 void EmitAssembly(BackendAction Action, raw_ostream *OS);
104 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
105 if (Builder.OptLevel > 0)
106 PM.add(createObjCARCExpandPass());
109 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
110 if (Builder.OptLevel > 0)
111 PM.add(createObjCARCOptPass());
114 void EmitAssemblyHelper::CreatePasses() {
115 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
116 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.Inlining;
118 // Handle disabling of LLVM optimization, where we want to preserve the
119 // internal module before any optimization.
120 if (CodeGenOpts.DisableLLVMOpts) {
122 Inlining = CodeGenOpts.NoInlining;
125 PassManagerBuilder PMBuilder;
126 PMBuilder.OptLevel = OptLevel;
127 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
129 PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
130 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
131 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
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,
141 // Figure out TargetLibraryInfo.
142 Triple TargetTriple(TheModule->getTargetTriple());
143 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
144 if (!CodeGenOpts.SimplifyLibCalls)
145 PMBuilder.LibraryInfo->disableAllFunctions();
148 case CodeGenOptions::NoInlining: break;
149 case CodeGenOptions::NormalInlining: {
150 // FIXME: Derive these constants in a principled fashion.
151 unsigned Threshold = 225;
152 if (CodeGenOpts.OptimizeSize == 1) // -Os
154 else if (CodeGenOpts.OptimizeSize == 2) // -Oz
156 else if (OptLevel > 2)
158 PMBuilder.Inliner = createFunctionInliningPass(Threshold);
161 case CodeGenOptions::OnlyAlwaysInlining:
162 // Respect always_inline.
163 PMBuilder.Inliner = createAlwaysInlinerPass();
168 // Set up the per-function pass manager.
169 FunctionPassManager *FPM = getPerFunctionPasses();
170 if (CodeGenOpts.VerifyModule)
171 FPM->add(createVerifierPass());
172 PMBuilder.populateFunctionPassManager(*FPM);
174 // Set up the per-module pass manager.
175 PassManager *MPM = getPerModulePasses();
177 if (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) {
178 MPM->add(createGCOVProfilerPass(CodeGenOpts.EmitGcovNotes,
179 CodeGenOpts.EmitGcovArcs,
180 TargetTriple.isMacOSX()));
182 if (!CodeGenOpts.DebugInfo)
183 MPM->add(createStripSymbolsPass(true));
187 PMBuilder.populateModulePassManager(*MPM);
190 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
191 formatted_raw_ostream &OS) {
192 // Create the TargetMachine for generating code.
194 std::string Triple = TheModule->getTargetTriple();
195 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
197 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
201 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
202 // being gross, this is also totally broken if we ever care about
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;
213 llvm::NoFramePointerElim = true;
214 llvm::NoFramePointerElimNonLeaf = true;
217 // Set float ABI type.
218 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
219 llvm::FloatABIType = llvm::FloatABI::Soft;
220 else if (CodeGenOpts.FloatABI == "hard")
221 llvm::FloatABIType = llvm::FloatABI::Hard;
223 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
224 llvm::FloatABIType = llvm::FloatABI::Default;
227 llvm::LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
228 llvm::NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
229 llvm::NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
230 NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
231 llvm::UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
232 llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
234 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
236 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
237 TargetMachine::setDataSections (CodeGenOpts.DataSections);
239 // FIXME: Parse this earlier.
240 if (CodeGenOpts.RelocationModel == "static") {
241 TargetMachine::setRelocationModel(llvm::Reloc::Static);
242 } else if (CodeGenOpts.RelocationModel == "pic") {
243 TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
245 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
246 "Invalid PIC model!");
247 TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
249 // FIXME: Parse this earlier.
250 if (CodeGenOpts.CodeModel == "small") {
251 TargetMachine::setCodeModel(llvm::CodeModel::Small);
252 } else if (CodeGenOpts.CodeModel == "kernel") {
253 TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
254 } else if (CodeGenOpts.CodeModel == "medium") {
255 TargetMachine::setCodeModel(llvm::CodeModel::Medium);
256 } else if (CodeGenOpts.CodeModel == "large") {
257 TargetMachine::setCodeModel(llvm::CodeModel::Large);
259 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
260 TargetMachine::setCodeModel(llvm::CodeModel::Default);
263 std::vector<const char *> BackendArgs;
264 BackendArgs.push_back("clang"); // Fake program name.
265 if (!CodeGenOpts.DebugPass.empty()) {
266 BackendArgs.push_back("-debug-pass");
267 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
269 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
270 BackendArgs.push_back("-limit-float-precision");
271 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
273 if (llvm::TimePassesIsEnabled)
274 BackendArgs.push_back("-time-passes");
275 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
276 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
277 BackendArgs.push_back(0);
278 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
279 const_cast<char **>(&BackendArgs[0]));
281 std::string FeaturesStr;
282 if (TargetOpts.Features.size()) {
283 SubtargetFeatures Features;
284 for (std::vector<std::string>::const_iterator
285 it = TargetOpts.Features.begin(),
286 ie = TargetOpts.Features.end(); it != ie; ++it)
287 Features.AddFeature(*it);
288 FeaturesStr = Features.getString();
290 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
293 if (CodeGenOpts.RelaxAll)
294 TM->setMCRelaxAll(true);
295 if (CodeGenOpts.SaveTempLabels)
296 TM->setMCSaveTempLabels(true);
297 if (CodeGenOpts.NoDwarf2CFIAsm)
298 TM->setMCUseCFI(false);
299 if (CodeGenOpts.NoExecStack)
300 TM->setMCNoExecStack(true);
302 // Create the code generator passes.
303 PassManager *PM = getCodeGenPasses();
304 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
306 switch (CodeGenOpts.OptimizationLevel) {
308 case 0: OptLevel = CodeGenOpt::None; break;
309 case 3: OptLevel = CodeGenOpt::Aggressive; break;
312 // Normal mode, emit a .s or .o file by running the code generator. Note,
313 // this also adds codegenerator level optimization passes.
314 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
315 if (Action == Backend_EmitObj)
316 CGFT = TargetMachine::CGFT_ObjectFile;
317 else if (Action == Backend_EmitMCNull)
318 CGFT = TargetMachine::CGFT_Null;
320 assert(Action == Backend_EmitAssembly && "Invalid action!");
322 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
323 // "codegen" passes so that it isn't run multiple times when there is
324 // inlining happening.
325 if (LangOpts.ObjCAutoRefCount)
326 PM->add(createObjCARCContractPass());
328 if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
329 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
330 Diags.Report(diag::err_fe_unable_to_interface_with_target);
337 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
338 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
339 llvm::formatted_raw_ostream FormattedOS;
343 case Backend_EmitNothing:
347 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
351 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
352 getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
356 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
357 if (!AddEmitPasses(Action, FormattedOS))
361 // Before executing passes, print the final values of the LLVM options.
362 cl::PrintOptionValues();
364 // Run passes. For now we do all passes at once, but eventually we
365 // would like to have the option of streaming code generation.
367 if (PerFunctionPasses) {
368 PrettyStackTraceString CrashInfo("Per-function optimization");
370 PerFunctionPasses->doInitialization();
371 for (Module::iterator I = TheModule->begin(),
372 E = TheModule->end(); I != E; ++I)
373 if (!I->isDeclaration())
374 PerFunctionPasses->run(*I);
375 PerFunctionPasses->doFinalization();
378 if (PerModulePasses) {
379 PrettyStackTraceString CrashInfo("Per-module optimization passes");
380 PerModulePasses->run(*TheModule);
384 PrettyStackTraceString CrashInfo("Code generation");
385 CodeGenPasses->run(*TheModule);
389 void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
390 const TargetOptions &TOpts,
391 const LangOptions &LOpts,
393 BackendAction Action, raw_ostream *OS) {
394 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
396 AsmHelper.EmitAssembly(Action, OS);