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