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