Introduce a string_ostream string builder facilty
[oota-llvm.git] / lib / LTO / LTOCodeGenerator.cpp
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 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/RuntimeLibcalls.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Mangler.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/LTO/LTOModule.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/PassManager.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetLibraryInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Transforms/IPO.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/ObjCARC.h"
54 #include <system_error>
55 using namespace llvm;
56
57 const char* LTOCodeGenerator::getVersionString() {
58 #ifdef LLVM_VERSION_INFO
59   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
60 #else
61   return PACKAGE_NAME " version " PACKAGE_VERSION;
62 #endif
63 }
64
65 LTOCodeGenerator::LTOCodeGenerator()
66     : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)),
67       TargetMach(nullptr), EmitDwarfDebugInfo(false),
68       ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT),
69       NativeObjectFile(nullptr), DiagHandler(nullptr), DiagContext(nullptr) {
70   initializeLTOPasses();
71 }
72
73 LTOCodeGenerator::~LTOCodeGenerator() {
74   delete TargetMach;
75   delete NativeObjectFile;
76   TargetMach = nullptr;
77   NativeObjectFile = nullptr;
78
79   IRLinker.deleteModule();
80
81   for (std::vector<char *>::iterator I = CodegenOptions.begin(),
82                                      E = CodegenOptions.end();
83        I != E; ++I)
84     free(*I);
85 }
86
87 // Initialize LTO passes. Please keep this funciton in sync with
88 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
89 // passes are initialized.
90 void LTOCodeGenerator::initializeLTOPasses() {
91   PassRegistry &R = *PassRegistry::getPassRegistry();
92
93   initializeInternalizePassPass(R);
94   initializeIPSCCPPass(R);
95   initializeGlobalOptPass(R);
96   initializeConstantMergePass(R);
97   initializeDAHPass(R);
98   initializeInstCombinerPass(R);
99   initializeSimpleInlinerPass(R);
100   initializePruneEHPass(R);
101   initializeGlobalDCEPass(R);
102   initializeArgPromotionPass(R);
103   initializeJumpThreadingPass(R);
104   initializeSROAPass(R);
105   initializeSROA_DTPass(R);
106   initializeSROA_SSAUpPass(R);
107   initializeFunctionAttrsPass(R);
108   initializeGlobalsModRefPass(R);
109   initializeLICMPass(R);
110   initializeGVNPass(R);
111   initializeMemCpyOptPass(R);
112   initializeDCEPass(R);
113   initializeCFGSimplifyPassPass(R);
114 }
115
116 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
117   bool ret = IRLinker.linkInModule(mod->getLLVVMModule(), &errMsg);
118
119   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
120   for (int i = 0, e = undefs.size(); i != e; ++i)
121     AsmUndefinedRefs[undefs[i]] = 1;
122
123   return !ret;
124 }
125
126 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
127   Options = options;
128 }
129
130 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
131   switch (debug) {
132   case LTO_DEBUG_MODEL_NONE:
133     EmitDwarfDebugInfo = false;
134     return;
135
136   case LTO_DEBUG_MODEL_DWARF:
137     EmitDwarfDebugInfo = true;
138     return;
139   }
140   llvm_unreachable("Unknown debug format!");
141 }
142
143 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
144   switch (model) {
145   case LTO_CODEGEN_PIC_MODEL_STATIC:
146   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
147   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
148   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
149     CodeModel = model;
150     return;
151   }
152   llvm_unreachable("Unknown PIC model!");
153 }
154
155 bool LTOCodeGenerator::writeMergedModules(const char *path,
156                                           std::string &errMsg) {
157   if (!determineTarget(errMsg))
158     return false;
159
160   // mark which symbols can not be internalized
161   applyScopeRestrictions();
162
163   // create output file
164   std::string ErrInfo;
165   tool_output_file Out(path, ErrInfo, sys::fs::F_None);
166   if (!ErrInfo.empty()) {
167     errMsg = "could not open bitcode file for writing: ";
168     errMsg += path;
169     return false;
170   }
171
172   // write bitcode to it
173   WriteBitcodeToFile(IRLinker.getModule(), Out.os());
174   Out.os().close();
175
176   if (Out.os().has_error()) {
177     errMsg = "could not write bitcode file: ";
178     errMsg += path;
179     Out.os().clear_error();
180     return false;
181   }
182
183   Out.keep();
184   return true;
185 }
186
187 bool LTOCodeGenerator::compile_to_file(const char** name,
188                                        bool disableOpt,
189                                        bool disableInline,
190                                        bool disableGVNLoadPRE,
191                                        std::string& errMsg) {
192   // make unique temp .o file to put generated object file
193   SmallString<128> Filename;
194   int FD;
195   std::error_code EC =
196       sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
197   if (EC) {
198     errMsg = EC.message();
199     return false;
200   }
201
202   // generate object file
203   tool_output_file objFile(Filename.c_str(), FD);
204
205   bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
206                                       disableGVNLoadPRE, errMsg);
207   objFile.os().close();
208   if (objFile.os().has_error()) {
209     objFile.os().clear_error();
210     sys::fs::remove(Twine(Filename));
211     return false;
212   }
213
214   objFile.keep();
215   if (!genResult) {
216     sys::fs::remove(Twine(Filename));
217     return false;
218   }
219
220   NativeObjectPath = Filename.c_str();
221   *name = NativeObjectPath.c_str();
222   return true;
223 }
224
225 const void* LTOCodeGenerator::compile(size_t* length,
226                                       bool disableOpt,
227                                       bool disableInline,
228                                       bool disableGVNLoadPRE,
229                                       std::string& errMsg) {
230   const char *name;
231   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
232                        errMsg))
233     return nullptr;
234
235   // remove old buffer if compile() called twice
236   delete NativeObjectFile;
237
238   // read .o file into memory buffer
239   std::unique_ptr<MemoryBuffer> BuffPtr;
240   if (std::error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
241     errMsg = ec.message();
242     sys::fs::remove(NativeObjectPath);
243     return nullptr;
244   }
245   NativeObjectFile = BuffPtr.release();
246
247   // remove temp files
248   sys::fs::remove(NativeObjectPath);
249
250   // return buffer, unless error
251   if (!NativeObjectFile)
252     return nullptr;
253   *length = NativeObjectFile->getBufferSize();
254   return NativeObjectFile->getBufferStart();
255 }
256
257 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
258   if (TargetMach)
259     return true;
260
261   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
262   if (TripleStr.empty())
263     TripleStr = sys::getDefaultTargetTriple();
264   llvm::Triple Triple(TripleStr);
265
266   // create target machine from info for merged modules
267   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
268   if (!march)
269     return false;
270
271   // The relocation model is actually a static member of TargetMachine and
272   // needs to be set before the TargetMachine is instantiated.
273   Reloc::Model RelocModel = Reloc::Default;
274   switch (CodeModel) {
275   case LTO_CODEGEN_PIC_MODEL_STATIC:
276     RelocModel = Reloc::Static;
277     break;
278   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
279     RelocModel = Reloc::PIC_;
280     break;
281   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
282     RelocModel = Reloc::DynamicNoPIC;
283     break;
284   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
285     // RelocModel is already the default, so leave it that way.
286     break;
287   }
288
289   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
290   // the default set of features.
291   SubtargetFeatures Features(MAttr);
292   Features.getDefaultSubtargetFeatures(Triple);
293   std::string FeatureStr = Features.getString();
294   // Set a default CPU for Darwin triples.
295   if (MCpu.empty() && Triple.isOSDarwin()) {
296     if (Triple.getArch() == llvm::Triple::x86_64)
297       MCpu = "core2";
298     else if (Triple.getArch() == llvm::Triple::x86)
299       MCpu = "yonah";
300     else if (Triple.getArch() == llvm::Triple::arm64 ||
301              Triple.getArch() == llvm::Triple::aarch64)
302       MCpu = "cyclone";
303   }
304
305   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
306                                           RelocModel, CodeModel::Default,
307                                           CodeGenOpt::Aggressive);
308   return true;
309 }
310
311 void LTOCodeGenerator::
312 applyRestriction(GlobalValue &GV,
313                  const ArrayRef<StringRef> &Libcalls,
314                  std::vector<const char*> &MustPreserveList,
315                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
316                  Mangler &Mangler) {
317   // There are no restrictions to apply to declarations.
318   if (GV.isDeclaration())
319     return;
320
321   // There is nothing more restrictive than private linkage.
322   if (GV.hasPrivateLinkage())
323     return;
324
325   SmallString<64> Buffer;
326   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
327
328   if (MustPreserveSymbols.count(Buffer))
329     MustPreserveList.push_back(GV.getName().data());
330   if (AsmUndefinedRefs.count(Buffer))
331     AsmUsed.insert(&GV);
332
333   // Conservatively append user-supplied runtime library functions to
334   // llvm.compiler.used.  These could be internalized and deleted by
335   // optimizations like -globalopt, causing problems when later optimizations
336   // add new library calls (e.g., llvm.memset => memset and printf => puts).
337   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
338   if (isa<Function>(GV) &&
339       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
340     AsmUsed.insert(&GV);
341 }
342
343 static void findUsedValues(GlobalVariable *LLVMUsed,
344                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
345   if (!LLVMUsed) return;
346
347   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
348   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
349     if (GlobalValue *GV =
350         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
351       UsedValues.insert(GV);
352 }
353
354 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
355                                       const TargetLibraryInfo& TLI,
356                                       const TargetLowering *Lowering)
357 {
358   // TargetLibraryInfo has info on C runtime library calls on the current
359   // target.
360   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
361        I != E; ++I) {
362     LibFunc::Func F = static_cast<LibFunc::Func>(I);
363     if (TLI.has(F))
364       Libcalls.push_back(TLI.getName(F));
365   }
366
367   // TargetLowering has info on library calls that CodeGen expects to be
368   // available, both from the C runtime and compiler-rt.
369   if (Lowering)
370     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
371          I != E; ++I)
372       if (const char *Name
373           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
374         Libcalls.push_back(Name);
375
376   array_pod_sort(Libcalls.begin(), Libcalls.end());
377   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
378                  Libcalls.end());
379 }
380
381 void LTOCodeGenerator::applyScopeRestrictions() {
382   if (ScopeRestrictionsDone)
383     return;
384   Module *mergedModule = IRLinker.getModule();
385
386   // Start off with a verification pass.
387   PassManager passes;
388   passes.add(createVerifierPass());
389   passes.add(createDebugInfoVerifierPass());
390
391   // mark which symbols can not be internalized
392   Mangler Mangler(TargetMach->getDataLayout());
393   std::vector<const char*> MustPreserveList;
394   SmallPtrSet<GlobalValue*, 8> AsmUsed;
395   std::vector<StringRef> Libcalls;
396   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
397   accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
398
399   for (Module::iterator f = mergedModule->begin(),
400          e = mergedModule->end(); f != e; ++f)
401     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
402   for (Module::global_iterator v = mergedModule->global_begin(),
403          e = mergedModule->global_end(); v !=  e; ++v)
404     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
405   for (Module::alias_iterator a = mergedModule->alias_begin(),
406          e = mergedModule->alias_end(); a != e; ++a)
407     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
408
409   GlobalVariable *LLVMCompilerUsed =
410     mergedModule->getGlobalVariable("llvm.compiler.used");
411   findUsedValues(LLVMCompilerUsed, AsmUsed);
412   if (LLVMCompilerUsed)
413     LLVMCompilerUsed->eraseFromParent();
414
415   if (!AsmUsed.empty()) {
416     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
417     std::vector<Constant*> asmUsed2;
418     for (auto *GV : AsmUsed) {
419       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
420       asmUsed2.push_back(c);
421     }
422
423     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
424     LLVMCompilerUsed =
425       new llvm::GlobalVariable(*mergedModule, ATy, false,
426                                llvm::GlobalValue::AppendingLinkage,
427                                llvm::ConstantArray::get(ATy, asmUsed2),
428                                "llvm.compiler.used");
429
430     LLVMCompilerUsed->setSection("llvm.metadata");
431   }
432
433   passes.add(createInternalizePass(MustPreserveList));
434
435   // apply scope restrictions
436   passes.run(*mergedModule);
437
438   ScopeRestrictionsDone = true;
439 }
440
441 /// Optimize merged modules using various IPO passes
442 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
443                                           bool DisableOpt,
444                                           bool DisableInline,
445                                           bool DisableGVNLoadPRE,
446                                           std::string &errMsg) {
447   if (!this->determineTarget(errMsg))
448     return false;
449
450   Module *mergedModule = IRLinker.getModule();
451
452   // Mark which symbols can not be internalized
453   this->applyScopeRestrictions();
454
455   // Instantiate the pass manager to organize the passes.
456   PassManager passes;
457
458   // Start off with a verification pass.
459   passes.add(createVerifierPass());
460   passes.add(createDebugInfoVerifierPass());
461
462   // Add an appropriate DataLayout instance for this module...
463   mergedModule->setDataLayout(TargetMach->getDataLayout());
464   passes.add(new DataLayoutPass(mergedModule));
465
466   // Add appropriate TargetLibraryInfo for this module.
467   passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
468
469   TargetMach->addAnalysisPasses(passes);
470
471   // Enabling internalize here would use its AllButMain variant. It
472   // keeps only main if it exists and does nothing for libraries. Instead
473   // we create the pass ourselves with the symbol list provided by the linker.
474   if (!DisableOpt)
475     PassManagerBuilder().populateLTOPassManager(passes,
476                                               /*Internalize=*/false,
477                                               !DisableInline,
478                                               DisableGVNLoadPRE);
479
480   // Make sure everything is still good.
481   passes.add(createVerifierPass());
482   passes.add(createDebugInfoVerifierPass());
483
484   PassManager codeGenPasses;
485
486   codeGenPasses.add(new DataLayoutPass(mergedModule));
487
488   formatted_raw_ostream Out(out);
489
490   // If the bitcode files contain ARC code and were compiled with optimization,
491   // the ObjCARCContractPass must be run, so do it unconditionally here.
492   codeGenPasses.add(createObjCARCContractPass());
493
494   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
495                                       TargetMachine::CGFT_ObjectFile)) {
496     errMsg = "target file type not supported";
497     return false;
498   }
499
500   // Run our queue of passes all at once now, efficiently.
501   passes.run(*mergedModule);
502
503   // Run the code generator, and write assembly file
504   codeGenPasses.run(*mergedModule);
505
506   return true;
507 }
508
509 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
510 /// LTO problems.
511 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
512   for (std::pair<StringRef, StringRef> o = getToken(options);
513        !o.first.empty(); o = getToken(o.second)) {
514     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
515     // that.
516     if (CodegenOptions.empty())
517       CodegenOptions.push_back(strdup("libLLVMLTO"));
518     CodegenOptions.push_back(strdup(o.first.str().c_str()));
519   }
520 }
521
522 void LTOCodeGenerator::parseCodeGenDebugOptions() {
523   // if options were requested, set them
524   if (!CodegenOptions.empty())
525     cl::ParseCommandLineOptions(CodegenOptions.size(),
526                                 const_cast<char **>(&CodegenOptions[0]));
527 }
528
529 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
530                                          void *Context) {
531   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
532 }
533
534 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
535   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
536   lto_codegen_diagnostic_severity_t Severity;
537   switch (DI.getSeverity()) {
538   case DS_Error:
539     Severity = LTO_DS_ERROR;
540     break;
541   case DS_Warning:
542     Severity = LTO_DS_WARNING;
543     break;
544   case DS_Remark:
545     Severity = LTO_DS_REMARK;
546     break;
547   case DS_Note:
548     Severity = LTO_DS_NOTE;
549     break;
550   }
551   // Create the string that will be reported to the external diagnostic handler.
552   string_ostream Msg;
553   DiagnosticPrinterRawOStream DP(Msg);
554   DI.print(DP);
555
556   // Null-terminate the C string.
557   Msg << '\0';
558
559   // If this method has been called it means someone has set up an external
560   // diagnostic handler. Assert on that.
561   assert(DiagHandler && "Invalid diagnostic handler");
562   (*DiagHandler)(Severity, Msg.str().data(), DiagContext);
563 }
564
565 void
566 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
567                                        void *Ctxt) {
568   this->DiagHandler = DiagHandler;
569   this->DiagContext = Ctxt;
570   if (!DiagHandler)
571     return Context.setDiagnosticHandler(nullptr, nullptr);
572   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
573   // diagnostic to the external DiagHandler.
574   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
575 }