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