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