1 //===--- 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/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/TargetOptions.h"
13 #include "clang/Frontend/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"
32 using namespace clang;
33 using namespace llvm;
34 
35 namespace {
36 
37 class EmitAssemblyHelper {
38   Diagnostic &Diags;
39   const CodeGenOptions &CodeGenOpts;
40   const TargetOptions &TargetOpts;
41   Module *TheModule;
42 
43   Timer CodeGenerationTime;
44 
45   mutable FunctionPassManager *CodeGenPasses;
46   mutable PassManager *PerModulePasses;
47   mutable FunctionPassManager *PerFunctionPasses;
48 
49 private:
50   FunctionPassManager *getCodeGenPasses() const {
51     if (!CodeGenPasses) {
52       CodeGenPasses = new FunctionPassManager(TheModule);
53       CodeGenPasses->add(new TargetData(TheModule));
54     }
55     return CodeGenPasses;
56   }
57 
58   PassManager *getPerModulePasses() const {
59     if (!PerModulePasses) {
60       PerModulePasses = new PassManager();
61       PerModulePasses->add(new TargetData(TheModule));
62     }
63     return PerModulePasses;
64   }
65 
66   FunctionPassManager *getPerFunctionPasses() const {
67     if (!PerFunctionPasses) {
68       PerFunctionPasses = new FunctionPassManager(TheModule);
69       PerFunctionPasses->add(new TargetData(TheModule));
70     }
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 
81 public:
82   EmitAssemblyHelper(Diagnostic &_Diags,
83                      const CodeGenOptions &CGOpts, const TargetOptions &TOpts,
84                      Module *M)
85     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts),
86       TheModule(M), CodeGenerationTime("Code Generation Time"),
87       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 
100 void 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 
149 bool 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.
163   llvm::NoFramePointerElim = CodeGenOpts.DisableFPElim;
164   if (CodeGenOpts.FloatABI == "soft")
165     llvm::FloatABIType = llvm::FloatABI::Soft;
166   else if (CodeGenOpts.FloatABI == "hard")
167     llvm::FloatABIType = llvm::FloatABI::Hard;
168   else {
169     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
170     llvm::FloatABIType = llvm::FloatABI::Default;
171   }
172   NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
173   llvm::UseSoftFloat = CodeGenOpts.SoftFloat;
174   UnwindTablesMandatory = CodeGenOpts.UnwindTables;
175 
176   TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
177 
178   TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
179   TargetMachine::setDataSections    (CodeGenOpts.DataSections);
180 
181   // FIXME: Parse this earlier.
182   if (CodeGenOpts.RelocationModel == "static") {
183     TargetMachine::setRelocationModel(llvm::Reloc::Static);
184   } else if (CodeGenOpts.RelocationModel == "pic") {
185     TargetMachine::setRelocationModel(llvm::Reloc::PIC_);
186   } else {
187     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
188            "Invalid PIC model!");
189     TargetMachine::setRelocationModel(llvm::Reloc::DynamicNoPIC);
190   }
191   // FIXME: Parse this earlier.
192   if (CodeGenOpts.CodeModel == "small") {
193     TargetMachine::setCodeModel(llvm::CodeModel::Small);
194   } else if (CodeGenOpts.CodeModel == "kernel") {
195     TargetMachine::setCodeModel(llvm::CodeModel::Kernel);
196   } else if (CodeGenOpts.CodeModel == "medium") {
197     TargetMachine::setCodeModel(llvm::CodeModel::Medium);
198   } else if (CodeGenOpts.CodeModel == "large") {
199     TargetMachine::setCodeModel(llvm::CodeModel::Large);
200   } else {
201     assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
202     TargetMachine::setCodeModel(llvm::CodeModel::Default);
203   }
204 
205   std::vector<const char *> BackendArgs;
206   BackendArgs.push_back("clang"); // Fake program name.
207   if (!CodeGenOpts.DebugPass.empty()) {
208     BackendArgs.push_back("-debug-pass");
209     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
210   }
211   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
212     BackendArgs.push_back("-limit-float-precision");
213     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
214   }
215   if (llvm::TimePassesIsEnabled)
216     BackendArgs.push_back("-time-passes");
217   BackendArgs.push_back(0);
218   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
219                                     const_cast<char **>(&BackendArgs[0]));
220 
221   std::string FeaturesStr;
222   if (TargetOpts.CPU.size() || TargetOpts.Features.size()) {
223     SubtargetFeatures Features;
224     Features.setCPU(TargetOpts.CPU);
225     for (std::vector<std::string>::const_iterator
226            it = TargetOpts.Features.begin(),
227            ie = TargetOpts.Features.end(); it != ie; ++it)
228       Features.AddFeature(*it);
229     FeaturesStr = Features.getString();
230   }
231   TargetMachine *TM = TheTarget->createTargetMachine(Triple, FeaturesStr);
232 
233   if (CodeGenOpts.RelaxAll)
234     TM->setMCRelaxAll(true);
235 
236   // Create the code generator passes.
237   FunctionPassManager *PM = getCodeGenPasses();
238   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
239 
240   switch (CodeGenOpts.OptimizationLevel) {
241   default: break;
242   case 0: OptLevel = CodeGenOpt::None; break;
243   case 3: OptLevel = CodeGenOpt::Aggressive; break;
244   }
245 
246   // Normal mode, emit a .s or .o file by running the code generator. Note,
247   // this also adds codegenerator level optimization passes.
248   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
249   if (Action == Backend_EmitObj)
250     CGFT = TargetMachine::CGFT_ObjectFile;
251   else if (Action == Backend_EmitMCNull)
252     CGFT = TargetMachine::CGFT_Null;
253   else
254     assert(Action == Backend_EmitAssembly && "Invalid action!");
255   if (TM->addPassesToEmitFile(*PM, OS, CGFT, OptLevel,
256                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
257     Diags.Report(diag::err_fe_unable_to_interface_with_target);
258     return false;
259   }
260 
261   return true;
262 }
263 
264 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
265   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
266   llvm::formatted_raw_ostream FormattedOS;
267 
268   CreatePasses();
269   switch (Action) {
270   case Backend_EmitNothing:
271     break;
272 
273   case Backend_EmitBC:
274     getPerModulePasses()->add(createBitcodeWriterPass(*OS));
275     break;
276 
277   case Backend_EmitLL:
278     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
279     getPerModulePasses()->add(createPrintModulePass(&FormattedOS));
280     break;
281 
282   default:
283     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
284     if (!AddEmitPasses(Action, FormattedOS))
285       return;
286   }
287 
288   // Run passes. For now we do all passes at once, but eventually we
289   // would like to have the option of streaming code generation.
290 
291   if (PerFunctionPasses) {
292     PrettyStackTraceString CrashInfo("Per-function optimization");
293 
294     PerFunctionPasses->doInitialization();
295     for (Module::iterator I = TheModule->begin(),
296            E = TheModule->end(); I != E; ++I)
297       if (!I->isDeclaration())
298         PerFunctionPasses->run(*I);
299     PerFunctionPasses->doFinalization();
300   }
301 
302   if (PerModulePasses) {
303     PrettyStackTraceString CrashInfo("Per-module optimization passes");
304     PerModulePasses->run(*TheModule);
305   }
306 
307   if (CodeGenPasses) {
308     PrettyStackTraceString CrashInfo("Code generation");
309 
310     CodeGenPasses->doInitialization();
311     for (Module::iterator I = TheModule->begin(),
312            E = TheModule->end(); I != E; ++I)
313       if (!I->isDeclaration())
314         CodeGenPasses->run(*I);
315     CodeGenPasses->doFinalization();
316   }
317 }
318 
319 void clang::EmitBackendOutput(Diagnostic &Diags, const CodeGenOptions &CGOpts,
320                               const TargetOptions &TOpts, Module *M,
321                               BackendAction Action, raw_ostream *OS) {
322   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, M);
323 
324   AsmHelper.EmitAssembly(Action, OS);
325 }
326