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 addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
170                                      legacy::PassManagerBase &PM) {
171   PM.add(createAddDiscriminatorsPass());
172 }
173 
174 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
175                                     legacy::PassManagerBase &PM) {
176   PM.add(createBoundsCheckingPass());
177 }
178 
179 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
180                                      legacy::PassManagerBase &PM) {
181   const PassManagerBuilderWrapper &BuilderWrapper =
182       static_cast<const PassManagerBuilderWrapper&>(Builder);
183   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
184   SanitizerCoverageOptions Opts;
185   Opts.CoverageType =
186       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
187   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
188   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
189   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
190   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
191   PM.add(createSanitizerCoverageModulePass(Opts));
192 }
193 
194 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
195                                       legacy::PassManagerBase &PM) {
196   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false));
197   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false));
198 }
199 
200 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
201                                             legacy::PassManagerBase &PM) {
202   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true));
203   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true));
204 }
205 
206 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
207                                    legacy::PassManagerBase &PM) {
208   const PassManagerBuilderWrapper &BuilderWrapper =
209       static_cast<const PassManagerBuilderWrapper&>(Builder);
210   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
211   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
212 
213   // MemorySanitizer inserts complex instrumentation that mostly follows
214   // the logic of the original code, but operates on "shadow" values.
215   // It can benefit from re-running some general purpose optimization passes.
216   if (Builder.OptLevel > 0) {
217     PM.add(createEarlyCSEPass());
218     PM.add(createReassociatePass());
219     PM.add(createLICMPass());
220     PM.add(createGVNPass());
221     PM.add(createInstructionCombiningPass());
222     PM.add(createDeadStoreEliminationPass());
223   }
224 }
225 
226 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
227                                    legacy::PassManagerBase &PM) {
228   PM.add(createThreadSanitizerPass());
229 }
230 
231 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
232                                      legacy::PassManagerBase &PM) {
233   const PassManagerBuilderWrapper &BuilderWrapper =
234       static_cast<const PassManagerBuilderWrapper&>(Builder);
235   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
236   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
237 }
238 
239 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
240                                          const CodeGenOptions &CodeGenOpts) {
241   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
242   if (!CodeGenOpts.SimplifyLibCalls)
243     TLII->disableAllFunctions();
244 
245   switch (CodeGenOpts.getVecLib()) {
246   case CodeGenOptions::Accelerate:
247     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
248     break;
249   default:
250     break;
251   }
252   return TLII;
253 }
254 
255 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
256                                   legacy::PassManager *MPM) {
257   llvm::SymbolRewriter::RewriteDescriptorList DL;
258 
259   llvm::SymbolRewriter::RewriteMapParser MapParser;
260   for (const auto &MapFile : Opts.RewriteMapFiles)
261     MapParser.parse(MapFile, &DL);
262 
263   MPM->add(createRewriteSymbolsPass(DL));
264 }
265 
266 void EmitAssemblyHelper::CreatePasses() {
267   if (CodeGenOpts.DisableLLVMPasses)
268     return;
269 
270   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
271   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
272 
273   // Handle disabling of LLVM optimization, where we want to preserve the
274   // internal module before any optimization.
275   if (CodeGenOpts.DisableLLVMOpts) {
276     OptLevel = 0;
277     Inlining = CodeGenOpts.NoInlining;
278   }
279 
280   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
281   PMBuilder.OptLevel = OptLevel;
282   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
283   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
284   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
285   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
286 
287   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
288   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
289   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
290   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
291   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
292 
293   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
294                          addAddDiscriminatorsPass);
295 
296   // In ObjC ARC mode, add the main ARC optimization passes.
297   if (LangOpts.ObjCAutoRefCount) {
298     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
299                            addObjCARCExpandPass);
300     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
301                            addObjCARCAPElimPass);
302     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
303                            addObjCARCOptPass);
304   }
305 
306   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
307     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
308                            addBoundsCheckingPass);
309     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
310                            addBoundsCheckingPass);
311   }
312 
313   if (CodeGenOpts.SanitizeCoverageType ||
314       CodeGenOpts.SanitizeCoverageIndirectCalls ||
315       CodeGenOpts.SanitizeCoverageTraceCmp) {
316     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
317                            addSanitizerCoveragePass);
318     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
319                            addSanitizerCoveragePass);
320   }
321 
322   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
323     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
324                            addAddressSanitizerPasses);
325     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
326                            addAddressSanitizerPasses);
327   }
328 
329   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
330     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
331                            addKernelAddressSanitizerPasses);
332     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
333                            addKernelAddressSanitizerPasses);
334   }
335 
336   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
337     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
338                            addMemorySanitizerPass);
339     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
340                            addMemorySanitizerPass);
341   }
342 
343   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
344     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
345                            addThreadSanitizerPass);
346     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
347                            addThreadSanitizerPass);
348   }
349 
350   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
351     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
352                            addDataFlowSanitizerPass);
353     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
354                            addDataFlowSanitizerPass);
355   }
356 
357   // Figure out TargetLibraryInfo.
358   Triple TargetTriple(TheModule->getTargetTriple());
359   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
360 
361   switch (Inlining) {
362   case CodeGenOptions::NoInlining: break;
363   case CodeGenOptions::NormalInlining: {
364     PMBuilder.Inliner =
365         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
366     break;
367   }
368   case CodeGenOptions::OnlyAlwaysInlining:
369     // Respect always_inline.
370     if (OptLevel == 0)
371       // Do not insert lifetime intrinsics at -O0.
372       PMBuilder.Inliner = createAlwaysInlinerPass(false);
373     else
374       PMBuilder.Inliner = createAlwaysInlinerPass();
375     break;
376   }
377 
378   // Set up the per-function pass manager.
379   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
380   if (CodeGenOpts.VerifyModule)
381     FPM->add(createVerifierPass());
382   PMBuilder.populateFunctionPassManager(*FPM);
383 
384   // Set up the per-module pass manager.
385   legacy::PassManager *MPM = getPerModulePasses();
386   if (!CodeGenOpts.RewriteMapFiles.empty())
387     addSymbolRewriterPass(CodeGenOpts, MPM);
388 
389   if (!CodeGenOpts.DisableGCov &&
390       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
391     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
392     // LLVM's -default-gcov-version flag is set to something invalid.
393     GCOVOptions Options;
394     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
395     Options.EmitData = CodeGenOpts.EmitGcovArcs;
396     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
397     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
398     Options.NoRedZone = CodeGenOpts.DisableRedZone;
399     Options.FunctionNamesInData =
400         !CodeGenOpts.CoverageNoFunctionNamesInData;
401     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
402     MPM->add(createGCOVProfilerPass(Options));
403     if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
404       MPM->add(createStripSymbolsPass(true));
405   }
406 
407   if (CodeGenOpts.ProfileInstrGenerate) {
408     InstrProfOptions Options;
409     Options.NoRedZone = CodeGenOpts.DisableRedZone;
410     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
411     MPM->add(createInstrProfilingPass(Options));
412   }
413 
414   if (!CodeGenOpts.SampleProfileFile.empty())
415     MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
416 
417   PMBuilder.populateModulePassManager(*MPM);
418 }
419 
420 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
421   // Create the TargetMachine for generating code.
422   std::string Error;
423   std::string Triple = TheModule->getTargetTriple();
424   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
425   if (!TheTarget) {
426     if (MustCreateTM)
427       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
428     return nullptr;
429   }
430 
431   unsigned CodeModel =
432     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
433       .Case("small", llvm::CodeModel::Small)
434       .Case("kernel", llvm::CodeModel::Kernel)
435       .Case("medium", llvm::CodeModel::Medium)
436       .Case("large", llvm::CodeModel::Large)
437       .Case("default", llvm::CodeModel::Default)
438       .Default(~0u);
439   assert(CodeModel != ~0u && "invalid code model!");
440   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
441 
442   SmallVector<const char *, 16> BackendArgs;
443   BackendArgs.push_back("clang"); // Fake program name.
444   if (!CodeGenOpts.DebugPass.empty()) {
445     BackendArgs.push_back("-debug-pass");
446     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
447   }
448   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
449     BackendArgs.push_back("-limit-float-precision");
450     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
451   }
452   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
453     BackendArgs.push_back(BackendOption.c_str());
454   BackendArgs.push_back(nullptr);
455   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
456                                     BackendArgs.data());
457 
458   std::string FeaturesStr;
459   if (!TargetOpts.Features.empty()) {
460     SubtargetFeatures Features;
461     for (const std::string &Feature : TargetOpts.Features)
462       Features.AddFeature(Feature);
463     FeaturesStr = Features.getString();
464   }
465 
466   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
467   llvm::Reloc::Model RM = llvm::Reloc::Default;
468   if (CodeGenOpts.RelocationModel == "static") {
469     RM = llvm::Reloc::Static;
470   } else if (CodeGenOpts.RelocationModel == "pic") {
471     RM = llvm::Reloc::PIC_;
472   } else {
473     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
474            "Invalid PIC model!");
475     RM = llvm::Reloc::DynamicNoPIC;
476   }
477 
478   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
479   switch (CodeGenOpts.OptimizationLevel) {
480   default: break;
481   case 0: OptLevel = CodeGenOpt::None; break;
482   case 3: OptLevel = CodeGenOpt::Aggressive; break;
483   }
484 
485   llvm::TargetOptions Options;
486 
487   if (!TargetOpts.Reciprocals.empty())
488     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
489 
490   Options.ThreadModel =
491     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
492       .Case("posix", llvm::ThreadModel::POSIX)
493       .Case("single", llvm::ThreadModel::Single);
494 
495   if (CodeGenOpts.DisableIntegratedAS)
496     Options.DisableIntegratedAS = true;
497 
498   if (CodeGenOpts.CompressDebugSections)
499     Options.CompressDebugSections = true;
500 
501   if (CodeGenOpts.UseInitArray)
502     Options.UseInitArray = true;
503 
504   // Set float ABI type.
505   if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
506     Options.FloatABIType = llvm::FloatABI::Soft;
507   else if (CodeGenOpts.FloatABI == "hard")
508     Options.FloatABIType = llvm::FloatABI::Hard;
509   else {
510     assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
511     Options.FloatABIType = llvm::FloatABI::Default;
512   }
513 
514   // Set FP fusion mode.
515   switch (CodeGenOpts.getFPContractMode()) {
516   case CodeGenOptions::FPC_Off:
517     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
518     break;
519   case CodeGenOptions::FPC_On:
520     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
521     break;
522   case CodeGenOptions::FPC_Fast:
523     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
524     break;
525   }
526 
527   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
528   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
529   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
530   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
531   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
532   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
533   Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
534   Options.FunctionSections = CodeGenOpts.FunctionSections;
535   Options.DataSections = CodeGenOpts.DataSections;
536   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
537   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
538 
539   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
540   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
541   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
542   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
543   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
544   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
545   Options.MCOptions.ABIName = TargetOpts.ABI;
546 
547   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
548                                                      FeaturesStr, Options,
549                                                      RM, CM, OptLevel);
550 
551   return TM;
552 }
553 
554 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
555                                        raw_pwrite_stream &OS) {
556 
557   // Create the code generator passes.
558   legacy::PassManager *PM = getCodeGenPasses();
559 
560   // Add LibraryInfo.
561   llvm::Triple TargetTriple(TheModule->getTargetTriple());
562   std::unique_ptr<TargetLibraryInfoImpl> TLII(
563       createTLII(TargetTriple, CodeGenOpts));
564   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
565 
566   // Normal mode, emit a .s or .o file by running the code generator. Note,
567   // this also adds codegenerator level optimization passes.
568   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
569   if (Action == Backend_EmitObj)
570     CGFT = TargetMachine::CGFT_ObjectFile;
571   else if (Action == Backend_EmitMCNull)
572     CGFT = TargetMachine::CGFT_Null;
573   else
574     assert(Action == Backend_EmitAssembly && "Invalid action!");
575 
576   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
577   // "codegen" passes so that it isn't run multiple times when there is
578   // inlining happening.
579   if (CodeGenOpts.OptimizationLevel > 0)
580     PM->add(createObjCARCContractPass());
581 
582   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
583                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
584     Diags.Report(diag::err_fe_unable_to_interface_with_target);
585     return false;
586   }
587 
588   return true;
589 }
590 
591 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
592                                       raw_pwrite_stream *OS) {
593   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
594 
595   bool UsesCodeGen = (Action != Backend_EmitNothing &&
596                       Action != Backend_EmitBC &&
597                       Action != Backend_EmitLL);
598   if (!TM)
599     TM.reset(CreateTargetMachine(UsesCodeGen));
600 
601   if (UsesCodeGen && !TM)
602     return;
603   if (TM)
604     TheModule->setDataLayout(TM->createDataLayout());
605   CreatePasses();
606 
607   switch (Action) {
608   case Backend_EmitNothing:
609     break;
610 
611   case Backend_EmitBC:
612     getPerModulePasses()->add(
613         createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
614     break;
615 
616   case Backend_EmitLL:
617     getPerModulePasses()->add(
618         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
619     break;
620 
621   default:
622     if (!AddEmitPasses(Action, *OS))
623       return;
624   }
625 
626   // Before executing passes, print the final values of the LLVM options.
627   cl::PrintOptionValues();
628 
629   // Run passes. For now we do all passes at once, but eventually we
630   // would like to have the option of streaming code generation.
631 
632   if (PerFunctionPasses) {
633     PrettyStackTraceString CrashInfo("Per-function optimization");
634 
635     PerFunctionPasses->doInitialization();
636     for (Function &F : *TheModule)
637       if (!F.isDeclaration())
638         PerFunctionPasses->run(F);
639     PerFunctionPasses->doFinalization();
640   }
641 
642   if (PerModulePasses) {
643     PrettyStackTraceString CrashInfo("Per-module optimization passes");
644     PerModulePasses->run(*TheModule);
645   }
646 
647   if (CodeGenPasses) {
648     PrettyStackTraceString CrashInfo("Code generation");
649     CodeGenPasses->run(*TheModule);
650   }
651 }
652 
653 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
654                               const CodeGenOptions &CGOpts,
655                               const clang::TargetOptions &TOpts,
656                               const LangOptions &LOpts, StringRef TDesc,
657                               Module *M, BackendAction Action,
658                               raw_pwrite_stream *OS) {
659   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
660 
661   AsmHelper.EmitAssembly(Action, OS);
662 
663   // If an optional clang TargetInfo description string was passed in, use it to
664   // verify the LLVM TargetMachine's DataLayout.
665   if (AsmHelper.TM && !TDesc.empty()) {
666     std::string DLDesc = M->getDataLayout().getStringRepresentation();
667     if (DLDesc != TDesc) {
668       unsigned DiagID = Diags.getCustomDiagID(
669           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
670                                     "expected target description '%1'");
671       Diags.Report(DiagID) << DLDesc << TDesc;
672     }
673   }
674 }
675