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