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