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