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