blob: a07edefe4c0fea1f402bb0ff121156651231a0ca [file] [log] [blame]
Nick Kledzik07b4a622008-02-26 20:26:43 +00001//===-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.
Bill Wendling39d942b2012-03-31 10:50:14 +00007//
Nick Kledzik07b4a622008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling39d942b2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik07b4a622008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000015#include "llvm/LTO/LTOCodeGenerator.h"
Adam Nemet106feda2016-02-16 21:41:51 +000016#include "llvm/ADT/Statistic.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000018#include "llvm/Analysis/Passes.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000019#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth93dcdc42015-01-31 11:17:59 +000020#include "llvm/Analysis/TargetTransformInfo.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000021#include "llvm/Bitcode/ReaderWriter.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000022#include "llvm/CodeGen/ParallelCG.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000023#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000024#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000028#include "llvm/IR/DiagnosticInfo.h"
29#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000031#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000032#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000035#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000036#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000037#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000038#include "llvm/MC/MCAsmInfo.h"
39#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000040#include "llvm/MC/SubtargetFeature.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000041#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000042#include "llvm/Support/FileSystem.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000043#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000044#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000045#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000048#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000049#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000050#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000051#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000052#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000053#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000054#include "llvm/Transforms/IPO.h"
55#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000056#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000057#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000058using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000059
Bill Wendling534a6582012-03-31 10:49:43 +000060const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000061#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000062 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000063#else
Bill Wendling534a6582012-03-31 10:49:43 +000064 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000065#endif
66}
67
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000068namespace llvm {
69cl::opt<bool> LTODiscardValueNames(
Mehdi Amini1592cb92016-03-10 17:06:52 +000070 "lto-discard-value-names",
71 cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000072#ifdef NDEBUG
73 cl::init(true),
74#else
75 cl::init(false),
76#endif
77 cl::Hidden);
78}
79
Rafael Espindola7b8a24e2015-12-04 02:42:28 +000080LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
Rafael Espindolaf49a38f2015-12-04 22:08:53 +000081 : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
Teresa Johnsonbef54362015-12-18 19:28:59 +000082 TheLinker(new Linker(*MergedModule)) {
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000083 Context.setDiscardValueNames(LTODiscardValueNames);
Duncan P. N. Exon Smith7832e0a2015-04-27 23:19:26 +000084 initializeLTOPasses();
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +000085}
86
Peter Collingbourne9c8909d2015-08-24 22:22:53 +000087LTOCodeGenerator::~LTOCodeGenerator() {}
Nick Kledzik07b4a622008-02-26 20:26:43 +000088
Yaron Keren55f5c3d2015-09-01 10:13:49 +000089// Initialize LTO passes. Please keep this function in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000090// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000091// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000092void LTOCodeGenerator::initializeLTOPasses() {
93 PassRegistry &R = *PassRegistry::getPassRegistry();
94
95 initializeInternalizePassPass(R);
96 initializeIPSCCPPass(R);
97 initializeGlobalOptPass(R);
98 initializeConstantMergePass(R);
99 initializeDAHPass(R);
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000100 initializeInstructionCombiningPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000101 initializeSimpleInlinerPass(R);
102 initializePruneEHPass(R);
103 initializeGlobalDCEPass(R);
104 initializeArgPromotionPass(R);
105 initializeJumpThreadingPass(R);
Chandler Carruth29a18a42015-09-12 09:09:14 +0000106 initializeSROALegacyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000107 initializeSROA_DTPass(R);
108 initializeSROA_SSAUpPass(R);
Chandler Carruth9c4ed172016-02-18 11:03:11 +0000109 initializePostOrderFunctionAttrsLegacyPassPass(R);
Chandler Carruth1926b702016-01-08 10:55:52 +0000110 initializeReversePostOrderFunctionAttrsPass(R);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000111 initializeGlobalsAAWrapperPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000112 initializeLICMPass(R);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000113 initializeMergedLoadStoreMotionPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000114 initializeGVNPass(R);
115 initializeMemCpyOptPass(R);
116 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000117 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000118}
119
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000120bool LTOCodeGenerator::addModule(LTOModule *Mod) {
121 assert(&Mod->getModule().getContext() == &Context &&
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000122 "Expected module in same context");
123
Teresa Johnsonbef54362015-12-18 19:28:59 +0000124 bool ret = TheLinker->linkInModule(Mod->takeModule());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000125
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000126 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000127 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000128 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000129
Shuxin Yangb6696a92013-08-07 05:19:23 +0000130 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000131}
Bill Wendling39d942b2012-03-31 10:50:14 +0000132
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000133void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
Manman Ren6487ce92015-02-24 00:45:56 +0000134 assert(&Mod->getModule().getContext() == &Context &&
135 "Expected module in same context");
136
Manman Ren6487ce92015-02-24 00:45:56 +0000137 AsmUndefinedRefs.clear();
138
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000139 MergedModule = Mod->takeModule();
Teresa Johnsonbef54362015-12-18 19:28:59 +0000140 TheLinker = make_unique<Linker>(*MergedModule);
Manman Ren6487ce92015-02-24 00:45:56 +0000141
142 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
143 for (int I = 0, E = Undefs.size(); I != E; ++I)
144 AsmUndefinedRefs[Undefs[I]] = 1;
145}
146
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000147void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
148 this->Options = Options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000149}
150
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000151void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
152 switch (Debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000153 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000154 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000155 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000156
Bill Wendling0e1824c2012-03-31 11:15:43 +0000157 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000158 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000159 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000160 }
161 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000162}
163
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000164void LTOCodeGenerator::setOptLevel(unsigned Level) {
165 OptLevel = Level;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000166 switch (OptLevel) {
167 case 0:
168 CGOptLevel = CodeGenOpt::None;
169 break;
170 case 1:
171 CGOptLevel = CodeGenOpt::Less;
172 break;
173 case 2:
174 CGOptLevel = CodeGenOpt::Default;
175 break;
176 case 3:
177 CGOptLevel = CodeGenOpt::Aggressive;
178 break;
179 }
180}
181
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000182bool LTOCodeGenerator::writeMergedModules(const char *Path) {
183 if (!determineTarget())
Shuxin Yangb6696a92013-08-07 05:19:23 +0000184 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000185
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000186 // mark which symbols can not be internalized
187 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000188
Chris Lattner69733952009-08-23 07:49:08 +0000189 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000190 std::error_code EC;
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000191 tool_output_file Out(Path, EC, sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000192 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000193 std::string ErrMsg = "could not open bitcode file for writing: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000194 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000195 emitError(ErrMsg);
Shuxin Yangb6696a92013-08-07 05:19:23 +0000196 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000197 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000198
Chris Lattner69733952009-08-23 07:49:08 +0000199 // write bitcode to it
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000200 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
Dan Gohmana2233f22010-09-01 14:20:41 +0000201 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000202
Dan Gohmana2233f22010-09-01 14:20:41 +0000203 if (Out.os().has_error()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000204 std::string ErrMsg = "could not write bitcode file: ";
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000205 ErrMsg += Path;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000206 emitError(ErrMsg);
Dan Gohmana2233f22010-09-01 14:20:41 +0000207 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000208 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000209 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000210
Dan Gohman8525fe72010-08-20 16:59:15 +0000211 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000212 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000213}
214
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000215bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000216 // make unique temp output file to put generated code
Shuxin Yang1826ae22013-08-12 21:07:31 +0000217 SmallString<128> Filename;
218 int FD;
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000219
220 const char *Extension =
221 (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
222
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000223 std::error_code EC =
Tobias Edler von Koch4d450902015-11-19 23:59:24 +0000224 sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000225 if (EC) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000226 emitError(EC.message());
Shuxin Yangb6696a92013-08-07 05:19:23 +0000227 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000228 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000229
Shuxin Yang1826ae22013-08-12 21:07:31 +0000230 // generate object file
231 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000232
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000233 bool genResult = compileOptimized(&objFile.os());
Shuxin Yang1826ae22013-08-12 21:07:31 +0000234 objFile.os().close();
235 if (objFile.os().has_error()) {
236 objFile.os().clear_error();
237 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000238 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000239 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000240
Shuxin Yang1826ae22013-08-12 21:07:31 +0000241 objFile.keep();
242 if (!genResult) {
243 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000244 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000245 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000246
Rafael Espindolac80c9692013-09-04 17:44:24 +0000247 NativeObjectPath = Filename.c_str();
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000248 *Name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000249 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000250}
251
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000252std::unique_ptr<MemoryBuffer>
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000253LTOCodeGenerator::compileOptimized() {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000254 const char *name;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000255 if (!compileOptimizedToFile(&name))
Craig Topper2617dcc2014-04-15 06:32:26 +0000256 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000257
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000258 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000259 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
260 MemoryBuffer::getFile(name, -1, false);
261 if (std::error_code EC = BufferOrErr.getError()) {
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000262 emitError(EC.message());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000263 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000264 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000265 }
Rafael Espindolafac373c2011-02-24 21:04:06 +0000266
Shuxin Yang1826ae22013-08-12 21:07:31 +0000267 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000268 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000269
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000270 return std::move(*BufferOrErr);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000271}
272
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000273bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
274 bool DisableInline,
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000275 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000276 bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000277 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000278 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000279 return false;
280
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000281 return compileOptimizedToFile(Name);
Manman Ren8121e1d2015-02-03 18:39:15 +0000282}
283
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000284std::unique_ptr<MemoryBuffer>
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000285LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000286 bool DisableGVNLoadPRE, bool DisableVectorization) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000287 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000288 DisableVectorization))
Manman Ren8121e1d2015-02-03 18:39:15 +0000289 return nullptr;
290
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000291 return compileOptimized();
Manman Ren8121e1d2015-02-03 18:39:15 +0000292}
293
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000294bool LTOCodeGenerator::determineTarget() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000295 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000296 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000297
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000298 std::string TripleStr = MergedModule->getTargetTriple();
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000299 if (TripleStr.empty()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000300 TripleStr = sys::getDefaultTargetTriple();
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000301 MergedModule->setTargetTriple(TripleStr);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000302 }
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000303 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000304
Bill Wendling45f74e32012-08-06 22:52:45 +0000305 // create target machine from info for merged modules
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000306 std::string ErrMsg;
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000307 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000308 if (!march) {
309 emitError(ErrMsg);
Shuxin Yang95866fa2013-08-06 21:51:21 +0000310 return false;
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000311 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000312
Tom Roederfd1bc602014-04-25 21:46:51 +0000313 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
314 // the default set of features.
315 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000316 Features.getDefaultSubtargetFeatures(Triple);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000317 FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000318 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000319 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000320 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000321 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000322 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000323 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000324 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000325 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000326 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000327
Peter Collingbourneec43d0f2015-08-21 04:45:57 +0000328 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
329 Options, RelocModel,
330 CodeModel::Default, CGOptLevel));
Shuxin Yang95866fa2013-08-06 21:51:21 +0000331 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000332}
333
Bill Wendling0e1824c2012-03-31 11:15:43 +0000334void LTOCodeGenerator::
335applyRestriction(GlobalValue &GV,
Craig Topper3af97222014-08-27 05:25:00 +0000336 ArrayRef<StringRef> Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000337 std::vector<const char*> &MustPreserveList,
Craig Topper71b7b682014-08-21 05:55:13 +0000338 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000339 Mangler &Mangler) {
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000340 // There are no restrictions to apply to declarations.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000341 if (GV.isDeclaration())
342 return;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000343
344 // There is nothing more restrictive than private linkage.
345 if (GV.hasPrivateLinkage())
346 return;
347
348 SmallString<64> Buffer;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000349 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000350
Rafael Espindolac80c9692013-09-04 17:44:24 +0000351 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000352 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000353 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000354 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000355
356 // Conservatively append user-supplied runtime library functions to
357 // llvm.compiler.used. These could be internalized and deleted by
358 // optimizations like -globalopt, causing problems when later optimizations
359 // add new library calls (e.g., llvm.memset => memset and printf => puts).
360 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
361 if (isa<Function>(GV) &&
362 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
363 AsmUsed.insert(&GV);
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000364
365 // Record the linkage type of non-local symbols so they can be restored prior
366 // to module splitting.
367 if (ShouldRestoreGlobalsLinkage && !GV.hasAvailableExternallyLinkage() &&
368 !GV.hasLocalLinkage() && GV.hasName())
369 ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000370}
371
372static void findUsedValues(GlobalVariable *LLVMUsed,
Craig Topper71b7b682014-08-21 05:55:13 +0000373 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000374 if (!LLVMUsed) return;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000375
Rafael Espindolacc111b22013-04-24 17:54:35 +0000376 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000377 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000378 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000379 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000380 UsedValues.insert(GV);
381}
382
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000383// Collect names of runtime library functions. User-defined functions with the
384// same names are added to llvm.compiler.used to prevent them from being
385// deleted by optimizations.
Justin Bognerb10a5202013-11-12 21:44:01 +0000386static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
387 const TargetLibraryInfo& TLI,
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000388 const Module &Mod,
389 const TargetMachine &TM) {
Justin Bognerb10a5202013-11-12 21:44:01 +0000390 // TargetLibraryInfo has info on C runtime library calls on the current
391 // target.
392 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
393 I != E; ++I) {
394 LibFunc::Func F = static_cast<LibFunc::Func>(I);
395 if (TLI.has(F))
396 Libcalls.push_back(TLI.getName(F));
397 }
398
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000399 SmallPtrSet<const TargetLowering *, 1> TLSet;
400
401 for (const Function &F : Mod) {
402 const TargetLowering *Lowering =
403 TM.getSubtargetImpl(F)->getTargetLowering();
404
405 if (Lowering && TLSet.insert(Lowering).second)
406 // TargetLowering has info on library calls that CodeGen expects to be
407 // available, both from the C runtime and compiler-rt.
408 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
409 I != E; ++I)
410 if (const char *Name =
411 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
412 Libcalls.push_back(Name);
413 }
Justin Bognerb10a5202013-11-12 21:44:01 +0000414
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000415 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000416 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
417 Libcalls.end());
418}
419
Chris Lattner2eff5052010-03-12 18:44:54 +0000420void LTOCodeGenerator::applyScopeRestrictions() {
Manman Rence0a0662015-04-17 17:10:09 +0000421 if (ScopeRestrictionsDone || !ShouldInternalize)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000422 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000423
Chris Lattner2eff5052010-03-12 18:44:54 +0000424 // Start off with a verification pass.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000425 legacy::PassManager passes;
Chris Lattner2eff5052010-03-12 18:44:54 +0000426 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000427
Bill Wendling39d942b2012-03-31 10:50:14 +0000428 // mark which symbols can not be internalized
Rafael Espindolac233f742015-06-23 13:59:29 +0000429 Mangler Mangler;
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000430 std::vector<const char*> MustPreserveList;
431 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000432 std::vector<StringRef> Libcalls;
Chandler Carruthc0291862015-01-24 02:06:09 +0000433 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
434 TargetLibraryInfo TLI(TLII);
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000435
Peter Collingbournee34034c2015-08-24 21:15:35 +0000436 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000437
Peter Collingbournee34034c2015-08-24 21:15:35 +0000438 for (Function &f : *MergedModule)
439 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
440 for (GlobalVariable &v : MergedModule->globals())
441 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
442 for (GlobalAlias &a : MergedModule->aliases())
443 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000444
445 GlobalVariable *LLVMCompilerUsed =
Peter Collingbournee34034c2015-08-24 21:15:35 +0000446 MergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000447 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000448 if (LLVMCompilerUsed)
449 LLVMCompilerUsed->eraseFromParent();
450
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000451 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000452 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000453 std::vector<Constant*> asmUsed2;
Rafael Espindola9c8c96f2014-05-05 20:06:41 +0000454 for (auto *GV : AsmUsed) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000455 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
456 asmUsed2.push_back(c);
457 }
458
459 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
460 LLVMCompilerUsed =
Peter Collingbournee34034c2015-08-24 21:15:35 +0000461 new llvm::GlobalVariable(*MergedModule, ATy, false,
Rafael Espindolacc111b22013-04-24 17:54:35 +0000462 llvm::GlobalValue::AppendingLinkage,
463 llvm::ConstantArray::get(ATy, asmUsed2),
464 "llvm.compiler.used");
465
466 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000467 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000468
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000469 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000470
Chris Lattner2eff5052010-03-12 18:44:54 +0000471 // apply scope restrictions
Peter Collingbournee34034c2015-08-24 21:15:35 +0000472 passes.run(*MergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000473
Rafael Espindolac80c9692013-09-04 17:44:24 +0000474 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000475}
476
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000477/// Restore original linkage for symbols that may have been internalized
478void LTOCodeGenerator::restoreLinkageForExternals() {
479 if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
480 return;
481
482 assert(ScopeRestrictionsDone &&
483 "Cannot externalize without internalization!");
484
485 if (ExternalSymbols.empty())
486 return;
487
488 auto externalize = [this](GlobalValue &GV) {
489 if (!GV.hasLocalLinkage() || !GV.hasName())
490 return;
491
492 auto I = ExternalSymbols.find(GV.getName());
493 if (I == ExternalSymbols.end())
494 return;
495
496 GV.setLinkage(I->second);
497 };
498
499 std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
500 std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
501 externalize);
502 std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
503 externalize);
504}
505
Nick Kledzik07b4a622008-02-26 20:26:43 +0000506/// Optimize merged modules using various IPO passes
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000507bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
508 bool DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000509 bool DisableVectorization) {
510 if (!this->determineTarget())
Shuxin Yang95866fa2013-08-06 21:51:21 +0000511 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000512
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000513 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000514 this->applyScopeRestrictions();
515
Bill Wendling0e1824c2012-03-31 11:15:43 +0000516 // Instantiate the pass manager to organize the passes.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000517 legacy::PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000518
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000519 // Add an appropriate DataLayout instance for this module...
Peter Collingbournee34034c2015-08-24 21:15:35 +0000520 MergedModule->setDataLayout(TargetMach->createDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000521
Chandler Carruth5ec2b1d2015-02-01 12:26:09 +0000522 passes.add(
523 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000524
Rafael Espindola216e0c02014-08-21 18:49:52 +0000525 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000526 PassManagerBuilder PMB;
527 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000528 PMB.LoopVectorize = !DisableVectorization;
529 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000530 if (!DisableInline)
531 PMB.Inliner = createFunctionInliningPass();
Chandler Carruthc0291862015-01-24 02:06:09 +0000532 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
Peter Collingbourne070843d2015-03-19 22:01:00 +0000533 PMB.OptLevel = OptLevel;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000534 PMB.VerifyInput = !DisableVerify;
535 PMB.VerifyOutput = !DisableVerify;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000536
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000537 PMB.populateLTOPassManager(passes);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000538
Manman Ren8121e1d2015-02-03 18:39:15 +0000539 // Run our queue of passes all at once now, efficiently.
Peter Collingbournee34034c2015-08-24 21:15:35 +0000540 passes.run(*MergedModule);
Manman Ren8121e1d2015-02-03 18:39:15 +0000541
542 return true;
543}
544
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000545bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
546 if (!this->determineTarget())
Manman Ren8121e1d2015-02-03 18:39:15 +0000547 return false;
548
Peter Collingbournec269ed52015-08-27 23:37:36 +0000549 legacy::PassManager preCodeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000550
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000551 // If the bitcode files contain ARC code and were compiled with optimization,
552 // the ObjCARCContractPass must be run, so do it unconditionally here.
Peter Collingbournec269ed52015-08-27 23:37:36 +0000553 preCodeGenPasses.add(createObjCARCContractPass());
554 preCodeGenPasses.run(*MergedModule);
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000555
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000556 // Re-externalize globals that may have been internalized to increase scope
557 // for splitting
558 restoreLinkageForExternals();
559
Peter Collingbournec269ed52015-08-27 23:37:36 +0000560 // Do code generation. We need to preserve the module in case the client calls
561 // writeMergedModules() after compilation, but we only need to allow this at
562 // parallelism level 1. This is achieved by having splitCodeGen return the
563 // original module at parallelism level 1 which we then assign back to
564 // MergedModule.
565 MergedModule =
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000566 splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
Tobias Edler von Koch8ecaf692016-01-18 23:24:54 +0000567 RelocModel, CodeModel::Default, CGOptLevel, FileType,
568 ShouldRestoreGlobalsLinkage);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000569
Adam Nemet106feda2016-02-16 21:41:51 +0000570 // If statistics were requested, print them out after codegen.
571 if (llvm::AreStatisticsEnabled())
572 llvm::PrintStatistics();
573
Shuxin Yang95866fa2013-08-06 21:51:21 +0000574 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000575}
576
Bill Wendling534a6582012-03-31 10:49:43 +0000577/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
578/// LTO problems.
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000579void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
580 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
581 o = getToken(o.second))
Peter Collingbourne22575122015-08-21 04:45:55 +0000582 CodegenOptions.push_back(o.first);
Nick Kledzikc2323472008-07-08 21:14:10 +0000583}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000584
585void LTOCodeGenerator::parseCodeGenDebugOptions() {
586 // if options were requested, set them
Peter Collingbourne22575122015-08-21 04:45:55 +0000587 if (!CodegenOptions.empty()) {
588 // ParseCommandLineOptions() expects argv[0] to be program name.
589 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
590 for (std::string &Arg : CodegenOptions)
591 CodegenArgv.push_back(Arg.c_str());
592 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
593 }
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000594}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000595
596void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
597 void *Context) {
598 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
599}
600
601void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
602 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
603 lto_codegen_diagnostic_severity_t Severity;
604 switch (DI.getSeverity()) {
605 case DS_Error:
606 Severity = LTO_DS_ERROR;
607 break;
608 case DS_Warning:
609 Severity = LTO_DS_WARNING;
610 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000611 case DS_Remark:
612 Severity = LTO_DS_REMARK;
613 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000614 case DS_Note:
615 Severity = LTO_DS_NOTE;
616 break;
617 }
618 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000619 std::string MsgStorage;
620 raw_string_ostream Stream(MsgStorage);
621 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000622 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000623 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000624
625 // If this method has been called it means someone has set up an external
626 // diagnostic handler. Assert on that.
627 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000628 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000629}
630
631void
632LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
633 void *Ctxt) {
634 this->DiagHandler = DiagHandler;
635 this->DiagContext = Ctxt;
636 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000637 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000638 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
639 // diagnostic to the external DiagHandler.
Duncan P. N. Exon Smithf02fe702014-10-02 21:11:04 +0000640 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
641 /* RespectFilters */ true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000642}
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000643
644namespace {
645class LTODiagnosticInfo : public DiagnosticInfo {
646 const Twine &Msg;
647public:
648 LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
649 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
650 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
651};
652}
653
654void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
655 if (DiagHandler)
656 (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
657 else
658 Context.diagnose(LTODiagnosticInfo(ErrMsg));
659}