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