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