blob: 6203000c2ec39ea9935195eb70ab0e70e04c5077 [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"
Justin Bognerb10a5202013-11-12 21:44:01 +000021#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000022#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000026#include "llvm/IR/DiagnosticInfo.h"
27#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000029#include "llvm/IR/LegacyPassManager.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000030#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000032#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000033#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000034#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000035#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000036#include "llvm/MC/MCAsmInfo.h"
37#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000038#include "llvm/MC/SubtargetFeature.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000039#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000040#include "llvm/Support/FileSystem.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000041#include "llvm/Support/Host.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencerab425d82010-11-29 18:47:54 +000043#include "llvm/Support/Signals.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000046#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000047#include "llvm/Support/raw_ostream.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000048#include "llvm/Target/TargetLowering.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000049#include "llvm/Target/TargetOptions.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000050#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000051#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000052#include "llvm/Transforms/IPO.h"
53#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsonf36f15f2013-03-29 23:28:55 +000054#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000055#include <system_error>
Shuxin Yang76d082b2013-08-12 18:29:43 +000056using namespace llvm;
Shuxin Yang76d082b2013-08-12 18:29:43 +000057
Bill Wendling534a6582012-03-31 10:49:43 +000058const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik07b4a622008-02-26 20:26:43 +000059#ifdef LLVM_VERSION_INFO
Bill Wendling534a6582012-03-31 10:49:43 +000060 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik07b4a622008-02-26 20:26:43 +000061#else
Bill Wendling534a6582012-03-31 10:49:43 +000062 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik07b4a622008-02-26 20:26:43 +000063#endif
64}
65
Bill Wendling39d942b2012-03-31 10:50:14 +000066LTOCodeGenerator::LTOCodeGenerator()
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +000067 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)) {
Duncan P. N. Exon Smith7832e0a2015-04-27 23:19:26 +000068 initializeLTOPasses();
Duncan P. N. Exon Smithde5e32b2014-11-11 23:03:29 +000069}
70
71LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72 : OwnedContext(std::move(Context)), Context(*OwnedContext),
Duncan P. N. Exon Smith7832e0a2015-04-27 23:19:26 +000073 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000074 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000075}
76
Manman Ren082a3362015-02-25 21:20:53 +000077void LTOCodeGenerator::destroyMergedModule() {
78 if (OwnedModule) {
79 assert(IRLinker.getModule() == &OwnedModule->getModule() &&
80 "The linker's module should be the same as the owned module");
81 delete OwnedModule;
82 OwnedModule = nullptr;
83 } else if (IRLinker.getModule())
84 IRLinker.deleteModule();
85}
86
Bill Wendling534a6582012-03-31 10:49:43 +000087LTOCodeGenerator::~LTOCodeGenerator() {
Manman Ren082a3362015-02-25 21:20:53 +000088 destroyMergedModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +000089}
90
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000091// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +000092// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +000093// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000094void LTOCodeGenerator::initializeLTOPasses() {
95 PassRegistry &R = *PassRegistry::getPassRegistry();
96
97 initializeInternalizePassPass(R);
98 initializeIPSCCPPass(R);
99 initializeGlobalOptPass(R);
100 initializeConstantMergePass(R);
101 initializeDAHPass(R);
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000102 initializeInstructionCombiningPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000103 initializeSimpleInlinerPass(R);
104 initializePruneEHPass(R);
105 initializeGlobalDCEPass(R);
106 initializeArgPromotionPass(R);
107 initializeJumpThreadingPass(R);
108 initializeSROAPass(R);
109 initializeSROA_DTPass(R);
110 initializeSROA_SSAUpPass(R);
111 initializeFunctionAttrsPass(R);
112 initializeGlobalsModRefPass(R);
113 initializeLICMPass(R);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000114 initializeMergedLoadStoreMotionPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000115 initializeGVNPass(R);
116 initializeMemCpyOptPass(R);
117 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000118 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000119}
120
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000121bool LTOCodeGenerator::addModule(LTOModule *mod) {
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000122 assert(&mod->getModule().getContext() == &Context &&
123 "Expected module in same context");
124
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000125 bool ret = IRLinker.linkInModule(&mod->getModule());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000126
127 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
128 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000129 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000130
Shuxin Yangb6696a92013-08-07 05:19:23 +0000131 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000132}
Bill Wendling39d942b2012-03-31 10:50:14 +0000133
Manman Ren6487ce92015-02-24 00:45:56 +0000134void LTOCodeGenerator::setModule(LTOModule *Mod) {
135 assert(&Mod->getModule().getContext() == &Context &&
136 "Expected module in same context");
137
138 // Delete the old merged module.
Manman Ren082a3362015-02-25 21:20:53 +0000139 destroyMergedModule();
Manman Ren6487ce92015-02-24 00:45:56 +0000140 AsmUndefinedRefs.clear();
141
Manman Ren082a3362015-02-25 21:20:53 +0000142 OwnedModule = Mod;
Manman Ren6487ce92015-02-24 00:45:56 +0000143 IRLinker.setModule(&Mod->getModule());
144
145 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
146 for (int I = 0, E = Undefs.size(); I != E; ++I)
147 AsmUndefinedRefs[Undefs[I]] = 1;
148}
149
Rafael Espindola0b385c72013-09-30 16:39:19 +0000150void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
Rafael Espindola70d3c202014-06-19 22:27:46 +0000151 Options = options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000152}
153
Shuxin Yangb6696a92013-08-07 05:19:23 +0000154void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000155 switch (debug) {
156 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000157 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000158 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000159
Bill Wendling0e1824c2012-03-31 11:15:43 +0000160 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000161 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000162 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000163 }
164 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000165}
166
Shuxin Yangb6696a92013-08-07 05:19:23 +0000167void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000168 switch (model) {
169 case LTO_CODEGEN_PIC_MODEL_STATIC:
170 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
171 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
James Molloy951e5292014-04-14 13:54:16 +0000172 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000173 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000174 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000175 }
176 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000177}
178
Chris Lattner69733952009-08-23 07:49:08 +0000179bool LTOCodeGenerator::writeMergedModules(const char *path,
180 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000181 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000182 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000183
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000184 // mark which symbols can not be internalized
185 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000186
Chris Lattner69733952009-08-23 07:49:08 +0000187 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000188 std::error_code EC;
189 tool_output_file Out(path, EC, sys::fs::F_None);
190 if (EC) {
Chris Lattner69733952009-08-23 07:49:08 +0000191 errMsg = "could not open bitcode file for writing: ";
192 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000193 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000194 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000195
Chris Lattner69733952009-08-23 07:49:08 +0000196 // write bitcode to it
Duncan P. N. Exon Smith5a490d02015-04-27 23:38:54 +0000197 WriteBitcodeToFile(IRLinker.getModule(), Out.os(), ShouldEmbedUselists);
Dan Gohmana2233f22010-09-01 14:20:41 +0000198 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000199
Dan Gohmana2233f22010-09-01 14:20:41 +0000200 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000201 errMsg = "could not write bitcode file: ";
202 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000203 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000204 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000205 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000206
Dan Gohman8525fe72010-08-20 16:59:15 +0000207 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000208 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000209}
210
Manman Ren8121e1d2015-02-03 18:39:15 +0000211bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
212 std::string &errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000213 // make unique temp .o file to put generated object file
214 SmallString<128> Filename;
215 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000216 std::error_code EC =
217 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000218 if (EC) {
219 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000220 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000221 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000222
Shuxin Yang1826ae22013-08-12 21:07:31 +0000223 // generate object file
224 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000225
Manman Ren8121e1d2015-02-03 18:39:15 +0000226 bool genResult = compileOptimized(objFile.os(), errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000227 objFile.os().close();
228 if (objFile.os().has_error()) {
229 objFile.os().clear_error();
230 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000231 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000232 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000233
Shuxin Yang1826ae22013-08-12 21:07:31 +0000234 objFile.keep();
235 if (!genResult) {
236 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000237 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000238 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000239
Rafael Espindolac80c9692013-09-04 17:44:24 +0000240 NativeObjectPath = Filename.c_str();
241 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000242 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000243}
244
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000245std::unique_ptr<MemoryBuffer>
246LTOCodeGenerator::compileOptimized(std::string &errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000247 const char *name;
Manman Ren8121e1d2015-02-03 18:39:15 +0000248 if (!compileOptimizedToFile(&name, errMsg))
Craig Topper2617dcc2014-04-15 06:32:26 +0000249 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000250
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000251 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000252 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
253 MemoryBuffer::getFile(name, -1, false);
254 if (std::error_code EC = BufferOrErr.getError()) {
255 errMsg = EC.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000256 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000257 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000258 }
Rafael Espindolafac373c2011-02-24 21:04:06 +0000259
Shuxin Yang1826ae22013-08-12 21:07:31 +0000260 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000261 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000262
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000263 return std::move(*BufferOrErr);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000264}
265
Manman Ren8121e1d2015-02-03 18:39:15 +0000266
267bool LTOCodeGenerator::compile_to_file(const char **name,
Manman Ren8121e1d2015-02-03 18:39:15 +0000268 bool disableInline,
269 bool disableGVNLoadPRE,
270 bool disableVectorization,
271 std::string &errMsg) {
Peter Collingbourne070843d2015-03-19 22:01:00 +0000272 if (!optimize(disableInline, disableGVNLoadPRE,
Manman Ren8121e1d2015-02-03 18:39:15 +0000273 disableVectorization, errMsg))
274 return false;
275
276 return compileOptimizedToFile(name, errMsg);
277}
278
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000279std::unique_ptr<MemoryBuffer>
280LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
281 bool disableVectorization, std::string &errMsg) {
Peter Collingbourne070843d2015-03-19 22:01:00 +0000282 if (!optimize(disableInline, disableGVNLoadPRE,
Manman Ren8121e1d2015-02-03 18:39:15 +0000283 disableVectorization, errMsg))
284 return nullptr;
285
Peter Collingbourne3cc69d902015-06-01 20:08:30 +0000286 return compileOptimized(errMsg);
Manman Ren8121e1d2015-02-03 18:39:15 +0000287}
288
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000289bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000290 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000291 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000292
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000293 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000294 if (TripleStr.empty())
295 TripleStr = sys::getDefaultTargetTriple();
296 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000297
Bill Wendling45f74e32012-08-06 22:52:45 +0000298 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000299 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Craig Topper2617dcc2014-04-15 06:32:26 +0000300 if (!march)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000301 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000302
Bill Wendling45f74e32012-08-06 22:52:45 +0000303 // The relocation model is actually a static member of TargetMachine and
304 // needs to be set before the TargetMachine is instantiated.
305 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000306 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000307 case LTO_CODEGEN_PIC_MODEL_STATIC:
308 RelocModel = Reloc::Static;
309 break;
310 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
311 RelocModel = Reloc::PIC_;
312 break;
313 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
314 RelocModel = Reloc::DynamicNoPIC;
315 break;
James Molloy951e5292014-04-14 13:54:16 +0000316 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
317 // RelocModel is already the default, so leave it that way.
318 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000319 }
Bill Wendling45f74e32012-08-06 22:52:45 +0000320
Tom Roederfd1bc602014-04-25 21:46:51 +0000321 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
322 // the default set of features.
323 SubtargetFeatures Features(MAttr);
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000324 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendling45f74e32012-08-06 22:52:45 +0000325 std::string FeatureStr = Features.getString();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000326 // Set a default CPU for Darwin triples.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000327 if (MCpu.empty() && Triple.isOSDarwin()) {
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000328 if (Triple.getArch() == llvm::Triple::x86_64)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000329 MCpu = "core2";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000330 else if (Triple.getArch() == llvm::Triple::x86)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000331 MCpu = "yonah";
Tim Northovere19bed72014-07-23 12:32:47 +0000332 else if (Triple.getArch() == llvm::Triple::aarch64)
Tim Northover00ed9962014-03-29 10:18:08 +0000333 MCpu = "cyclone";
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000334 }
Rafael Espindola0b385c72013-09-30 16:39:19 +0000335
Peter Collingbourne070843d2015-03-19 22:01:00 +0000336 CodeGenOpt::Level CGOptLevel;
337 switch (OptLevel) {
338 case 0:
339 CGOptLevel = CodeGenOpt::None;
340 break;
341 case 1:
342 CGOptLevel = CodeGenOpt::Less;
343 break;
344 case 2:
345 CGOptLevel = CodeGenOpt::Default;
346 break;
347 case 3:
348 CGOptLevel = CodeGenOpt::Aggressive;
349 break;
350 }
351
Peter Collingbourneec43d0f2015-08-21 04:45:57 +0000352 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
353 Options, RelocModel,
354 CodeModel::Default, CGOptLevel));
Shuxin Yang95866fa2013-08-06 21:51:21 +0000355 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000356}
357
Bill Wendling0e1824c2012-03-31 11:15:43 +0000358void LTOCodeGenerator::
359applyRestriction(GlobalValue &GV,
Craig Topper3af97222014-08-27 05:25:00 +0000360 ArrayRef<StringRef> Libcalls,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000361 std::vector<const char*> &MustPreserveList,
Craig Topper71b7b682014-08-21 05:55:13 +0000362 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000363 Mangler &Mangler) {
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000364 // There are no restrictions to apply to declarations.
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000365 if (GV.isDeclaration())
366 return;
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000367
368 // There is nothing more restrictive than private linkage.
369 if (GV.hasPrivateLinkage())
370 return;
371
372 SmallString<64> Buffer;
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000373 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000374
Rafael Espindolac80c9692013-09-04 17:44:24 +0000375 if (MustPreserveSymbols.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000376 MustPreserveList.push_back(GV.getName().data());
Rafael Espindolac80c9692013-09-04 17:44:24 +0000377 if (AsmUndefinedRefs.count(Buffer))
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000378 AsmUsed.insert(&GV);
Justin Bognerb10a5202013-11-12 21:44:01 +0000379
380 // Conservatively append user-supplied runtime library functions to
381 // llvm.compiler.used. These could be internalized and deleted by
382 // optimizations like -globalopt, causing problems when later optimizations
383 // add new library calls (e.g., llvm.memset => memset and printf => puts).
384 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
385 if (isa<Function>(GV) &&
386 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
387 AsmUsed.insert(&GV);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000388}
389
390static void findUsedValues(GlobalVariable *LLVMUsed,
Craig Topper71b7b682014-08-21 05:55:13 +0000391 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000392 if (!LLVMUsed) return;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000393
Rafael Espindolacc111b22013-04-24 17:54:35 +0000394 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000395 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling39d942b2012-03-31 10:50:14 +0000396 if (GlobalValue *GV =
Bill Wendling0e1824c2012-03-31 11:15:43 +0000397 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000398 UsedValues.insert(GV);
399}
400
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000401// Collect names of runtime library functions. User-defined functions with the
402// same names are added to llvm.compiler.used to prevent them from being
403// deleted by optimizations.
Justin Bognerb10a5202013-11-12 21:44:01 +0000404static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
405 const TargetLibraryInfo& TLI,
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000406 const Module &Mod,
407 const TargetMachine &TM) {
Justin Bognerb10a5202013-11-12 21:44:01 +0000408 // TargetLibraryInfo has info on C runtime library calls on the current
409 // target.
410 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
411 I != E; ++I) {
412 LibFunc::Func F = static_cast<LibFunc::Func>(I);
413 if (TLI.has(F))
414 Libcalls.push_back(TLI.getName(F));
415 }
416
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000417 SmallPtrSet<const TargetLowering *, 1> TLSet;
418
419 for (const Function &F : Mod) {
420 const TargetLowering *Lowering =
421 TM.getSubtargetImpl(F)->getTargetLowering();
422
423 if (Lowering && TLSet.insert(Lowering).second)
424 // TargetLowering has info on library calls that CodeGen expects to be
425 // available, both from the C runtime and compiler-rt.
426 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
427 I != E; ++I)
428 if (const char *Name =
429 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
430 Libcalls.push_back(Name);
431 }
Justin Bognerb10a5202013-11-12 21:44:01 +0000432
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000433 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000434 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
435 Libcalls.end());
436}
437
Chris Lattner2eff5052010-03-12 18:44:54 +0000438void LTOCodeGenerator::applyScopeRestrictions() {
Manman Rence0a0662015-04-17 17:10:09 +0000439 if (ScopeRestrictionsDone || !ShouldInternalize)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000440 return;
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000441 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000442
Chris Lattner2eff5052010-03-12 18:44:54 +0000443 // Start off with a verification pass.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000444 legacy::PassManager passes;
Chris Lattner2eff5052010-03-12 18:44:54 +0000445 passes.add(createVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000446
Bill Wendling39d942b2012-03-31 10:50:14 +0000447 // mark which symbols can not be internalized
Rafael Espindolac233f742015-06-23 13:59:29 +0000448 Mangler Mangler;
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000449 std::vector<const char*> MustPreserveList;
450 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000451 std::vector<StringRef> Libcalls;
Chandler Carruthc0291862015-01-24 02:06:09 +0000452 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
453 TargetLibraryInfo TLI(TLII);
Akira Hatanaka8fba18e2015-01-30 01:16:24 +0000454
455 accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000456
457 for (Module::iterator f = mergedModule->begin(),
458 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000459 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000460 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000461 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000462 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000463 for (Module::alias_iterator a = mergedModule->alias_begin(),
464 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000465 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000466
467 GlobalVariable *LLVMCompilerUsed =
468 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000469 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000470 if (LLVMCompilerUsed)
471 LLVMCompilerUsed->eraseFromParent();
472
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000473 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000474 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000475 std::vector<Constant*> asmUsed2;
Rafael Espindola9c8c96f2014-05-05 20:06:41 +0000476 for (auto *GV : AsmUsed) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000477 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
478 asmUsed2.push_back(c);
479 }
480
481 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
482 LLVMCompilerUsed =
483 new llvm::GlobalVariable(*mergedModule, ATy, false,
484 llvm::GlobalValue::AppendingLinkage,
485 llvm::ConstantArray::get(ATy, asmUsed2),
486 "llvm.compiler.used");
487
488 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000489 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000490
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000491 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000492
Chris Lattner2eff5052010-03-12 18:44:54 +0000493 // apply scope restrictions
494 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000495
Rafael Espindolac80c9692013-09-04 17:44:24 +0000496 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000497}
498
Nick Kledzik07b4a622008-02-26 20:26:43 +0000499/// Optimize merged modules using various IPO passes
Peter Collingbourne070843d2015-03-19 22:01:00 +0000500bool LTOCodeGenerator::optimize(bool DisableInline,
Manman Ren8121e1d2015-02-03 18:39:15 +0000501 bool DisableGVNLoadPRE,
502 bool DisableVectorization,
503 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000504 if (!this->determineTarget(errMsg))
505 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000506
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000507 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000508
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000509 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000510 this->applyScopeRestrictions();
511
Bill Wendling0e1824c2012-03-31 11:15:43 +0000512 // Instantiate the pass manager to organize the passes.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000513 legacy::PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000514
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000515 // Add an appropriate DataLayout instance for this module...
Mehdi Amini26d48132015-07-24 16:04:22 +0000516 mergedModule->setDataLayout(TargetMach->createDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000517
Chandler Carruth5ec2b1d2015-02-01 12:26:09 +0000518 passes.add(
519 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000520
Rafael Espindola216e0c02014-08-21 18:49:52 +0000521 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000522 PassManagerBuilder PMB;
523 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000524 PMB.LoopVectorize = !DisableVectorization;
525 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000526 if (!DisableInline)
527 PMB.Inliner = createFunctionInliningPass();
Chandler Carruthc0291862015-01-24 02:06:09 +0000528 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
Peter Collingbourne070843d2015-03-19 22:01:00 +0000529 PMB.OptLevel = OptLevel;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000530 PMB.VerifyInput = true;
531 PMB.VerifyOutput = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000532
Chandler Carruth1efa12d2015-01-30 13:33:42 +0000533 PMB.populateLTOPassManager(passes);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000534
Manman Ren8121e1d2015-02-03 18:39:15 +0000535 // Run our queue of passes all at once now, efficiently.
536 passes.run(*mergedModule);
537
538 return true;
539}
540
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000541bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
542 std::string &errMsg) {
Manman Ren8121e1d2015-02-03 18:39:15 +0000543 if (!this->determineTarget(errMsg))
544 return false;
545
546 Module *mergedModule = IRLinker.getModule();
547
Chandler Carruth30d69c22015-02-13 10:01:29 +0000548 legacy::PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000549
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000550 // If the bitcode files contain ARC code and were compiled with optimization,
551 // the ObjCARCContractPass must be run, so do it unconditionally here.
552 codeGenPasses.add(createObjCARCContractPass());
553
Rafael Espindola5682ce22015-04-09 21:06:08 +0000554 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
Rafael Espindolac80c9692013-09-04 17:44:24 +0000555 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000556 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000557 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000558 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000559
Bill Wendling0e1824c2012-03-31 11:15:43 +0000560 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000561 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000562
Shuxin Yang95866fa2013-08-06 21:51:21 +0000563 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000564}
565
Bill Wendling534a6582012-03-31 10:49:43 +0000566/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
567/// LTO problems.
568void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
569 for (std::pair<StringRef, StringRef> o = getToken(options);
Peter Collingbourne22575122015-08-21 04:45:55 +0000570 !o.first.empty(); o = getToken(o.second))
571 CodegenOptions.push_back(o.first);
Nick Kledzikc2323472008-07-08 21:14:10 +0000572}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000573
574void LTOCodeGenerator::parseCodeGenDebugOptions() {
575 // if options were requested, set them
Peter Collingbourne22575122015-08-21 04:45:55 +0000576 if (!CodegenOptions.empty()) {
577 // ParseCommandLineOptions() expects argv[0] to be program name.
578 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
579 for (std::string &Arg : CodegenOptions)
580 CodegenArgv.push_back(Arg.c_str());
581 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
582 }
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000583}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000584
585void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
586 void *Context) {
587 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
588}
589
590void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
591 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
592 lto_codegen_diagnostic_severity_t Severity;
593 switch (DI.getSeverity()) {
594 case DS_Error:
595 Severity = LTO_DS_ERROR;
596 break;
597 case DS_Warning:
598 Severity = LTO_DS_WARNING;
599 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000600 case DS_Remark:
601 Severity = LTO_DS_REMARK;
602 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000603 case DS_Note:
604 Severity = LTO_DS_NOTE;
605 break;
606 }
607 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000608 std::string MsgStorage;
609 raw_string_ostream Stream(MsgStorage);
610 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000611 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000612 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000613
614 // If this method has been called it means someone has set up an external
615 // diagnostic handler. Assert on that.
616 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000617 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000618}
619
620void
621LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
622 void *Ctxt) {
623 this->DiagHandler = DiagHandler;
624 this->DiagContext = Ctxt;
625 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000626 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000627 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
628 // diagnostic to the external DiagHandler.
Duncan P. N. Exon Smithf02fe702014-10-02 21:11:04 +0000629 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
630 /* RespectFilters */ true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000631}