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