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