blob: 8dcc53c8033ac870e1e57e33f9136cba93f0d097 [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"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "llvm/ADT/StringExtras.h"
Nick Lewycky510dae32009-06-17 06:52:10 +000017#include "llvm/Analysis/Passes.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth93dcdc42015-01-31 11:17:59 +000019#include "llvm/Analysis/TargetTransformInfo.h"
Nick Kledzik07b4a622008-02-26 20:26:43 +000020#include "llvm/Bitcode/ReaderWriter.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000021#include "llvm/CodeGen/ParallelCG.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000022#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000023#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000027#include "llvm/IR/DiagnosticInfo.h"
28#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000030#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000031#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000033#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000034#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000035#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000036#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000037#include "llvm/MC/MCAsmInfo.h"
38#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000039#include "llvm/MC/SubtargetFeature.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000040#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000041#include "llvm/Support/FileSystem.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000042#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000044#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000045#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000047#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000048#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000049#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000050#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000051#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000053#include "llvm/Transforms/IPO.h"
54#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000055#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000056#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000057using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000058
Bill Wendling534a6582012-03-31 10:49:43 +000059const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000060#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000061 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000062#else
Bill Wendling534a6582012-03-31 10:49:43 +000063 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000064#endif
65}
66
Yunzhong Gao46261a72015-09-11 20:01:53 +000067static void handleLTODiagnostic(const DiagnosticInfo &DI) {
68 DiagnosticPrinterRawOStream DP(errs());
69 DI.print(DP);
70 errs() << "\n";
71}
72
Bill Wendling39d942b2012-03-31 10:50:14 +000073LTOCodeGenerator::LTOCodeGenerator()
Peter Collingbourne9c8909d2015-08-24 22:22:53 +000074 : Context(getGlobalContext()),
75 MergedModule(new Module("ld-temp.o", Context)),
Yunzhong Gao46261a72015-09-11 20:01:53 +000076 IRLinker(MergedModule.get(), handleLTODiagnostic) {
Duncan P. N. Exon Smith7832e0a2015-04-27 23:19:26 +000077 initializeLTOPasses();
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +000078}
79
80LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
81 : OwnedContext(std::move(Context)), Context(*OwnedContext),
Peter Collingbourne9c8909d2015-08-24 22:22:53 +000082 MergedModule(new Module("ld-temp.o", *OwnedContext)),
Yunzhong Gao46261a72015-09-11 20:01:53 +000083 IRLinker(MergedModule.get(), handleLTODiagnostic) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000084 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +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);
109 initializeFunctionAttrsPass(R);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000110 initializeGlobalsAAWrapperPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000111 initializeLICMPass(R);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000112 initializeMergedLoadStoreMotionPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000113 initializeGVNPass(R);
114 initializeMemCpyOptPass(R);
115 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000116 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000117}
118
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000119bool LTOCodeGenerator::addModule(LTOModule *Mod) {
120 assert(&Mod->getModule().getContext() == &Context &&
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000121 "Expected module in same context");
122
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000123 bool ret = IRLinker.linkInModule(&Mod->getModule());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000124
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000125 const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000126 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000127 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000128
Shuxin Yangb6696a92013-08-07 05:19:23 +0000129 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000130}
Bill Wendling39d942b2012-03-31 10:50:14 +0000131
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000132void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
Manman Ren6487ce92015-02-24 00:45:56 +0000133 assert(&Mod->getModule().getContext() == &Context &&
134 "Expected module in same context");
135
Manman Ren6487ce92015-02-24 00:45:56 +0000136 AsmUndefinedRefs.clear();
137
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000138 MergedModule = Mod->takeModule();
139 IRLinker.setModule(MergedModule.get());
Manman Ren6487ce92015-02-24 00:45:56 +0000140
141 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
142 for (int I = 0, E = Undefs.size(); I != E; ++I)
143 AsmUndefinedRefs[Undefs[I]] = 1;
144}
145
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000146void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
147 this->Options = Options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000148}
149
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000150void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
151 switch (Debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000152 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000153 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000154 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000155
Bill Wendling0e1824c2012-03-31 11:15:43 +0000156 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000157 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000158 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000159 }
160 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000161}
162
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000163void LTOCodeGenerator::setOptLevel(unsigned Level) {
164 OptLevel = Level;
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000165 switch (OptLevel) {
166 case 0:
167 CGOptLevel = CodeGenOpt::None;
168 break;
169 case 1:
170 CGOptLevel = CodeGenOpt::Less;
171 break;
172 case 2:
173 CGOptLevel = CodeGenOpt::Default;
174 break;
175 case 3:
176 CGOptLevel = CodeGenOpt::Aggressive;
177 break;
178 }
179}
180
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000181bool LTOCodeGenerator::writeMergedModules(const char *Path,
182 std::string &ErrMsg) {
183 if (!determineTarget(ErrMsg))
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) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000193 ErrMsg = "could not open bitcode file for writing: ";
194 ErrMsg += Path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000195 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000196 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000197
Chris Lattner69733952009-08-23 07:49:08 +0000198 // write bitcode to it
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000199 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
Dan Gohmana2233f22010-09-01 14:20:41 +0000200 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000201
Dan Gohmana2233f22010-09-01 14:20:41 +0000202 if (Out.os().has_error()) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000203 ErrMsg = "could not write bitcode file: ";
204 ErrMsg += Path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000205 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000206 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000207 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000208
Dan Gohman8525fe72010-08-20 16:59:15 +0000209 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000210 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000211}
212
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000213bool LTOCodeGenerator::compileOptimizedToFile(const char **Name,
214 std::string &ErrMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000215 // make unique temp .o file to put generated object file
216 SmallString<128> Filename;
217 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000218 std::error_code EC =
219 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000220 if (EC) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000221 ErrMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000222 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000223 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000224
Shuxin Yang1826ae22013-08-12 21:07:31 +0000225 // generate object file
226 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000227
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000228 bool genResult = compileOptimized(&objFile.os(), ErrMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000229 objFile.os().close();
230 if (objFile.os().has_error()) {
231 objFile.os().clear_error();
232 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000233 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000234 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000235
Shuxin Yang1826ae22013-08-12 21:07:31 +0000236 objFile.keep();
237 if (!genResult) {
238 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000239 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000240 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000241
Rafael Espindolac80c9692013-09-04 17:44:24 +0000242 NativeObjectPath = Filename.c_str();
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000243 *Name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000244 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000245}
246
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000247std::unique_ptr<MemoryBuffer>
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000248LTOCodeGenerator::compileOptimized(std::string &ErrMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000249 const char *name;
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000250 if (!compileOptimizedToFile(&name, ErrMsg))
Craig Topper2617dcc2014-04-15 06:32:26 +0000251 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000252
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000253 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000254 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
255 MemoryBuffer::getFile(name, -1, false);
256 if (std::error_code EC = BufferOrErr.getError()) {
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000257 ErrMsg = EC.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000258 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000259 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000260 }
Rafael Espindolafac373c2011-02-24 21:04:06 +0000261
Shuxin Yang1826ae22013-08-12 21:07:31 +0000262 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000263 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000264
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000265 return std::move(*BufferOrErr);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000266}
267
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000268bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
269 bool DisableInline,
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000270 bool DisableGVNLoadPRE,
271 bool DisableVectorization,
272 std::string &ErrMsg) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000273 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
274 DisableVectorization, ErrMsg))
Manman Ren8121e1d2015-02-03 18:39:15 +0000275 return false;
276
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000277 return compileOptimizedToFile(Name, ErrMsg);
Manman Ren8121e1d2015-02-03 18:39:15 +0000278}
279
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000280std::unique_ptr<MemoryBuffer>
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000281LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
282 bool DisableGVNLoadPRE, bool DisableVectorization,
283 std::string &ErrMsg) {
284 if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
285 DisableVectorization, ErrMsg))
Manman Ren8121e1d2015-02-03 18:39:15 +0000286 return nullptr;
287
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000288 return compileOptimized(ErrMsg);
Manman Ren8121e1d2015-02-03 18:39:15 +0000289}
290
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000291bool LTOCodeGenerator::determineTarget(std::string &ErrMsg) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000292 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000293 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000294
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000295 std::string TripleStr = MergedModule->getTargetTriple();
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000296 if (TripleStr.empty()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000297 TripleStr = sys::getDefaultTargetTriple();
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000298 MergedModule->setTargetTriple(TripleStr);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000299 }
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000300 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000301
Bill Wendling45f74e32012-08-06 22:52:45 +0000302 // create target machine from info for merged modules
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000303 const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
Craig Topper2617dcc2014-04-15 06:32:26 +0000304 if (!march)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000305 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000306
Tom Roederfd1bc602014-04-25 21:46:51 +0000307 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
308 // the default set of features.
309 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000310 Features.getDefaultSubtargetFeatures(Triple);
Peter Collingbournec7b675f2015-08-22 02:25:53 +0000311 FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000312 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000313 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000314 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000315 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000316 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000317 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000318 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000319 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000320 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000321
Peter Collingbourneec43d0f2015-08-21 04:45:57 +0000322 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
323 Options, RelocModel,
324 CodeModel::Default, CGOptLevel));
Shuxin Yang95866fa2013-08-06 21:51:21 +0000325 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000326}
327
Bill Wendling0e1824c2012-03-31 11:15:43 +0000328void LTOCodeGenerator::
329applyRestriction(GlobalValue &GV,
Craig Topper3af97222014-08-27 05:25:00 +0000330 ArrayRef<StringRef> Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000331 std::vector<const char*> &MustPreserveList,
Craig Topper71b7b682014-08-21 05:55:13 +0000332 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000333 Mangler &Mangler) {
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000334 // There are no restrictions to apply to declarations.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000335 if (GV.isDeclaration())
336 return;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000337
338 // There is nothing more restrictive than private linkage.
339 if (GV.hasPrivateLinkage())
340 return;
341
342 SmallString<64> Buffer;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000343 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000344
Rafael Espindolac80c9692013-09-04 17:44:24 +0000345 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000346 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000347 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000348 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000349
350 // Conservatively append user-supplied runtime library functions to
351 // llvm.compiler.used. These could be internalized and deleted by
352 // optimizations like -globalopt, causing problems when later optimizations
353 // add new library calls (e.g., llvm.memset => memset and printf => puts).
354 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
355 if (isa<Function>(GV) &&
356 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
357 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000358}
359
360static void findUsedValues(GlobalVariable *LLVMUsed,
Craig Topper71b7b682014-08-21 05:55:13 +0000361 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000362 if (!LLVMUsed) return;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000363
Rafael Espindolacc111b22013-04-24 17:54:35 +0000364 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000365 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000366 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000367 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000368 UsedValues.insert(GV);
369}
370
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000371// Collect names of runtime library functions. User-defined functions with the
372// same names are added to llvm.compiler.used to prevent them from being
373// deleted by optimizations.
Justin Bognerb10a5202013-11-12 21:44:01 +0000374static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
375 const TargetLibraryInfo& TLI,
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000376 const Module &Mod,
377 const TargetMachine &TM) {
Justin Bognerb10a5202013-11-12 21:44:01 +0000378 // TargetLibraryInfo has info on C runtime library calls on the current
379 // target.
380 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
381 I != E; ++I) {
382 LibFunc::Func F = static_cast<LibFunc::Func>(I);
383 if (TLI.has(F))
384 Libcalls.push_back(TLI.getName(F));
385 }
386
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000387 SmallPtrSet<const TargetLowering *, 1> TLSet;
388
389 for (const Function &F : Mod) {
390 const TargetLowering *Lowering =
391 TM.getSubtargetImpl(F)->getTargetLowering();
392
393 if (Lowering && TLSet.insert(Lowering).second)
394 // TargetLowering has info on library calls that CodeGen expects to be
395 // available, both from the C runtime and compiler-rt.
396 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
397 I != E; ++I)
398 if (const char *Name =
399 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
400 Libcalls.push_back(Name);
401 }
Justin Bognerb10a5202013-11-12 21:44:01 +0000402
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000403 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000404 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
405 Libcalls.end());
406}
407
Chris Lattner2eff5052010-03-12 18:44:54 +0000408void LTOCodeGenerator::applyScopeRestrictions() {
Manman Rence0a0662015-04-17 17:10:09 +0000409 if (ScopeRestrictionsDone || !ShouldInternalize)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000410 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000411
Chris Lattner2eff5052010-03-12 18:44:54 +0000412 // Start off with a verification pass.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000413 legacy::PassManager passes;
Chris Lattner2eff5052010-03-12 18:44:54 +0000414 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000415
Bill Wendling39d942b2012-03-31 10:50:14 +0000416 // mark which symbols can not be internalized
Rafael Espindolac233f742015-06-23 13:59:29 +0000417 Mangler Mangler;
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000418 std::vector<const char*> MustPreserveList;
419 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000420 std::vector<StringRef> Libcalls;
Chandler Carruthc0291862015-01-24 02:06:09 +0000421 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
422 TargetLibraryInfo TLI(TLII);
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000423
Peter Collingbournee34034c2015-08-24 21:15:35 +0000424 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000425
Peter Collingbournee34034c2015-08-24 21:15:35 +0000426 for (Function &f : *MergedModule)
427 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
428 for (GlobalVariable &v : MergedModule->globals())
429 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
430 for (GlobalAlias &a : MergedModule->aliases())
431 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000432
433 GlobalVariable *LLVMCompilerUsed =
Peter Collingbournee34034c2015-08-24 21:15:35 +0000434 MergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000435 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000436 if (LLVMCompilerUsed)
437 LLVMCompilerUsed->eraseFromParent();
438
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000439 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000440 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000441 std::vector<Constant*> asmUsed2;
Rafael Espindola9c8c96f2014-05-05 20:06:41 +0000442 for (auto *GV : AsmUsed) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000443 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
444 asmUsed2.push_back(c);
445 }
446
447 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
448 LLVMCompilerUsed =
Peter Collingbournee34034c2015-08-24 21:15:35 +0000449 new llvm::GlobalVariable(*MergedModule, ATy, false,
Rafael Espindolacc111b22013-04-24 17:54:35 +0000450 llvm::GlobalValue::AppendingLinkage,
451 llvm::ConstantArray::get(ATy, asmUsed2),
452 "llvm.compiler.used");
453
454 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000455 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000456
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000457 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000458
Chris Lattner2eff5052010-03-12 18:44:54 +0000459 // apply scope restrictions
Peter Collingbournee34034c2015-08-24 21:15:35 +0000460 passes.run(*MergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000461
Rafael Espindolac80c9692013-09-04 17:44:24 +0000462 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000463}
464
Nick Kledzik07b4a622008-02-26 20:26:43 +0000465/// Optimize merged modules using various IPO passes
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000466bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
467 bool DisableGVNLoadPRE,
Manman Ren8121e1d2015-02-03 18:39:15 +0000468 bool DisableVectorization,
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000469 std::string &ErrMsg) {
470 if (!this->determineTarget(ErrMsg))
Shuxin Yang95866fa2013-08-06 21:51:21 +0000471 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000472
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000473 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000474 this->applyScopeRestrictions();
475
Bill Wendling0e1824c2012-03-31 11:15:43 +0000476 // Instantiate the pass manager to organize the passes.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000477 legacy::PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000478
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000479 // Add an appropriate DataLayout instance for this module...
Peter Collingbournee34034c2015-08-24 21:15:35 +0000480 MergedModule->setDataLayout(TargetMach->createDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000481
Chandler Carruth5ec2b1d2015-02-01 12:26:09 +0000482 passes.add(
483 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000484
Rafael Espindola216e0c02014-08-21 18:49:52 +0000485 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000486 PassManagerBuilder PMB;
487 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000488 PMB.LoopVectorize = !DisableVectorization;
489 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000490 if (!DisableInline)
491 PMB.Inliner = createFunctionInliningPass();
Chandler Carruthc0291862015-01-24 02:06:09 +0000492 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
Peter Collingbourne070843d2015-03-19 22:01:00 +0000493 PMB.OptLevel = OptLevel;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000494 PMB.VerifyInput = !DisableVerify;
495 PMB.VerifyOutput = !DisableVerify;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000496
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000497 PMB.populateLTOPassManager(passes);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000498
Manman Ren8121e1d2015-02-03 18:39:15 +0000499 // Run our queue of passes all at once now, efficiently.
Peter Collingbournee34034c2015-08-24 21:15:35 +0000500 passes.run(*MergedModule);
Manman Ren8121e1d2015-02-03 18:39:15 +0000501
502 return true;
503}
504
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000505bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out,
506 std::string &ErrMsg) {
507 if (!this->determineTarget(ErrMsg))
Manman Ren8121e1d2015-02-03 18:39:15 +0000508 return false;
509
Peter Collingbournec269ed52015-08-27 23:37:36 +0000510 legacy::PassManager preCodeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000511
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000512 // If the bitcode files contain ARC code and were compiled with optimization,
513 // the ObjCARCContractPass must be run, so do it unconditionally here.
Peter Collingbournec269ed52015-08-27 23:37:36 +0000514 preCodeGenPasses.add(createObjCARCContractPass());
515 preCodeGenPasses.run(*MergedModule);
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000516
Peter Collingbournec269ed52015-08-27 23:37:36 +0000517 // Do code generation. We need to preserve the module in case the client calls
518 // writeMergedModules() after compilation, but we only need to allow this at
519 // parallelism level 1. This is achieved by having splitCodeGen return the
520 // original module at parallelism level 1 which we then assign back to
521 // MergedModule.
522 MergedModule =
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000523 splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
Peter Collingbournec269ed52015-08-27 23:37:36 +0000524 RelocModel, CodeModel::Default, CGOptLevel);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000525
Shuxin Yang95866fa2013-08-06 21:51:21 +0000526 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000527}
528
Bill Wendling534a6582012-03-31 10:49:43 +0000529/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
530/// LTO problems.
Duncan P. N. Exon Smithf4967752015-08-31 23:44:06 +0000531void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
532 for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
533 o = getToken(o.second))
Peter Collingbourne22575122015-08-21 04:45:55 +0000534 CodegenOptions.push_back(o.first);
Nick Kledzikc2323472008-07-08 21:14:10 +0000535}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000536
537void LTOCodeGenerator::parseCodeGenDebugOptions() {
538 // if options were requested, set them
Peter Collingbourne22575122015-08-21 04:45:55 +0000539 if (!CodegenOptions.empty()) {
540 // ParseCommandLineOptions() expects argv[0] to be program name.
541 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
542 for (std::string &Arg : CodegenOptions)
543 CodegenArgv.push_back(Arg.c_str());
544 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
545 }
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000546}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000547
548void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
549 void *Context) {
550 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
551}
552
553void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
554 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
555 lto_codegen_diagnostic_severity_t Severity;
556 switch (DI.getSeverity()) {
557 case DS_Error:
558 Severity = LTO_DS_ERROR;
559 break;
560 case DS_Warning:
561 Severity = LTO_DS_WARNING;
562 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000563 case DS_Remark:
564 Severity = LTO_DS_REMARK;
565 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000566 case DS_Note:
567 Severity = LTO_DS_NOTE;
568 break;
569 }
570 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000571 std::string MsgStorage;
572 raw_string_ostream Stream(MsgStorage);
573 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000574 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000575 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000576
577 // If this method has been called it means someone has set up an external
578 // diagnostic handler. Assert on that.
579 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000580 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000581}
582
583void
584LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
585 void *Ctxt) {
586 this->DiagHandler = DiagHandler;
587 this->DiagContext = Ctxt;
588 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000589 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000590 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
591 // diagnostic to the external DiagHandler.
Duncan P. N. Exon Smithf02fe702014-10-02 21:11:04 +0000592 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
593 /* RespectFilters */ true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000594}