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/ADT/Triple.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriterPass.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/ModuleSummaryIndex.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/Timer.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Instrumentation.h"
45 #include "llvm/Transforms/ObjCARC.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Scalar/GVN.h"
48 #include "llvm/Transforms/Utils/SymbolRewriter.h"
49 #include <memory>
50 using namespace clang;
51 using namespace llvm;
52 
53 namespace {
54 
55 class EmitAssemblyHelper {
56   DiagnosticsEngine &Diags;
57   const CodeGenOptions &CodeGenOpts;
58   const clang::TargetOptions &TargetOpts;
59   const LangOptions &LangOpts;
60   Module *TheModule;
61 
62   Timer CodeGenerationTime;
63 
64   mutable legacy::PassManager *CodeGenPasses;
65   mutable legacy::PassManager *PerModulePasses;
66   mutable legacy::FunctionPassManager *PerFunctionPasses;
67 
68 private:
69   TargetIRAnalysis getTargetIRAnalysis() const {
70     if (TM)
71       return TM->getTargetIRAnalysis();
72 
73     return TargetIRAnalysis();
74   }
75 
76   legacy::PassManager *getCodeGenPasses() const {
77     if (!CodeGenPasses) {
78       CodeGenPasses = new legacy::PassManager();
79       CodeGenPasses->add(
80           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
81     }
82     return CodeGenPasses;
83   }
84 
85   legacy::PassManager *getPerModulePasses() const {
86     if (!PerModulePasses) {
87       PerModulePasses = new legacy::PassManager();
88       PerModulePasses->add(
89           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
90     }
91     return PerModulePasses;
92   }
93 
94   legacy::FunctionPassManager *getPerFunctionPasses() const {
95     if (!PerFunctionPasses) {
96       PerFunctionPasses = new legacy::FunctionPassManager(TheModule);
97       PerFunctionPasses->add(
98           createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
99     }
100     return PerFunctionPasses;
101   }
102 
103   /// Set LLVM command line options passed through -backend-option.
104   void setCommandLineOpts();
105 
106   void CreatePasses(ModuleSummaryIndex *ModuleSummary);
107 
108   /// Generates the TargetMachine.
109   /// Returns Null if it is unable to create the target machine.
110   /// Some of our clang tests specify triples which are not built
111   /// into clang. This is okay because these tests check the generated
112   /// IR, and they require DataLayout which depends on the triple.
113   /// In this case, we allow this method to fail and not report an error.
114   /// When MustCreateTM is used, we print an error if we are unable to load
115   /// the requested target.
116   TargetMachine *CreateTargetMachine(bool MustCreateTM);
117 
118   /// Add passes necessary to emit assembly or LLVM IR.
119   ///
120   /// \return True on success.
121   bool AddEmitPasses(BackendAction Action, raw_pwrite_stream &OS);
122 
123 public:
124   EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
125                      const clang::TargetOptions &TOpts,
126                      const LangOptions &LOpts, Module *M)
127       : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
128         TheModule(M), CodeGenerationTime("Code Generation Time"),
129         CodeGenPasses(nullptr), PerModulePasses(nullptr),
130         PerFunctionPasses(nullptr) {}
131 
132   ~EmitAssemblyHelper() {
133     delete CodeGenPasses;
134     delete PerModulePasses;
135     delete PerFunctionPasses;
136     if (CodeGenOpts.DisableFree)
137       BuryPointer(std::move(TM));
138   }
139 
140   std::unique_ptr<TargetMachine> TM;
141 
142   void EmitAssembly(BackendAction Action, raw_pwrite_stream *OS);
143 };
144 
145 // We need this wrapper to access LangOpts and CGOpts from extension functions
146 // that we add to the PassManagerBuilder.
147 class PassManagerBuilderWrapper : public PassManagerBuilder {
148 public:
149   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
150                             const LangOptions &LangOpts)
151       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
152   const CodeGenOptions &getCGOpts() const { return CGOpts; }
153   const LangOptions &getLangOpts() const { return LangOpts; }
154 private:
155   const CodeGenOptions &CGOpts;
156   const LangOptions &LangOpts;
157 };
158 
159 }
160 
161 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
162   if (Builder.OptLevel > 0)
163     PM.add(createObjCARCAPElimPass());
164 }
165 
166 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
167   if (Builder.OptLevel > 0)
168     PM.add(createObjCARCExpandPass());
169 }
170 
171 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
172   if (Builder.OptLevel > 0)
173     PM.add(createObjCARCOptPass());
174 }
175 
176 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
177                                      legacy::PassManagerBase &PM) {
178   PM.add(createAddDiscriminatorsPass());
179 }
180 
181 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
182                                     legacy::PassManagerBase &PM) {
183   PM.add(createBoundsCheckingPass());
184 }
185 
186 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
187                                      legacy::PassManagerBase &PM) {
188   const PassManagerBuilderWrapper &BuilderWrapper =
189       static_cast<const PassManagerBuilderWrapper&>(Builder);
190   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
191   SanitizerCoverageOptions Opts;
192   Opts.CoverageType =
193       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
194   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
195   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
196   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
197   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
198   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
199   PM.add(createSanitizerCoverageModulePass(Opts));
200 }
201 
202 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
203                                       legacy::PassManagerBase &PM) {
204   const PassManagerBuilderWrapper &BuilderWrapper =
205       static_cast<const PassManagerBuilderWrapper&>(Builder);
206   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
207   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
208   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/false, Recover));
209   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
210 }
211 
212 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
213                                             legacy::PassManagerBase &PM) {
214   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/true,
215                                             /*Recover*/true));
216   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
217                                           /*Recover*/true));
218 }
219 
220 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
221                                    legacy::PassManagerBase &PM) {
222   const PassManagerBuilderWrapper &BuilderWrapper =
223       static_cast<const PassManagerBuilderWrapper&>(Builder);
224   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
225   PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
226 
227   // MemorySanitizer inserts complex instrumentation that mostly follows
228   // the logic of the original code, but operates on "shadow" values.
229   // It can benefit from re-running some general purpose optimization passes.
230   if (Builder.OptLevel > 0) {
231     PM.add(createEarlyCSEPass());
232     PM.add(createReassociatePass());
233     PM.add(createLICMPass());
234     PM.add(createGVNPass());
235     PM.add(createInstructionCombiningPass());
236     PM.add(createDeadStoreEliminationPass());
237   }
238 }
239 
240 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
241                                    legacy::PassManagerBase &PM) {
242   PM.add(createThreadSanitizerPass());
243 }
244 
245 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
246                                      legacy::PassManagerBase &PM) {
247   const PassManagerBuilderWrapper &BuilderWrapper =
248       static_cast<const PassManagerBuilderWrapper&>(Builder);
249   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
250   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
251 }
252 
253 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
254                                        legacy::PassManagerBase &PM) {
255   const PassManagerBuilderWrapper &BuilderWrapper =
256       static_cast<const PassManagerBuilderWrapper&>(Builder);
257   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
258   EfficiencySanitizerOptions Opts;
259   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
260     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
261   PM.add(createEfficiencySanitizerPass(Opts));
262 }
263 
264 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
265                                          const CodeGenOptions &CodeGenOpts) {
266   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
267   if (!CodeGenOpts.SimplifyLibCalls)
268     TLII->disableAllFunctions();
269   else {
270     // Disable individual libc/libm calls in TargetLibraryInfo.
271     LibFunc::Func F;
272     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
273       if (TLII->getLibFunc(FuncName, F))
274         TLII->setUnavailable(F);
275   }
276 
277   switch (CodeGenOpts.getVecLib()) {
278   case CodeGenOptions::Accelerate:
279     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
280     break;
281   default:
282     break;
283   }
284   return TLII;
285 }
286 
287 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
288                                   legacy::PassManager *MPM) {
289   llvm::SymbolRewriter::RewriteDescriptorList DL;
290 
291   llvm::SymbolRewriter::RewriteMapParser MapParser;
292   for (const auto &MapFile : Opts.RewriteMapFiles)
293     MapParser.parse(MapFile, &DL);
294 
295   MPM->add(createRewriteSymbolsPass(DL));
296 }
297 
298 void EmitAssemblyHelper::CreatePasses(ModuleSummaryIndex *ModuleSummary) {
299   if (CodeGenOpts.DisableLLVMPasses)
300     return;
301 
302   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
303   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
304 
305   // Handle disabling of LLVM optimization, where we want to preserve the
306   // internal module before any optimization.
307   if (CodeGenOpts.DisableLLVMOpts) {
308     OptLevel = 0;
309     Inlining = CodeGenOpts.NoInlining;
310   }
311 
312   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
313 
314   // Figure out TargetLibraryInfo.
315   Triple TargetTriple(TheModule->getTargetTriple());
316   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
317 
318   switch (Inlining) {
319   case CodeGenOptions::NoInlining:
320     break;
321   case CodeGenOptions::NormalInlining: {
322     PMBuilder.Inliner =
323         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
324     break;
325   }
326   case CodeGenOptions::OnlyAlwaysInlining:
327     // Respect always_inline.
328     if (OptLevel == 0)
329       // Do not insert lifetime intrinsics at -O0.
330       PMBuilder.Inliner = createAlwaysInlinerPass(false);
331     else
332       PMBuilder.Inliner = createAlwaysInlinerPass();
333     break;
334   }
335 
336   PMBuilder.OptLevel = OptLevel;
337   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
338   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
339   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
340   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
341 
342   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
343   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
344   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
345   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
346   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
347   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
348 
349   legacy::PassManager *MPM = getPerModulePasses();
350 
351   // If we are performing a ThinLTO importing compile, invoke the LTO
352   // pipeline and pass down the in-memory module summary index.
353   if (ModuleSummary) {
354     PMBuilder.ModuleSummary = ModuleSummary;
355     PMBuilder.populateThinLTOPassManager(*MPM);
356     return;
357   }
358 
359   // Add target-specific passes that need to run as early as possible.
360   if (TM)
361     PMBuilder.addExtension(
362         PassManagerBuilder::EP_EarlyAsPossible,
363         [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
364           TM->addEarlyAsPossiblePasses(PM);
365         });
366 
367   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
368                          addAddDiscriminatorsPass);
369 
370   // In ObjC ARC mode, add the main ARC optimization passes.
371   if (LangOpts.ObjCAutoRefCount) {
372     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
373                            addObjCARCExpandPass);
374     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
375                            addObjCARCAPElimPass);
376     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
377                            addObjCARCOptPass);
378   }
379 
380   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
381     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
382                            addBoundsCheckingPass);
383     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
384                            addBoundsCheckingPass);
385   }
386 
387   if (CodeGenOpts.SanitizeCoverageType ||
388       CodeGenOpts.SanitizeCoverageIndirectCalls ||
389       CodeGenOpts.SanitizeCoverageTraceCmp) {
390     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
391                            addSanitizerCoveragePass);
392     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
393                            addSanitizerCoveragePass);
394   }
395 
396   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
397     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
398                            addAddressSanitizerPasses);
399     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
400                            addAddressSanitizerPasses);
401   }
402 
403   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
404     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
405                            addKernelAddressSanitizerPasses);
406     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
407                            addKernelAddressSanitizerPasses);
408   }
409 
410   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
411     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
412                            addMemorySanitizerPass);
413     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
414                            addMemorySanitizerPass);
415   }
416 
417   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
418     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
419                            addThreadSanitizerPass);
420     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
421                            addThreadSanitizerPass);
422   }
423 
424   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
425     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
426                            addDataFlowSanitizerPass);
427     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
428                            addDataFlowSanitizerPass);
429   }
430 
431   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
432     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
433                            addEfficiencySanitizerPass);
434     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
435                            addEfficiencySanitizerPass);
436   }
437 
438   // Set up the per-function pass manager.
439   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
440   if (CodeGenOpts.VerifyModule)
441     FPM->add(createVerifierPass());
442   PMBuilder.populateFunctionPassManager(*FPM);
443 
444   // Set up the per-module pass manager.
445   if (!CodeGenOpts.RewriteMapFiles.empty())
446     addSymbolRewriterPass(CodeGenOpts, MPM);
447 
448   if (!CodeGenOpts.DisableGCov &&
449       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
450     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
451     // LLVM's -default-gcov-version flag is set to something invalid.
452     GCOVOptions Options;
453     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
454     Options.EmitData = CodeGenOpts.EmitGcovArcs;
455     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
456     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
457     Options.NoRedZone = CodeGenOpts.DisableRedZone;
458     Options.FunctionNamesInData =
459         !CodeGenOpts.CoverageNoFunctionNamesInData;
460     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
461     MPM->add(createGCOVProfilerPass(Options));
462     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
463       MPM->add(createStripSymbolsPass(true));
464   }
465 
466   if (CodeGenOpts.hasProfileClangInstr()) {
467     InstrProfOptions Options;
468     Options.NoRedZone = CodeGenOpts.DisableRedZone;
469     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
470     MPM->add(createInstrProfilingLegacyPass(Options));
471   }
472   if (CodeGenOpts.hasProfileIRInstr()) {
473     if (!CodeGenOpts.InstrProfileOutput.empty())
474       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
475     else
476       PMBuilder.PGOInstrGen = "default.profraw";
477   }
478   if (CodeGenOpts.hasProfileIRUse())
479     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
480 
481   if (!CodeGenOpts.SampleProfileFile.empty())
482     MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
483 
484   PMBuilder.populateModulePassManager(*MPM);
485 }
486 
487 void EmitAssemblyHelper::setCommandLineOpts() {
488   SmallVector<const char *, 16> BackendArgs;
489   BackendArgs.push_back("clang"); // Fake program name.
490   if (!CodeGenOpts.DebugPass.empty()) {
491     BackendArgs.push_back("-debug-pass");
492     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
493   }
494   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
495     BackendArgs.push_back("-limit-float-precision");
496     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
497   }
498   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
499     BackendArgs.push_back(BackendOption.c_str());
500   BackendArgs.push_back(nullptr);
501   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
502                                     BackendArgs.data());
503 }
504 
505 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
506   // Create the TargetMachine for generating code.
507   std::string Error;
508   std::string Triple = TheModule->getTargetTriple();
509   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
510   if (!TheTarget) {
511     if (MustCreateTM)
512       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
513     return nullptr;
514   }
515 
516   unsigned CodeModel =
517     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
518       .Case("small", llvm::CodeModel::Small)
519       .Case("kernel", llvm::CodeModel::Kernel)
520       .Case("medium", llvm::CodeModel::Medium)
521       .Case("large", llvm::CodeModel::Large)
522       .Case("default", llvm::CodeModel::Default)
523       .Default(~0u);
524   assert(CodeModel != ~0u && "invalid code model!");
525   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
526 
527   std::string FeaturesStr =
528       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
529 
530   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
531   llvm::Reloc::Model RM = llvm::Reloc::Default;
532   if (CodeGenOpts.RelocationModel == "static") {
533     RM = llvm::Reloc::Static;
534   } else if (CodeGenOpts.RelocationModel == "pic") {
535     RM = llvm::Reloc::PIC_;
536   } else {
537     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
538            "Invalid PIC model!");
539     RM = llvm::Reloc::DynamicNoPIC;
540   }
541 
542   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
543   switch (CodeGenOpts.OptimizationLevel) {
544   default: break;
545   case 0: OptLevel = CodeGenOpt::None; break;
546   case 3: OptLevel = CodeGenOpt::Aggressive; break;
547   }
548 
549   llvm::TargetOptions Options;
550 
551   if (!TargetOpts.Reciprocals.empty())
552     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
553 
554   Options.ThreadModel =
555     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
556       .Case("posix", llvm::ThreadModel::POSIX)
557       .Case("single", llvm::ThreadModel::Single);
558 
559   // Set float ABI type.
560   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
561           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
562          "Invalid Floating Point ABI!");
563   Options.FloatABIType =
564       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
565           .Case("soft", llvm::FloatABI::Soft)
566           .Case("softfp", llvm::FloatABI::Soft)
567           .Case("hard", llvm::FloatABI::Hard)
568           .Default(llvm::FloatABI::Default);
569 
570   // Set FP fusion mode.
571   switch (CodeGenOpts.getFPContractMode()) {
572   case CodeGenOptions::FPC_Off:
573     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
574     break;
575   case CodeGenOptions::FPC_On:
576     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
577     break;
578   case CodeGenOptions::FPC_Fast:
579     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
580     break;
581   }
582 
583   Options.UseInitArray = CodeGenOpts.UseInitArray;
584   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
585   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
586 
587   // Set EABI version.
588   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
589                             .Case("4", llvm::EABI::EABI4)
590                             .Case("5", llvm::EABI::EABI5)
591                             .Case("gnu", llvm::EABI::GNU)
592                             .Default(llvm::EABI::Default);
593 
594   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
595   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
596   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
597   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
598   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
599   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
600   Options.FunctionSections = CodeGenOpts.FunctionSections;
601   Options.DataSections = CodeGenOpts.DataSections;
602   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
603   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
604   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
605 
606   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
607   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
608   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
609   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
610   Options.MCOptions.MCIncrementalLinkerCompatible =
611       CodeGenOpts.IncrementalLinkerCompatible;
612   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
613   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
614   Options.MCOptions.ABIName = TargetOpts.ABI;
615 
616   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
617                                                      FeaturesStr, Options,
618                                                      RM, CM, OptLevel);
619 
620   return TM;
621 }
622 
623 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
624                                        raw_pwrite_stream &OS) {
625 
626   // Create the code generator passes.
627   legacy::PassManager *PM = getCodeGenPasses();
628 
629   // Add LibraryInfo.
630   llvm::Triple TargetTriple(TheModule->getTargetTriple());
631   std::unique_ptr<TargetLibraryInfoImpl> TLII(
632       createTLII(TargetTriple, CodeGenOpts));
633   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
634 
635   // Normal mode, emit a .s or .o file by running the code generator. Note,
636   // this also adds codegenerator level optimization passes.
637   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
638   if (Action == Backend_EmitObj)
639     CGFT = TargetMachine::CGFT_ObjectFile;
640   else if (Action == Backend_EmitMCNull)
641     CGFT = TargetMachine::CGFT_Null;
642   else
643     assert(Action == Backend_EmitAssembly && "Invalid action!");
644 
645   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
646   // "codegen" passes so that it isn't run multiple times when there is
647   // inlining happening.
648   if (CodeGenOpts.OptimizationLevel > 0)
649     PM->add(createObjCARCContractPass());
650 
651   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
652                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
653     Diags.Report(diag::err_fe_unable_to_interface_with_target);
654     return false;
655   }
656 
657   return true;
658 }
659 
660 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
661                                       raw_pwrite_stream *OS) {
662   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
663 
664   setCommandLineOpts();
665 
666   bool UsesCodeGen = (Action != Backend_EmitNothing &&
667                       Action != Backend_EmitBC &&
668                       Action != Backend_EmitLL);
669   if (!TM)
670     TM.reset(CreateTargetMachine(UsesCodeGen));
671 
672   if (UsesCodeGen && !TM)
673     return;
674   if (TM)
675     TheModule->setDataLayout(TM->createDataLayout());
676 
677   // If we are performing a ThinLTO importing compile, load the function
678   // index into memory and pass it into CreatePasses, which will add it
679   // to the PassManagerBuilder and invoke LTO passes.
680   std::unique_ptr<ModuleSummaryIndex> ModuleSummary;
681   if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
682     ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
683         llvm::getModuleSummaryIndexForFile(
684             CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) {
685               TheModule->getContext().diagnose(DI);
686             });
687     if (std::error_code EC = IndexOrErr.getError()) {
688       std::string Error = EC.message();
689       errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
690              << "': " << Error << "\n";
691       return;
692     }
693     ModuleSummary = std::move(IndexOrErr.get());
694     assert(ModuleSummary && "Expected non-empty module summary index");
695   }
696 
697   CreatePasses(ModuleSummary.get());
698 
699   switch (Action) {
700   case Backend_EmitNothing:
701     break;
702 
703   case Backend_EmitBC:
704     getPerModulePasses()->add(createBitcodeWriterPass(
705         *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
706         CodeGenOpts.EmitSummaryIndex));
707     break;
708 
709   case Backend_EmitLL:
710     getPerModulePasses()->add(
711         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
712     break;
713 
714   default:
715     if (!AddEmitPasses(Action, *OS))
716       return;
717   }
718 
719   // Before executing passes, print the final values of the LLVM options.
720   cl::PrintOptionValues();
721 
722   // Run passes. For now we do all passes at once, but eventually we
723   // would like to have the option of streaming code generation.
724 
725   if (PerFunctionPasses) {
726     PrettyStackTraceString CrashInfo("Per-function optimization");
727 
728     PerFunctionPasses->doInitialization();
729     for (Function &F : *TheModule)
730       if (!F.isDeclaration())
731         PerFunctionPasses->run(F);
732     PerFunctionPasses->doFinalization();
733   }
734 
735   if (PerModulePasses) {
736     PrettyStackTraceString CrashInfo("Per-module optimization passes");
737     PerModulePasses->run(*TheModule);
738   }
739 
740   if (CodeGenPasses) {
741     PrettyStackTraceString CrashInfo("Code generation");
742     CodeGenPasses->run(*TheModule);
743   }
744 }
745 
746 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
747                               const CodeGenOptions &CGOpts,
748                               const clang::TargetOptions &TOpts,
749                               const LangOptions &LOpts, const llvm::DataLayout &TDesc,
750                               Module *M, BackendAction Action,
751                               raw_pwrite_stream *OS) {
752   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
753 
754   AsmHelper.EmitAssembly(Action, OS);
755 
756   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
757   // DataLayout.
758   if (AsmHelper.TM) {
759     std::string DLDesc = M->getDataLayout().getStringRepresentation();
760     if (DLDesc != TDesc.getStringRepresentation()) {
761       unsigned DiagID = Diags.getCustomDiagID(
762           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
763                                     "expected target description '%1'");
764       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
765     }
766   }
767 }
768 
769 static const char* getSectionNameForBitcode(const Triple &T) {
770   switch (T.getObjectFormat()) {
771   case Triple::MachO:
772     return "__LLVM,__bitcode";
773   case Triple::COFF:
774   case Triple::ELF:
775   case Triple::UnknownObjectFormat:
776     return ".llvmbc";
777   }
778   llvm_unreachable("Unimplemented ObjectFormatType");
779 }
780 
781 static const char* getSectionNameForCommandline(const Triple &T) {
782   switch (T.getObjectFormat()) {
783   case Triple::MachO:
784     return "__LLVM,__cmdline";
785   case Triple::COFF:
786   case Triple::ELF:
787   case Triple::UnknownObjectFormat:
788     return ".llvmcmd";
789   }
790   llvm_unreachable("Unimplemented ObjectFormatType");
791 }
792 
793 // With -fembed-bitcode, save a copy of the llvm IR as data in the
794 // __LLVM,__bitcode section.
795 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
796                          llvm::MemoryBufferRef Buf) {
797   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
798     return;
799 
800   // Embed the bitcode for the llvm module.
801   std::string Data;
802   ArrayRef<uint8_t> ModuleData;
803   Triple T(M->getTargetTriple());
804   // Create a constant that contains the bitcode.
805   // In case of embedding a marker, ignore the input Buf and use the empty
806   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
807   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
808     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
809                    (const unsigned char *)Buf.getBufferEnd())) {
810       // If the input is LLVM Assembly, bitcode is produced by serializing
811       // the module. Use-lists order need to be perserved in this case.
812       llvm::raw_string_ostream OS(Data);
813       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
814       ModuleData =
815           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
816     } else
817       // If the input is LLVM bitcode, write the input byte stream directly.
818       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
819                                      Buf.getBufferSize());
820   }
821   llvm::Constant *ModuleConstant =
822       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
823   // Use Appending linkage so it doesn't get optimized out.
824   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
825       *M, ModuleConstant->getType(), true, llvm::GlobalValue::AppendingLinkage,
826       ModuleConstant);
827   GV->setSection(getSectionNameForBitcode(T));
828   if (llvm::GlobalVariable *Old =
829           M->getGlobalVariable("llvm.embedded.module")) {
830     assert(Old->use_empty() && "llvm.embedded.module must have no uses");
831     GV->takeName(Old);
832     Old->eraseFromParent();
833   } else {
834     GV->setName("llvm.embedded.module");
835   }
836 
837   // Return if only bitcode needs to be embedded.
838   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Bitcode)
839     return;
840 
841   // Embed command-line options.
842   ArrayRef<uint8_t> CmdData((uint8_t*)CGOpts.CmdArgs.data(),
843                             CGOpts.CmdArgs.size());
844   llvm::Constant *CmdConstant =
845     llvm::ConstantDataArray::get(M->getContext(), CmdData);
846   GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
847                                 llvm::GlobalValue::AppendingLinkage,
848                                 CmdConstant);
849   GV->setSection(getSectionNameForCommandline(T));
850   if (llvm::GlobalVariable *Old = M->getGlobalVariable("llvm.cmdline")) {
851     assert(Old->use_empty() && "llvm.cmdline must have no uses");
852     GV->takeName(Old);
853     Old->eraseFromParent();
854   } else {
855     GV->setName("llvm.cmdline");
856   }
857 }
858