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   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
262     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
263   PM.add(createEfficiencySanitizerPass(Opts));
264 }
265 
266 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
267                                          const CodeGenOptions &CodeGenOpts) {
268   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
269   if (!CodeGenOpts.SimplifyLibCalls)
270     TLII->disableAllFunctions();
271   else {
272     // Disable individual libc/libm calls in TargetLibraryInfo.
273     LibFunc::Func F;
274     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
275       if (TLII->getLibFunc(FuncName, F))
276         TLII->setUnavailable(F);
277   }
278 
279   switch (CodeGenOpts.getVecLib()) {
280   case CodeGenOptions::Accelerate:
281     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
282     break;
283   default:
284     break;
285   }
286   return TLII;
287 }
288 
289 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
290                                   legacy::PassManager *MPM) {
291   llvm::SymbolRewriter::RewriteDescriptorList DL;
292 
293   llvm::SymbolRewriter::RewriteMapParser MapParser;
294   for (const auto &MapFile : Opts.RewriteMapFiles)
295     MapParser.parse(MapFile, &DL);
296 
297   MPM->add(createRewriteSymbolsPass(DL));
298 }
299 
300 void EmitAssemblyHelper::CreatePasses(ModuleSummaryIndex *ModuleSummary) {
301   if (CodeGenOpts.DisableLLVMPasses)
302     return;
303 
304   unsigned OptLevel = CodeGenOpts.OptimizationLevel;
305   CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
306 
307   // Handle disabling of LLVM optimization, where we want to preserve the
308   // internal module before any optimization.
309   if (CodeGenOpts.DisableLLVMOpts) {
310     OptLevel = 0;
311     Inlining = CodeGenOpts.NoInlining;
312   }
313 
314   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
315 
316   // Figure out TargetLibraryInfo.
317   Triple TargetTriple(TheModule->getTargetTriple());
318   PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
319 
320   switch (Inlining) {
321   case CodeGenOptions::NoInlining:
322     break;
323   case CodeGenOptions::NormalInlining: {
324     PMBuilder.Inliner =
325         createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
326     break;
327   }
328   case CodeGenOptions::OnlyAlwaysInlining:
329     // Respect always_inline.
330     if (OptLevel == 0)
331       // Do not insert lifetime intrinsics at -O0.
332       PMBuilder.Inliner = createAlwaysInlinerPass(false);
333     else
334       PMBuilder.Inliner = createAlwaysInlinerPass();
335     break;
336   }
337 
338   PMBuilder.OptLevel = OptLevel;
339   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
340   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
341   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
342   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
343 
344   PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
345   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
346   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
347   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
348   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
349   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
350 
351   legacy::PassManager *MPM = getPerModulePasses();
352 
353   // If we are performing a ThinLTO importing compile, invoke the LTO
354   // pipeline and pass down the in-memory module summary index.
355   if (ModuleSummary) {
356     PMBuilder.ModuleSummary = ModuleSummary;
357     PMBuilder.populateThinLTOPassManager(*MPM);
358     return;
359   }
360 
361   // Add target-specific passes that need to run as early as possible.
362   if (TM)
363     PMBuilder.addExtension(
364         PassManagerBuilder::EP_EarlyAsPossible,
365         [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
366           TM->addEarlyAsPossiblePasses(PM);
367         });
368 
369   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
370                          addAddDiscriminatorsPass);
371 
372   // In ObjC ARC mode, add the main ARC optimization passes.
373   if (LangOpts.ObjCAutoRefCount) {
374     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
375                            addObjCARCExpandPass);
376     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
377                            addObjCARCAPElimPass);
378     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
379                            addObjCARCOptPass);
380   }
381 
382   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
383     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
384                            addBoundsCheckingPass);
385     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
386                            addBoundsCheckingPass);
387   }
388 
389   if (CodeGenOpts.SanitizeCoverageType ||
390       CodeGenOpts.SanitizeCoverageIndirectCalls ||
391       CodeGenOpts.SanitizeCoverageTraceCmp) {
392     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
393                            addSanitizerCoveragePass);
394     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
395                            addSanitizerCoveragePass);
396   }
397 
398   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
399     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
400                            addAddressSanitizerPasses);
401     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
402                            addAddressSanitizerPasses);
403   }
404 
405   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
406     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
407                            addKernelAddressSanitizerPasses);
408     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
409                            addKernelAddressSanitizerPasses);
410   }
411 
412   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
413     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
414                            addMemorySanitizerPass);
415     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
416                            addMemorySanitizerPass);
417   }
418 
419   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
420     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
421                            addThreadSanitizerPass);
422     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
423                            addThreadSanitizerPass);
424   }
425 
426   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
427     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
428                            addDataFlowSanitizerPass);
429     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
430                            addDataFlowSanitizerPass);
431   }
432 
433   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
434     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
435                            addEfficiencySanitizerPass);
436     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
437                            addEfficiencySanitizerPass);
438   }
439 
440   // Set up the per-function pass manager.
441   legacy::FunctionPassManager *FPM = getPerFunctionPasses();
442   if (CodeGenOpts.VerifyModule)
443     FPM->add(createVerifierPass());
444   PMBuilder.populateFunctionPassManager(*FPM);
445 
446   // Set up the per-module pass manager.
447   if (!CodeGenOpts.RewriteMapFiles.empty())
448     addSymbolRewriterPass(CodeGenOpts, MPM);
449 
450   if (!CodeGenOpts.DisableGCov &&
451       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
452     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
453     // LLVM's -default-gcov-version flag is set to something invalid.
454     GCOVOptions Options;
455     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
456     Options.EmitData = CodeGenOpts.EmitGcovArcs;
457     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
458     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
459     Options.NoRedZone = CodeGenOpts.DisableRedZone;
460     Options.FunctionNamesInData =
461         !CodeGenOpts.CoverageNoFunctionNamesInData;
462     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
463     MPM->add(createGCOVProfilerPass(Options));
464     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
465       MPM->add(createStripSymbolsPass(true));
466   }
467 
468   if (CodeGenOpts.hasProfileClangInstr()) {
469     InstrProfOptions Options;
470     Options.NoRedZone = CodeGenOpts.DisableRedZone;
471     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
472     MPM->add(createInstrProfilingLegacyPass(Options));
473   }
474   if (CodeGenOpts.hasProfileIRInstr()) {
475     if (!CodeGenOpts.InstrProfileOutput.empty())
476       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
477     else
478       PMBuilder.PGOInstrGen = "default.profraw";
479   }
480   if (CodeGenOpts.hasProfileIRUse())
481     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
482 
483   if (!CodeGenOpts.SampleProfileFile.empty())
484     MPM->add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
485 
486   PMBuilder.populateModulePassManager(*MPM);
487 }
488 
489 void EmitAssemblyHelper::setCommandLineOpts() {
490   SmallVector<const char *, 16> BackendArgs;
491   BackendArgs.push_back("clang"); // Fake program name.
492   if (!CodeGenOpts.DebugPass.empty()) {
493     BackendArgs.push_back("-debug-pass");
494     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
495   }
496   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
497     BackendArgs.push_back("-limit-float-precision");
498     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
499   }
500   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
501     BackendArgs.push_back(BackendOption.c_str());
502   BackendArgs.push_back(nullptr);
503   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
504                                     BackendArgs.data());
505 }
506 
507 TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
508   // Create the TargetMachine for generating code.
509   std::string Error;
510   std::string Triple = TheModule->getTargetTriple();
511   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
512   if (!TheTarget) {
513     if (MustCreateTM)
514       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
515     return nullptr;
516   }
517 
518   unsigned CodeModel =
519     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
520       .Case("small", llvm::CodeModel::Small)
521       .Case("kernel", llvm::CodeModel::Kernel)
522       .Case("medium", llvm::CodeModel::Medium)
523       .Case("large", llvm::CodeModel::Large)
524       .Case("default", llvm::CodeModel::Default)
525       .Default(~0u);
526   assert(CodeModel != ~0u && "invalid code model!");
527   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
528 
529   std::string FeaturesStr =
530       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
531 
532   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
533   llvm::Optional<llvm::Reloc::Model> RM;
534   if (CodeGenOpts.RelocationModel == "static") {
535     RM = llvm::Reloc::Static;
536   } else if (CodeGenOpts.RelocationModel == "pic") {
537     RM = llvm::Reloc::PIC_;
538   } else {
539     assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
540            "Invalid PIC model!");
541     RM = llvm::Reloc::DynamicNoPIC;
542   }
543 
544   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
545   switch (CodeGenOpts.OptimizationLevel) {
546   default: break;
547   case 0: OptLevel = CodeGenOpt::None; break;
548   case 3: OptLevel = CodeGenOpt::Aggressive; break;
549   }
550 
551   llvm::TargetOptions Options;
552 
553   if (!TargetOpts.Reciprocals.empty())
554     Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
555 
556   Options.ThreadModel =
557     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
558       .Case("posix", llvm::ThreadModel::POSIX)
559       .Case("single", llvm::ThreadModel::Single);
560 
561   // Set float ABI type.
562   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
563           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
564          "Invalid Floating Point ABI!");
565   Options.FloatABIType =
566       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
567           .Case("soft", llvm::FloatABI::Soft)
568           .Case("softfp", llvm::FloatABI::Soft)
569           .Case("hard", llvm::FloatABI::Hard)
570           .Default(llvm::FloatABI::Default);
571 
572   // Set FP fusion mode.
573   switch (CodeGenOpts.getFPContractMode()) {
574   case CodeGenOptions::FPC_Off:
575     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
576     break;
577   case CodeGenOptions::FPC_On:
578     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
579     break;
580   case CodeGenOptions::FPC_Fast:
581     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
582     break;
583   }
584 
585   Options.UseInitArray = CodeGenOpts.UseInitArray;
586   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
587   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
588 
589   // Set EABI version.
590   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
591                             .Case("4", llvm::EABI::EABI4)
592                             .Case("5", llvm::EABI::EABI5)
593                             .Case("gnu", llvm::EABI::GNU)
594                             .Default(llvm::EABI::Default);
595 
596   if (LangOpts.SjLjExceptions)
597     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
598 
599   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
600   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
601   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
602   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
603   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
604   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
605   Options.FunctionSections = CodeGenOpts.FunctionSections;
606   Options.DataSections = CodeGenOpts.DataSections;
607   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
608   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
609   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
610 
611   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
612   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
613   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
614   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
615   Options.MCOptions.MCIncrementalLinkerCompatible =
616       CodeGenOpts.IncrementalLinkerCompatible;
617   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
618   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
619   Options.MCOptions.ABIName = TargetOpts.ABI;
620 
621   TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
622                                                      FeaturesStr, Options,
623                                                      RM, CM, OptLevel);
624 
625   return TM;
626 }
627 
628 bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
629                                        raw_pwrite_stream &OS) {
630 
631   // Create the code generator passes.
632   legacy::PassManager *PM = getCodeGenPasses();
633 
634   // Add LibraryInfo.
635   llvm::Triple TargetTriple(TheModule->getTargetTriple());
636   std::unique_ptr<TargetLibraryInfoImpl> TLII(
637       createTLII(TargetTriple, CodeGenOpts));
638   PM->add(new TargetLibraryInfoWrapperPass(*TLII));
639 
640   // Normal mode, emit a .s or .o file by running the code generator. Note,
641   // this also adds codegenerator level optimization passes.
642   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
643   if (Action == Backend_EmitObj)
644     CGFT = TargetMachine::CGFT_ObjectFile;
645   else if (Action == Backend_EmitMCNull)
646     CGFT = TargetMachine::CGFT_Null;
647   else
648     assert(Action == Backend_EmitAssembly && "Invalid action!");
649 
650   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
651   // "codegen" passes so that it isn't run multiple times when there is
652   // inlining happening.
653   if (CodeGenOpts.OptimizationLevel > 0)
654     PM->add(createObjCARCContractPass());
655 
656   if (TM->addPassesToEmitFile(*PM, OS, CGFT,
657                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
658     Diags.Report(diag::err_fe_unable_to_interface_with_target);
659     return false;
660   }
661 
662   return true;
663 }
664 
665 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
666                                       raw_pwrite_stream *OS) {
667   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
668 
669   setCommandLineOpts();
670 
671   bool UsesCodeGen = (Action != Backend_EmitNothing &&
672                       Action != Backend_EmitBC &&
673                       Action != Backend_EmitLL);
674   if (!TM)
675     TM.reset(CreateTargetMachine(UsesCodeGen));
676 
677   if (UsesCodeGen && !TM)
678     return;
679   if (TM)
680     TheModule->setDataLayout(TM->createDataLayout());
681 
682   // If we are performing a ThinLTO importing compile, load the function
683   // index into memory and pass it into CreatePasses, which will add it
684   // to the PassManagerBuilder and invoke LTO passes.
685   std::unique_ptr<ModuleSummaryIndex> ModuleSummary;
686   if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
687     ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
688         llvm::getModuleSummaryIndexForFile(
689             CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) {
690               TheModule->getContext().diagnose(DI);
691             });
692     if (std::error_code EC = IndexOrErr.getError()) {
693       std::string Error = EC.message();
694       errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
695              << "': " << Error << "\n";
696       return;
697     }
698     ModuleSummary = std::move(IndexOrErr.get());
699     assert(ModuleSummary && "Expected non-empty module summary index");
700   }
701 
702   CreatePasses(ModuleSummary.get());
703 
704   switch (Action) {
705   case Backend_EmitNothing:
706     break;
707 
708   case Backend_EmitBC:
709     getPerModulePasses()->add(createBitcodeWriterPass(
710         *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
711         CodeGenOpts.EmitSummaryIndex));
712     break;
713 
714   case Backend_EmitLL:
715     getPerModulePasses()->add(
716         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
717     break;
718 
719   default:
720     if (!AddEmitPasses(Action, *OS))
721       return;
722   }
723 
724   // Before executing passes, print the final values of the LLVM options.
725   cl::PrintOptionValues();
726 
727   // Run passes. For now we do all passes at once, but eventually we
728   // would like to have the option of streaming code generation.
729 
730   if (PerFunctionPasses) {
731     PrettyStackTraceString CrashInfo("Per-function optimization");
732 
733     PerFunctionPasses->doInitialization();
734     for (Function &F : *TheModule)
735       if (!F.isDeclaration())
736         PerFunctionPasses->run(F);
737     PerFunctionPasses->doFinalization();
738   }
739 
740   if (PerModulePasses) {
741     PrettyStackTraceString CrashInfo("Per-module optimization passes");
742     PerModulePasses->run(*TheModule);
743   }
744 
745   if (CodeGenPasses) {
746     PrettyStackTraceString CrashInfo("Code generation");
747     CodeGenPasses->run(*TheModule);
748   }
749 }
750 
751 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
752                               const CodeGenOptions &CGOpts,
753                               const clang::TargetOptions &TOpts,
754                               const LangOptions &LOpts, const llvm::DataLayout &TDesc,
755                               Module *M, BackendAction Action,
756                               raw_pwrite_stream *OS) {
757   EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
758 
759   AsmHelper.EmitAssembly(Action, OS);
760 
761   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
762   // DataLayout.
763   if (AsmHelper.TM) {
764     std::string DLDesc = M->getDataLayout().getStringRepresentation();
765     if (DLDesc != TDesc.getStringRepresentation()) {
766       unsigned DiagID = Diags.getCustomDiagID(
767           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
768                                     "expected target description '%1'");
769       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
770     }
771   }
772 }
773 
774 static const char* getSectionNameForBitcode(const Triple &T) {
775   switch (T.getObjectFormat()) {
776   case Triple::MachO:
777     return "__LLVM,__bitcode";
778   case Triple::COFF:
779   case Triple::ELF:
780   case Triple::UnknownObjectFormat:
781     return ".llvmbc";
782   }
783   llvm_unreachable("Unimplemented ObjectFormatType");
784 }
785 
786 static const char* getSectionNameForCommandline(const Triple &T) {
787   switch (T.getObjectFormat()) {
788   case Triple::MachO:
789     return "__LLVM,__cmdline";
790   case Triple::COFF:
791   case Triple::ELF:
792   case Triple::UnknownObjectFormat:
793     return ".llvmcmd";
794   }
795   llvm_unreachable("Unimplemented ObjectFormatType");
796 }
797 
798 // With -fembed-bitcode, save a copy of the llvm IR as data in the
799 // __LLVM,__bitcode section.
800 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
801                          llvm::MemoryBufferRef Buf) {
802   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
803     return;
804 
805   // Save llvm.compiler.used and remote it.
806   SmallVector<Constant*, 2> UsedArray;
807   SmallSet<GlobalValue*, 4> UsedGlobals;
808   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
809   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
810   for (auto *GV : UsedGlobals) {
811     if (GV->getName() != "llvm.embedded.module" &&
812         GV->getName() != "llvm.cmdline")
813       UsedArray.push_back(
814           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
815   }
816   if (Used)
817     Used->eraseFromParent();
818 
819   // Embed the bitcode for the llvm module.
820   std::string Data;
821   ArrayRef<uint8_t> ModuleData;
822   Triple T(M->getTargetTriple());
823   // Create a constant that contains the bitcode.
824   // In case of embedding a marker, ignore the input Buf and use the empty
825   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
826   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
827     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
828                    (const unsigned char *)Buf.getBufferEnd())) {
829       // If the input is LLVM Assembly, bitcode is produced by serializing
830       // the module. Use-lists order need to be perserved in this case.
831       llvm::raw_string_ostream OS(Data);
832       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
833       ModuleData =
834           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
835     } else
836       // If the input is LLVM bitcode, write the input byte stream directly.
837       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
838                                      Buf.getBufferSize());
839   }
840   llvm::Constant *ModuleConstant =
841       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
842   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
843       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
844       ModuleConstant);
845   GV->setSection(getSectionNameForBitcode(T));
846   UsedArray.push_back(
847       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
848   if (llvm::GlobalVariable *Old =
849           M->getGlobalVariable("llvm.embedded.module", true)) {
850     assert(Old->hasOneUse() &&
851            "llvm.embedded.module can only be used once in llvm.compiler.used");
852     GV->takeName(Old);
853     Old->eraseFromParent();
854   } else {
855     GV->setName("llvm.embedded.module");
856   }
857 
858   // Skip if only bitcode needs to be embedded.
859   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
860     // Embed command-line options.
861     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
862                               CGOpts.CmdArgs.size());
863     llvm::Constant *CmdConstant =
864       llvm::ConstantDataArray::get(M->getContext(), CmdData);
865     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
866                                   llvm::GlobalValue::PrivateLinkage,
867                                   CmdConstant);
868     GV->setSection(getSectionNameForCommandline(T));
869     UsedArray.push_back(
870         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
871     if (llvm::GlobalVariable *Old =
872             M->getGlobalVariable("llvm.cmdline", true)) {
873       assert(Old->hasOneUse() &&
874              "llvm.cmdline can only be used once in llvm.compiler.used");
875       GV->takeName(Old);
876       Old->eraseFromParent();
877     } else {
878       GV->setName("llvm.cmdline");
879     }
880   }
881 
882   if (UsedArray.empty())
883     return;
884 
885   // Recreate llvm.compiler.used.
886   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
887   auto *NewUsed = new GlobalVariable(
888       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
889       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
890   NewUsed->setSection("llvm.metadata");
891 }
892