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