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/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/Bitcode/BitcodeWriterPass.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/MC/SubtargetFeature.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/Timer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetLibraryInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include "llvm/Transforms/IPO.h"
38 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/ObjCARC.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include <memory>
43 using namespace clang;
44 using namespace llvm;
45 
46 namespace {
47 
48 class EmitAssemblyHelper {
49   DiagnosticsEngine &Diags;
50   const CodeGenOptions &CodeGenOpts;
51   const clang::TargetOptions &TargetOpts;
52   const LangOptions &LangOpts;
53   Module *TheModule;
54 
55   Timer CodeGenerationTime;
56 
57   mutable PassManager *CodeGenPasses;
58   mutable PassManager *PerModulePasses;
59   mutable FunctionPassManager *PerFunctionPasses;
60 
61 private:
62   PassManager *getCodeGenPasses() const {
63     if (!CodeGenPasses) {
64       CodeGenPasses = new PassManager();
65       CodeGenPasses->add(new DataLayoutPass(TheModule));
66       if (TM)
67         TM->addAnalysisPasses(*CodeGenPasses);
68     }
69     return CodeGenPasses;
70   }
71 
72   PassManager *getPerModulePasses() const {
73     if (!PerModulePasses) {
74       PerModulePasses = new PassManager();
75       PerModulePasses->add(new DataLayoutPass(TheModule));
76       if (TM)
77         TM->addAnalysisPasses(*PerModulePasses);
78     }
79     return PerModulePasses;
80   }
81 
82   FunctionPassManager *getPerFunctionPasses() const {
83     if (!PerFunctionPasses) {
84       PerFunctionPasses = new FunctionPassManager(TheModule);
85       PerFunctionPasses->add(new DataLayoutPass(TheModule));
86       if (TM)
87         TM->addAnalysisPasses(*PerFunctionPasses);
88     }
89     return PerFunctionPasses;
90   }
91 
92   void CreatePasses();
93 
94   /// CreateTargetMachine - Generates the TargetMachine.
95   /// Returns Null if it is unable to create the target machine.
96   /// Some of our clang tests specify triples which are not built
97   /// into clang. This is okay because these tests check the generated
98   /// IR, and they require DataLayout which depends on the triple.
99   /// In this case, we allow this method to fail and not report an error.
100   /// When MustCreateTM is used, we print an error if we are unable to load
101   /// the requested target.
102   TargetMachine *CreateTargetMachine(bool MustCreateTM);
103 
104   /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
105   ///
106   /// \return True on success.
107   bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
108 
109 public:
110   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
111                      const CodeGenOptions &CGOpts,
112                      const clang::TargetOptions &TOpts,
113                      const LangOptions &LOpts,
114                      Module *M)
115     : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
116       TheModule(M), CodeGenerationTime("Code Generation Time"),
117       CodeGenPasses(nullptr), PerModulePasses(nullptr),
118       PerFunctionPasses(nullptr) {}
119 
120   ~EmitAssemblyHelper() {
121     delete CodeGenPasses;
122     delete PerModulePasses;
123     delete PerFunctionPasses;
124     if (CodeGenOpts.DisableFree)
125       BuryPointer(TM.release());
126   }
127 
128   std::unique_ptr<TargetMachine> TM;
129 
130   void EmitAssembly(BackendAction Action, raw_ostream *OS);
131 };
132 
133 // We need this wrapper to access LangOpts and CGOpts from extension functions
134 // that we add to the PassManagerBuilder.
135 class PassManagerBuilderWrapper : public PassManagerBuilder {
136 public:
137   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
138                             const LangOptions &LangOpts)
139       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
140   const CodeGenOptions &getCGOpts() const { return CGOpts; }
141   const LangOptions &getLangOpts() const { return LangOpts; }
142 private:
143   const CodeGenOptions &CGOpts;
144   const LangOptions &LangOpts;
145 };
146 
147 }
148 
149 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
150   if (Builder.OptLevel > 0)
151     PM.add(createObjCARCAPElimPass());
152 }
153 
154 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
155   if (Builder.OptLevel > 0)
156     PM.add(createObjCARCExpandPass());
157 }
158 
159 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
160   if (Builder.OptLevel > 0)
161     PM.add(createObjCARCOptPass());
162 }
163 
164 static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
165                                        PassManagerBase &PM) {
166   const PassManagerBuilderWrapper &BuilderWrapper =
167       static_cast<const PassManagerBuilderWrapper &>(Builder);
168   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
169   PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
170 }
171 
172 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
173                                      PassManagerBase &PM) {
174   PM.add(createAddDiscriminatorsPass());
175 }
176 
177 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
178                                     PassManagerBase &PM) {
179   PM.add(createBoundsCheckingPass());
180 }
181 
182 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
183                                       PassManagerBase &PM) {
184   PM.add(createAddressSanitizerFunctionPass());
185   PM.add(createAddressSanitizerModulePass());
186 }
187 
188 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
189                                    PassManagerBase &PM) {
190   const PassManagerBuilderWrapper &BuilderWrapper =
191       static_cast<const PassManagerBuilderWrapper&>(Builder);
192   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
193   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
194 
195   // MemorySanitizer inserts complex instrumentation that mostly follows
196   // the logic of the original code, but operates on "shadow" values.
197   // It can benefit from re-running some general purpose optimization passes.
198   if (Builder.OptLevel > 0) {
199     PM.add(createEarlyCSEPass());
200     PM.add(createReassociatePass());
201     PM.add(createLICMPass());
202     PM.add(createGVNPass());
203     PM.add(createInstructionCombiningPass());
204     PM.add(createDeadStoreEliminationPass());
205   }
206 }
207 
208 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
209                                    PassManagerBase &PM) {
210   PM.add(createThreadSanitizerPass());
211 }
212 
213 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
214                                      PassManagerBase &PM) {
215   const PassManagerBuilderWrapper &BuilderWrapper =
216       static_cast<const PassManagerBuilderWrapper&>(Builder);
217   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
218   PM.add(createDataFlowSanitizerPass(CGOpts.SanitizerBlacklistFile));
219 }
220 
221 void EmitAssemblyHelper::CreatePasses() {
222   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
223   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
224 
225   // Handle disabling of LLVM optimization, where we want to preserve the
226   // internal module before any optimization.
227   if (CodeGenOpts.DisableLLVMOpts) {
228     OptLevel = 0;
229     Inlining = CodeGenOpts.NoInlining;
230   }
231 
232   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
233   PMBuilder.OptLevel = OptLevel;
234   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
235   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
236   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
237   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
238 
239   PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
240   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
241   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
242   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
243 
244   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
245                          addAddDiscriminatorsPass);
246 
247   if (!CodeGenOpts.SampleProfileFile.empty())
248     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
249                            addSampleProfileLoaderPass);
250 
251   // In ObjC ARC mode, add the main ARC optimization passes.
252   if (LangOpts.ObjCAutoRefCount) {
253     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
254                            addObjCARCExpandPass);
255     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
256                            addObjCARCAPElimPass);
257     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
258                            addObjCARCOptPass);
259   }
260 
261   if (LangOpts.Sanitize.LocalBounds) {
262     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
263                            addBoundsCheckingPass);
264     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
265                            addBoundsCheckingPass);
266   }
267 
268   if (LangOpts.Sanitize.Address) {
269     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
270                            addAddressSanitizerPasses);
271     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
272                            addAddressSanitizerPasses);
273   }
274 
275   if (LangOpts.Sanitize.Memory) {
276     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
277                            addMemorySanitizerPass);
278     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
279                            addMemorySanitizerPass);
280   }
281 
282   if (LangOpts.Sanitize.Thread) {
283     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
284                            addThreadSanitizerPass);
285     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
286                            addThreadSanitizerPass);
287   }
288 
289   if (LangOpts.Sanitize.DataFlow) {
290     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
291                            addDataFlowSanitizerPass);
292     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
293                            addDataFlowSanitizerPass);
294   }
295 
296   // Figure out TargetLibraryInfo.
297   Triple TargetTriple(TheModule->getTargetTriple());
298   PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
299   if (!CodeGenOpts.SimplifyLibCalls)
300     PMBuilder.LibraryInfo->disableAllFunctions();
301 
302   switch (Inlining) {
303   case CodeGenOptions::NoInlining: break;
304   case CodeGenOptions::NormalInlining: {
305     PMBuilder.Inliner =
306         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
307     break;
308   }
309   case CodeGenOptions::OnlyAlwaysInlining:
310     // Respect always_inline.
311     if (OptLevel == 0)
312       // Do not insert lifetime intrinsics at -O0.
313       PMBuilder.Inliner = createAlwaysInlinerPass(false);
314     else
315       PMBuilder.Inliner = createAlwaysInlinerPass();
316     break;
317   }
318 
319   // Set up the per-function pass manager.
320   FunctionPassManager *FPM = getPerFunctionPasses();
321   if (CodeGenOpts.VerifyModule)
322     FPM->add(createVerifierPass());
323   PMBuilder.populateFunctionPassManager(*FPM);
324 
325   // Set up the per-module pass manager.
326   PassManager *MPM = getPerModulePasses();
327   if (CodeGenOpts.VerifyModule)
328     MPM->add(createDebugInfoVerifierPass());
329 
330   if (!CodeGenOpts.DisableGCov &&
331       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
332     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
333     // LLVM's -default-gcov-version flag is set to something invalid.
334     GCOVOptions Options;
335     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
336     Options.EmitData = CodeGenOpts.EmitGcovArcs;
337     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
338     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
339     Options.NoRedZone = CodeGenOpts.DisableRedZone;
340     Options.FunctionNamesInData =
341         !CodeGenOpts.CoverageNoFunctionNamesInData;
342     MPM->add(createGCOVProfilerPass(Options));
343     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
344       MPM->add(createStripSymbolsPass(true));
345   }
346 
347   PMBuilder.populateModulePassManager(*MPM);
348 }
349 
350 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
351   // Create the TargetMachine for generating code.
352   std::string Error;
353   std::string Triple = TheModule->getTargetTriple();
354   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
355   if (!TheTarget) {
356     if (MustCreateTM)
357       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
358     return nullptr;
359   }
360 
361   unsigned CodeModel =
362     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
363       .Case("small", llvm::CodeModel::Small)
364       .Case("kernel", llvm::CodeModel::Kernel)
365       .Case("medium", llvm::CodeModel::Medium)
366       .Case("large", llvm::CodeModel::Large)
367       .Case("default", llvm::CodeModel::Default)
368       .Default(~0u);
369   assert(CodeModel != ~0u && "invalid code model!");
370   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
371 
372   SmallVector<const char *, 16> BackendArgs;
373   BackendArgs.push_back("clang"); // Fake program name.
374   if (!CodeGenOpts.DebugPass.empty()) {
375     BackendArgs.push_back("-debug-pass");
376     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
377   }
378   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
379     BackendArgs.push_back("-limit-float-precision");
380     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
381   }
382   if (llvm::TimePassesIsEnabled)
383     BackendArgs.push_back("-time-passes");
384   for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
385     BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
386   if (CodeGenOpts.NoGlobalMerge)
387     BackendArgs.push_back("-enable-global-merge=false");
388   BackendArgs.push_back(nullptr);
389   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
390                                     BackendArgs.data());
391 
392   std::string FeaturesStr;
393   if (TargetOpts.Features.size()) {
394     SubtargetFeatures Features;
395     for (std::vector<std::string>::const_iterator
396            it = TargetOpts.Features.begin(),
397            ie = TargetOpts.Features.end(); it != ie; ++it)
398       Features.AddFeature(*it);
399     FeaturesStr = Features.getString();
400   }
401 
402   llvm::Reloc::Model RM = llvm::Reloc::Default;
403   if (CodeGenOpts.RelocationModel == "static") {
404     RM = llvm::Reloc::Static;
405   } else if (CodeGenOpts.RelocationModel == "pic") {
406     RM = llvm::Reloc::PIC_;
407   } else {
408     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
409            "Invalid PIC model!");
410     RM = llvm::Reloc::DynamicNoPIC;
411   }
412 
413   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
414   switch (CodeGenOpts.OptimizationLevel) {
415   default: break;
416   case 0: OptLevel = CodeGenOpt::None; break;
417   case 3: OptLevel = CodeGenOpt::Aggressive; break;
418   }
419 
420   llvm::TargetOptions Options;
421 
422   if (CodeGenOpts.DisableIntegratedAS)
423     Options.DisableIntegratedAS = true;
424 
425   if (CodeGenOpts.CompressDebugSections)
426     Options.CompressDebugSections = true;
427 
428   // Set frame pointer elimination mode.
429   if (!CodeGenOpts.DisableFPElim) {
430     Options.NoFramePointerElim = false;
431   } else if (CodeGenOpts.OmitLeafFramePointer) {
432     Options.NoFramePointerElim = false;
433   } else {
434     Options.NoFramePointerElim = true;
435   }
436 
437   if (CodeGenOpts.UseInitArray)
438     Options.UseInitArray = true;
439 
440   // Set float ABI type.
441   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
442     Options.FloatABIType = llvm::FloatABI::Soft;
443   else if (CodeGenOpts.FloatABI == "hard")
444     Options.FloatABIType = llvm::FloatABI::Hard;
445   else {
446     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
447     Options.FloatABIType = llvm::FloatABI::Default;
448   }
449 
450   // Set FP fusion mode.
451   switch (CodeGenOpts.getFPContractMode()) {
452   case CodeGenOptions::FPC_Off:
453     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
454     break;
455   case CodeGenOptions::FPC_On:
456     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
457     break;
458   case CodeGenOptions::FPC_Fast:
459     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
460     break;
461   }
462 
463   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
464   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
465   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
466   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
467   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
468   Options.UseSoftFloat = CodeGenOpts.SoftFloat;
469   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
470   Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
471   Options.TrapFuncName = CodeGenOpts.TrapFuncName;
472   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
473   Options.FunctionSections = CodeGenOpts.FunctionSections;
474   Options.DataSections = CodeGenOpts.DataSections;
475 
476   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
477   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
478   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
479   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
480   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
481 
482   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
483                                                      FeaturesStr, Options,
484                                                      RM, CM, OptLevel);
485 
486   return TM;
487 }
488 
489 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
490                                        formatted_raw_ostream &OS) {
491 
492   // Create the code generator passes.
493   PassManager *PM = getCodeGenPasses();
494 
495   // Add LibraryInfo.
496   llvm::Triple TargetTriple(TheModule->getTargetTriple());
497   TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
498   if (!CodeGenOpts.SimplifyLibCalls)
499     TLI->disableAllFunctions();
500   PM->add(TLI);
501 
502   // Add Target specific analysis passes.
503   TM->addAnalysisPasses(*PM);
504 
505   // Normal mode, emit a .s or .o file by running the code generator. Note,
506   // this also adds codegenerator level optimization passes.
507   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
508   if (Action == Backend_EmitObj)
509     CGFT = TargetMachine::CGFT_ObjectFile;
510   else if (Action == Backend_EmitMCNull)
511     CGFT = TargetMachine::CGFT_Null;
512   else
513     assert(Action == Backend_EmitAssembly && "Invalid action!");
514 
515   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
516   // "codegen" passes so that it isn't run multiple times when there is
517   // inlining happening.
518   if (LangOpts.ObjCAutoRefCount &&
519       CodeGenOpts.OptimizationLevel > 0)
520     PM->add(createObjCARCContractPass());
521 
522   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
523                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
524     Diags.Report(diag::err_fe_unable_to_interface_with_target);
525     return false;
526   }
527 
528   return true;
529 }
530 
531 void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
532   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
533   llvm::formatted_raw_ostream FormattedOS;
534 
535   bool UsesCodeGen = (Action != Backend_EmitNothing &&
536                       Action != Backend_EmitBC &&
537                       Action != Backend_EmitLL);
538   if (!TM)
539     TM.reset(CreateTargetMachine(UsesCodeGen));
540 
541   if (UsesCodeGen && !TM) return;
542   CreatePasses();
543 
544   switch (Action) {
545   case Backend_EmitNothing:
546     break;
547 
548   case Backend_EmitBC:
549     getPerModulePasses()->add(createBitcodeWriterPass(*OS));
550     break;
551 
552   case Backend_EmitLL:
553     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
554     getPerModulePasses()->add(createPrintModulePass(FormattedOS));
555     break;
556 
557   default:
558     FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
559     if (!AddEmitPasses(Action, FormattedOS))
560       return;
561   }
562 
563   // Before executing passes, print the final values of the LLVM options.
564   cl::PrintOptionValues();
565 
566   // Run passes. For now we do all passes at once, but eventually we
567   // would like to have the option of streaming code generation.
568 
569   if (PerFunctionPasses) {
570     PrettyStackTraceString CrashInfo("Per-function optimization");
571 
572     PerFunctionPasses->doInitialization();
573     for (Module::iterator I = TheModule->begin(),
574            E = TheModule->end(); I != E; ++I)
575       if (!I->isDeclaration())
576         PerFunctionPasses->run(*I);
577     PerFunctionPasses->doFinalization();
578   }
579 
580   if (PerModulePasses) {
581     PrettyStackTraceString CrashInfo("Per-module optimization passes");
582     PerModulePasses->run(*TheModule);
583   }
584 
585   if (CodeGenPasses) {
586     PrettyStackTraceString CrashInfo("Code generation");
587     CodeGenPasses->run(*TheModule);
588   }
589 }
590 
591 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
592                               const CodeGenOptions &CGOpts,
593                               const clang::TargetOptions &TOpts,
594                               const LangOptions &LOpts, StringRef TDesc,
595                               Module *M, BackendAction Action,
596                               raw_ostream *OS) {
597   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
598 
599   AsmHelper.EmitAssembly(Action, OS);
600 
601   // If an optional clang TargetInfo description string was passed in, use it to
602   // verify the LLVM TargetMachine's DataLayout.
603   if (AsmHelper.TM && !TDesc.empty()) {
604     std::string DLDesc = AsmHelper.TM->getSubtargetImpl()
605                              ->getDataLayout()
606                              ->getStringRepresentation();
607     if (DLDesc != TDesc) {
608       unsigned DiagID = Diags.getCustomDiagID(
609           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
610                                     "expected target description '%1'");
611       Diags.Report(DiagID) << DLDesc << TDesc;
612     }
613   }
614 }
615