1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
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 // This file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/LTO/LTOCodeGenerator.h"
16 
17 #include "UpdateCompilerUsed.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/Passes.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/ParallelCG.h"
25 #include "llvm/CodeGen/RuntimeLibcalls.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LTO/LTOModule.h"
39 #include "llvm/Linker/Linker.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCContext.h"
42 #include "llvm/MC/SubtargetFeature.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Signals.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
56 #include "llvm/Transforms/IPO.h"
57 #include "llvm/Transforms/IPO/Internalize.h"
58 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
59 #include "llvm/Transforms/ObjCARC.h"
60 #include <system_error>
61 using namespace llvm;
62 
63 const char* LTOCodeGenerator::getVersionString() {
64 #ifdef LLVM_VERSION_INFO
65   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
66 #else
67   return PACKAGE_NAME " version " PACKAGE_VERSION;
68 #endif
69 }
70 
71 namespace llvm {
72 cl::opt<bool> LTODiscardValueNames(
73     "lto-discard-value-names",
74     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
75 #ifdef NDEBUG
76     cl::init(true),
77 #else
78     cl::init(false),
79 #endif
80     cl::Hidden);
81 }
82 
83 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
84     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
85       TheLinker(new Linker(*MergedModule)) {
86   Context.setDiscardValueNames(LTODiscardValueNames);
87   Context.enableDebugTypeODRUniquing();
88   initializeLTOPasses();
89 }
90 
91 LTOCodeGenerator::~LTOCodeGenerator() {}
92 
93 // Initialize LTO passes. Please keep this function in sync with
94 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
95 // passes are initialized.
96 void LTOCodeGenerator::initializeLTOPasses() {
97   PassRegistry &R = *PassRegistry::getPassRegistry();
98 
99   initializeInternalizePassPass(R);
100   initializeIPSCCPPass(R);
101   initializeGlobalOptPass(R);
102   initializeConstantMergePass(R);
103   initializeDAHPass(R);
104   initializeInstructionCombiningPassPass(R);
105   initializeSimpleInlinerPass(R);
106   initializePruneEHPass(R);
107   initializeGlobalDCEPass(R);
108   initializeArgPromotionPass(R);
109   initializeJumpThreadingPass(R);
110   initializeSROALegacyPassPass(R);
111   initializeSROA_DTPass(R);
112   initializeSROA_SSAUpPass(R);
113   initializePostOrderFunctionAttrsLegacyPassPass(R);
114   initializeReversePostOrderFunctionAttrsPass(R);
115   initializeGlobalsAAWrapperPassPass(R);
116   initializeLICMPass(R);
117   initializeMergedLoadStoreMotionPass(R);
118   initializeGVNLegacyPassPass(R);
119   initializeMemCpyOptPass(R);
120   initializeDCEPass(R);
121   initializeCFGSimplifyPassPass(R);
122 }
123 
124 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
125   assert(&Mod->getModule().getContext() == &Context &&
126          "Expected module in same context");
127 
128   bool ret = TheLinker->linkInModule(Mod->takeModule());
129 
130   const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
131   for (int i = 0, e = undefs.size(); i != e; ++i)
132     AsmUndefinedRefs[undefs[i]] = 1;
133 
134   // We've just changed the input, so let's make sure we verify it.
135   HasVerifiedInput = false;
136 
137   return !ret;
138 }
139 
140 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
141   assert(&Mod->getModule().getContext() == &Context &&
142          "Expected module in same context");
143 
144   AsmUndefinedRefs.clear();
145 
146   MergedModule = Mod->takeModule();
147   TheLinker = make_unique<Linker>(*MergedModule);
148 
149   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
150   for (int I = 0, E = Undefs.size(); I != E; ++I)
151     AsmUndefinedRefs[Undefs[I]] = 1;
152 
153   // We've just changed the input, so let's make sure we verify it.
154   HasVerifiedInput = false;
155 }
156 
157 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
158   this->Options = Options;
159 }
160 
161 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
162   switch (Debug) {
163   case LTO_DEBUG_MODEL_NONE:
164     EmitDwarfDebugInfo = false;
165     return;
166 
167   case LTO_DEBUG_MODEL_DWARF:
168     EmitDwarfDebugInfo = true;
169     return;
170   }
171   llvm_unreachable("Unknown debug format!");
172 }
173 
174 void LTOCodeGenerator::setOptLevel(unsigned Level) {
175   OptLevel = Level;
176   switch (OptLevel) {
177   case 0:
178     CGOptLevel = CodeGenOpt::None;
179     break;
180   case 1:
181     CGOptLevel = CodeGenOpt::Less;
182     break;
183   case 2:
184     CGOptLevel = CodeGenOpt::Default;
185     break;
186   case 3:
187     CGOptLevel = CodeGenOpt::Aggressive;
188     break;
189   }
190 }
191 
192 bool LTOCodeGenerator::writeMergedModules(const char *Path) {
193   if (!determineTarget())
194     return false;
195 
196   // We always run the verifier once on the merged module.
197   verifyMergedModuleOnce();
198 
199   // mark which symbols can not be internalized
200   applyScopeRestrictions();
201 
202   // create output file
203   std::error_code EC;
204   tool_output_file Out(Path, EC, sys::fs::F_None);
205   if (EC) {
206     std::string ErrMsg = "could not open bitcode file for writing: ";
207     ErrMsg += Path;
208     emitError(ErrMsg);
209     return false;
210   }
211 
212   // write bitcode to it
213   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
214   Out.os().close();
215 
216   if (Out.os().has_error()) {
217     std::string ErrMsg = "could not write bitcode file: ";
218     ErrMsg += Path;
219     emitError(ErrMsg);
220     Out.os().clear_error();
221     return false;
222   }
223 
224   Out.keep();
225   return true;
226 }
227 
228 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
229   // make unique temp output file to put generated code
230   SmallString<128> Filename;
231   int FD;
232 
233   const char *Extension =
234       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
235 
236   std::error_code EC =
237       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
238   if (EC) {
239     emitError(EC.message());
240     return false;
241   }
242 
243   // generate object file
244   tool_output_file objFile(Filename.c_str(), FD);
245 
246   bool genResult = compileOptimized(&objFile.os());
247   objFile.os().close();
248   if (objFile.os().has_error()) {
249     objFile.os().clear_error();
250     sys::fs::remove(Twine(Filename));
251     return false;
252   }
253 
254   objFile.keep();
255   if (!genResult) {
256     sys::fs::remove(Twine(Filename));
257     return false;
258   }
259 
260   NativeObjectPath = Filename.c_str();
261   *Name = NativeObjectPath.c_str();
262   return true;
263 }
264 
265 std::unique_ptr<MemoryBuffer>
266 LTOCodeGenerator::compileOptimized() {
267   const char *name;
268   if (!compileOptimizedToFile(&name))
269     return nullptr;
270 
271   // read .o file into memory buffer
272   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
273       MemoryBuffer::getFile(name, -1, false);
274   if (std::error_code EC = BufferOrErr.getError()) {
275     emitError(EC.message());
276     sys::fs::remove(NativeObjectPath);
277     return nullptr;
278   }
279 
280   // remove temp files
281   sys::fs::remove(NativeObjectPath);
282 
283   return std::move(*BufferOrErr);
284 }
285 
286 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
287                                        bool DisableInline,
288                                        bool DisableGVNLoadPRE,
289                                        bool DisableVectorization) {
290   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
291                 DisableVectorization))
292     return false;
293 
294   return compileOptimizedToFile(Name);
295 }
296 
297 std::unique_ptr<MemoryBuffer>
298 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
299                           bool DisableGVNLoadPRE, bool DisableVectorization) {
300   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
301                 DisableVectorization))
302     return nullptr;
303 
304   return compileOptimized();
305 }
306 
307 bool LTOCodeGenerator::determineTarget() {
308   if (TargetMach)
309     return true;
310 
311   TripleStr = MergedModule->getTargetTriple();
312   if (TripleStr.empty()) {
313     TripleStr = sys::getDefaultTargetTriple();
314     MergedModule->setTargetTriple(TripleStr);
315   }
316   llvm::Triple Triple(TripleStr);
317 
318   // create target machine from info for merged modules
319   std::string ErrMsg;
320   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
321   if (!MArch) {
322     emitError(ErrMsg);
323     return false;
324   }
325 
326   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
327   // the default set of features.
328   SubtargetFeatures Features(MAttr);
329   Features.getDefaultSubtargetFeatures(Triple);
330   FeatureStr = Features.getString();
331   // Set a default CPU for Darwin triples.
332   if (MCpu.empty() && Triple.isOSDarwin()) {
333     if (Triple.getArch() == llvm::Triple::x86_64)
334       MCpu = "core2";
335     else if (Triple.getArch() == llvm::Triple::x86)
336       MCpu = "yonah";
337     else if (Triple.getArch() == llvm::Triple::aarch64)
338       MCpu = "cyclone";
339   }
340 
341   TargetMach = createTargetMachine();
342   return true;
343 }
344 
345 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
346   return std::unique_ptr<TargetMachine>(
347       MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
348                                  RelocModel, CodeModel::Default, CGOptLevel));
349 }
350 
351 void LTOCodeGenerator::applyScopeRestrictions() {
352   if (ScopeRestrictionsDone || !ShouldInternalize)
353     return;
354 
355   if (ShouldRestoreGlobalsLinkage) {
356     // Record the linkage type of non-local symbols so they can be restored
357     // prior
358     // to module splitting.
359     auto RecordLinkage = [&](const GlobalValue &GV) {
360       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
361           GV.hasName())
362         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
363     };
364     for (auto &GV : *MergedModule)
365       RecordLinkage(GV);
366     for (auto &GV : MergedModule->globals())
367       RecordLinkage(GV);
368     for (auto &GV : MergedModule->aliases())
369       RecordLinkage(GV);
370   }
371 
372   // Update the llvm.compiler_used globals to force preserving libcalls and
373   // symbols referenced from asm
374   UpdateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
375 
376   // Declare a callback for the internalize pass that will ask for every
377   // candidate GlobalValue if it can be internalized or not.
378   Mangler Mangler;
379   SmallString<64> MangledName;
380   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
381     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
382     // with the linker supplied name, which on Darwin includes a leading
383     // underscore.
384     MangledName.clear();
385     MangledName.reserve(GV.getName().size() + 1);
386     Mangler::getNameWithPrefix(MangledName, GV.getName(),
387                                MergedModule->getDataLayout());
388     return MustPreserveSymbols.count(MangledName);
389   };
390 
391   internalizeModule(*MergedModule, MustPreserveGV);
392 
393   ScopeRestrictionsDone = true;
394 }
395 
396 /// Restore original linkage for symbols that may have been internalized
397 void LTOCodeGenerator::restoreLinkageForExternals() {
398   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
399     return;
400 
401   assert(ScopeRestrictionsDone &&
402          "Cannot externalize without internalization!");
403 
404   if (ExternalSymbols.empty())
405     return;
406 
407   auto externalize = [this](GlobalValue &GV) {
408     if (!GV.hasLocalLinkage() || !GV.hasName())
409       return;
410 
411     auto I = ExternalSymbols.find(GV.getName());
412     if (I == ExternalSymbols.end())
413       return;
414 
415     GV.setLinkage(I->second);
416   };
417 
418   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
419   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
420                 externalize);
421   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
422                 externalize);
423 }
424 
425 void LTOCodeGenerator::verifyMergedModuleOnce() {
426   // Only run on the first call.
427   if (HasVerifiedInput)
428     return;
429   HasVerifiedInput = true;
430 
431   if (verifyModule(*MergedModule, &dbgs()))
432     report_fatal_error("Broken module found, compilation aborted!");
433 }
434 
435 /// Optimize merged modules using various IPO passes
436 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
437                                 bool DisableGVNLoadPRE,
438                                 bool DisableVectorization) {
439   if (!this->determineTarget())
440     return false;
441 
442   // We always run the verifier once on the merged module, the `DisableVerify`
443   // parameter only applies to subsequent verify.
444   verifyMergedModuleOnce();
445 
446   // Mark which symbols can not be internalized
447   this->applyScopeRestrictions();
448 
449   // Instantiate the pass manager to organize the passes.
450   legacy::PassManager passes;
451 
452   // Add an appropriate DataLayout instance for this module...
453   MergedModule->setDataLayout(TargetMach->createDataLayout());
454 
455   passes.add(
456       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
457 
458   Triple TargetTriple(TargetMach->getTargetTriple());
459   PassManagerBuilder PMB;
460   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
461   PMB.LoopVectorize = !DisableVectorization;
462   PMB.SLPVectorize = !DisableVectorization;
463   if (!DisableInline)
464     PMB.Inliner = createFunctionInliningPass();
465   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
466   PMB.OptLevel = OptLevel;
467   PMB.VerifyInput = !DisableVerify;
468   PMB.VerifyOutput = !DisableVerify;
469 
470   PMB.populateLTOPassManager(passes);
471 
472   // Run our queue of passes all at once now, efficiently.
473   passes.run(*MergedModule);
474 
475   return true;
476 }
477 
478 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
479   if (!this->determineTarget())
480     return false;
481 
482   // We always run the verifier once on the merged module.  If it has already
483   // been called in optimize(), this call will return early.
484   verifyMergedModuleOnce();
485 
486   legacy::PassManager preCodeGenPasses;
487 
488   // If the bitcode files contain ARC code and were compiled with optimization,
489   // the ObjCARCContractPass must be run, so do it unconditionally here.
490   preCodeGenPasses.add(createObjCARCContractPass());
491   preCodeGenPasses.run(*MergedModule);
492 
493   // Re-externalize globals that may have been internalized to increase scope
494   // for splitting
495   restoreLinkageForExternals();
496 
497   // Do code generation. We need to preserve the module in case the client calls
498   // writeMergedModules() after compilation, but we only need to allow this at
499   // parallelism level 1. This is achieved by having splitCodeGen return the
500   // original module at parallelism level 1 which we then assign back to
501   // MergedModule.
502   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
503                               [&]() { return createTargetMachine(); }, FileType,
504                               ShouldRestoreGlobalsLinkage);
505 
506   // If statistics were requested, print them out after codegen.
507   if (llvm::AreStatisticsEnabled())
508     llvm::PrintStatistics();
509 
510   return true;
511 }
512 
513 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
514 /// LTO problems.
515 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
516   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
517        o = getToken(o.second))
518     CodegenOptions.push_back(o.first);
519 }
520 
521 void LTOCodeGenerator::parseCodeGenDebugOptions() {
522   // if options were requested, set them
523   if (!CodegenOptions.empty()) {
524     // ParseCommandLineOptions() expects argv[0] to be program name.
525     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
526     for (std::string &Arg : CodegenOptions)
527       CodegenArgv.push_back(Arg.c_str());
528     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
529   }
530 }
531 
532 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
533                                          void *Context) {
534   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
535 }
536 
537 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
538   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
539   lto_codegen_diagnostic_severity_t Severity;
540   switch (DI.getSeverity()) {
541   case DS_Error:
542     Severity = LTO_DS_ERROR;
543     break;
544   case DS_Warning:
545     Severity = LTO_DS_WARNING;
546     break;
547   case DS_Remark:
548     Severity = LTO_DS_REMARK;
549     break;
550   case DS_Note:
551     Severity = LTO_DS_NOTE;
552     break;
553   }
554   // Create the string that will be reported to the external diagnostic handler.
555   std::string MsgStorage;
556   raw_string_ostream Stream(MsgStorage);
557   DiagnosticPrinterRawOStream DP(Stream);
558   DI.print(DP);
559   Stream.flush();
560 
561   // If this method has been called it means someone has set up an external
562   // diagnostic handler. Assert on that.
563   assert(DiagHandler && "Invalid diagnostic handler");
564   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
565 }
566 
567 void
568 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
569                                        void *Ctxt) {
570   this->DiagHandler = DiagHandler;
571   this->DiagContext = Ctxt;
572   if (!DiagHandler)
573     return Context.setDiagnosticHandler(nullptr, nullptr);
574   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
575   // diagnostic to the external DiagHandler.
576   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
577                                /* RespectFilters */ true);
578 }
579 
580 namespace {
581 class LTODiagnosticInfo : public DiagnosticInfo {
582   const Twine &Msg;
583 public:
584   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
585       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
586   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
587 };
588 }
589 
590 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
591   if (DiagHandler)
592     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
593   else
594     Context.diagnose(LTODiagnosticInfo(ErrMsg));
595 }
596