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