blob: ceaddce0bd4437693233eb67db55363d9dd83c67 [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"
Nick Kledzik07b4a622008-02-26 20:26:43 +000019#include "llvm/Bitcode/ReaderWriter.h"
Justin Bognerb10a5202013-11-12 21:44:01 +000020#include "llvm/CodeGen/RuntimeLibcalls.h"
Bill Wendling0e1824c2012-03-31 11:15:43 +000021#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +000025#include "llvm/IR/DiagnosticInfo.h"
26#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/LLVMContext.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000028#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000030#include "llvm/IR/Verifier.h"
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000031#include "llvm/InitializePasses.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000032#include "llvm/LTO/LTOModule.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000033#include "llvm/Linker/Linker.h"
Chris Lattner2eff5052010-03-12 18:44:54 +000034#include "llvm/MC/MCAsmInfo.h"
35#include "llvm/MC/MCContext.h"
Evan Cheng8264e272011-06-29 01:14:12 +000036#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/PassManager.h"
Nick Kledzikc2323472008-07-08 21:14:10 +000038#include "llvm/Support/CommandLine.h"
Rafael Espindola40c908b2013-06-17 18:05:35 +000039#include "llvm/Support/FileSystem.h"
David Greenea31f96c2009-07-14 20:18:05 +000040#include "llvm/Support/FormattedStream.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)) {
68 initialize();
69}
70
71LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
72 : OwnedContext(std::move(Context)), Context(*OwnedContext),
73 IRLinker(new Module("ld-temp.o", *OwnedContext)) {
74 initialize();
75}
76
77void LTOCodeGenerator::initialize() {
78 TargetMach = nullptr;
79 EmitDwarfDebugInfo = false;
80 ScopeRestrictionsDone = false;
81 CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
82 DiagHandler = nullptr;
83 DiagContext = nullptr;
84
Shuxin Yang1e6d80e2013-07-22 18:40:34 +000085 initializeLTOPasses();
Nick Kledzik07b4a622008-02-26 20:26:43 +000086}
87
Bill Wendling534a6582012-03-31 10:49:43 +000088LTOCodeGenerator::~LTOCodeGenerator() {
Rafael Espindolac80c9692013-09-04 17:44:24 +000089 delete TargetMach;
Craig Topper2617dcc2014-04-15 06:32:26 +000090 TargetMach = nullptr;
Bill Wendling91e6f6e2013-10-16 08:59:57 +000091
Rafael Espindola80df4bb2014-05-03 15:28:13 +000092 IRLinker.deleteModule();
Bill Wendling534a6582012-03-31 10:49:43 +000093
Rafael Espindolac80c9692013-09-04 17:44:24 +000094 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
95 E = CodegenOptions.end();
96 I != E; ++I)
Bill Wendling534a6582012-03-31 10:49:43 +000097 free(*I);
Nick Kledzik07b4a622008-02-26 20:26:43 +000098}
99
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000100// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangca760852013-07-23 06:44:34 +0000101// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000102// passes are initialized.
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000103void LTOCodeGenerator::initializeLTOPasses() {
104 PassRegistry &R = *PassRegistry::getPassRegistry();
105
106 initializeInternalizePassPass(R);
107 initializeIPSCCPPass(R);
108 initializeGlobalOptPass(R);
109 initializeConstantMergePass(R);
110 initializeDAHPass(R);
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000111 initializeInstructionCombiningPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000112 initializeSimpleInlinerPass(R);
113 initializePruneEHPass(R);
114 initializeGlobalDCEPass(R);
115 initializeArgPromotionPass(R);
116 initializeJumpThreadingPass(R);
117 initializeSROAPass(R);
118 initializeSROA_DTPass(R);
119 initializeSROA_SSAUpPass(R);
120 initializeFunctionAttrsPass(R);
121 initializeGlobalsModRefPass(R);
122 initializeLICMPass(R);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000123 initializeMergedLoadStoreMotionPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000124 initializeGVNPass(R);
125 initializeMemCpyOptPass(R);
126 initializeDCEPass(R);
Tom Stellardaa664d92013-08-06 02:43:45 +0000127 initializeCFGSimplifyPassPass(R);
Shuxin Yang1e6d80e2013-07-22 18:40:34 +0000128}
129
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000130bool LTOCodeGenerator::addModule(LTOModule *mod) {
Duncan P. N. Exon Smith94198632014-11-11 23:13:10 +0000131 assert(&mod->getModule().getContext() == &Context &&
132 "Expected module in same context");
133
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000134 bool ret = IRLinker.linkInModule(&mod->getModule());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000135
136 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
137 for (int i = 0, e = undefs.size(); i != e; ++i)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000138 AsmUndefinedRefs[undefs[i]] = 1;
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000139
Shuxin Yangb6696a92013-08-07 05:19:23 +0000140 return !ret;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000141}
Bill Wendling39d942b2012-03-31 10:50:14 +0000142
Rafael Espindola0b385c72013-09-30 16:39:19 +0000143void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
Rafael Espindola70d3c202014-06-19 22:27:46 +0000144 Options = options;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000145}
146
Shuxin Yangb6696a92013-08-07 05:19:23 +0000147void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000148 switch (debug) {
149 case LTO_DEBUG_MODEL_NONE:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000150 EmitDwarfDebugInfo = false;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000151 return;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000152
Bill Wendling0e1824c2012-03-31 11:15:43 +0000153 case LTO_DEBUG_MODEL_DWARF:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000154 EmitDwarfDebugInfo = true;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000155 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000156 }
157 llvm_unreachable("Unknown debug format!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000158}
159
Shuxin Yangb6696a92013-08-07 05:19:23 +0000160void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000161 switch (model) {
162 case LTO_CODEGEN_PIC_MODEL_STATIC:
163 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
164 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
James Molloy951e5292014-04-14 13:54:16 +0000165 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
Rafael Espindolac80c9692013-09-04 17:44:24 +0000166 CodeModel = model;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000167 return;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000168 }
169 llvm_unreachable("Unknown PIC model!");
Nick Kledzik07b4a622008-02-26 20:26:43 +0000170}
171
Chris Lattner69733952009-08-23 07:49:08 +0000172bool LTOCodeGenerator::writeMergedModules(const char *path,
173 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000174 if (!determineTarget(errMsg))
Shuxin Yangb6696a92013-08-07 05:19:23 +0000175 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000176
Bill Wendling2bbbfef2013-08-08 23:51:04 +0000177 // mark which symbols can not be internalized
178 applyScopeRestrictions();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000179
Chris Lattner69733952009-08-23 07:49:08 +0000180 // create output file
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000181 std::error_code EC;
182 tool_output_file Out(path, EC, sys::fs::F_None);
183 if (EC) {
Chris Lattner69733952009-08-23 07:49:08 +0000184 errMsg = "could not open bitcode file for writing: ";
185 errMsg += path;
Shuxin Yangb6696a92013-08-07 05:19:23 +0000186 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000187 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000188
Chris Lattner69733952009-08-23 07:49:08 +0000189 // write bitcode to it
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000190 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
Dan Gohmana2233f22010-09-01 14:20:41 +0000191 Out.os().close();
Dan Gohmanab366f02010-05-27 20:19:47 +0000192
Dan Gohmana2233f22010-09-01 14:20:41 +0000193 if (Out.os().has_error()) {
Chris Lattner69733952009-08-23 07:49:08 +0000194 errMsg = "could not write bitcode file: ";
195 errMsg += path;
Dan Gohmana2233f22010-09-01 14:20:41 +0000196 Out.os().clear_error();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000197 return false;
Chris Lattner69733952009-08-23 07:49:08 +0000198 }
Bill Wendling39d942b2012-03-31 10:50:14 +0000199
Dan Gohman8525fe72010-08-20 16:59:15 +0000200 Out.keep();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000201 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000202}
203
Duncan P. N. Exon Smithbccb4fd2014-01-10 20:24:35 +0000204bool LTOCodeGenerator::compile_to_file(const char** name,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000205 bool disableOpt,
206 bool disableInline,
207 bool disableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000208 bool disableVectorization,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000209 std::string& errMsg) {
Shuxin Yang1826ae22013-08-12 21:07:31 +0000210 // make unique temp .o file to put generated object file
211 SmallString<128> Filename;
212 int FD;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000213 std::error_code EC =
214 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000215 if (EC) {
216 errMsg = EC.message();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000217 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000218 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000219
Shuxin Yang1826ae22013-08-12 21:07:31 +0000220 // generate object file
221 tool_output_file objFile(Filename.c_str(), FD);
Bill Wendling0e1824c2012-03-31 11:15:43 +0000222
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000223 bool genResult =
224 generateObjectFile(objFile.os(), disableOpt, disableInline,
225 disableGVNLoadPRE, disableVectorization, errMsg);
Shuxin Yang1826ae22013-08-12 21:07:31 +0000226 objFile.os().close();
227 if (objFile.os().has_error()) {
228 objFile.os().clear_error();
229 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000230 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000231 }
Bill Wendling0e1824c2012-03-31 11:15:43 +0000232
Shuxin Yang1826ae22013-08-12 21:07:31 +0000233 objFile.keep();
234 if (!genResult) {
235 sys::fs::remove(Twine(Filename));
Shuxin Yangb6696a92013-08-07 05:19:23 +0000236 return false;
Shuxin Yang1826ae22013-08-12 21:07:31 +0000237 }
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000238
Rafael Espindolac80c9692013-09-04 17:44:24 +0000239 NativeObjectPath = Filename.c_str();
240 *name = NativeObjectPath.c_str();
Shuxin Yangb6696a92013-08-07 05:19:23 +0000241 return true;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000242}
243
Rafael Espindola0b385c72013-09-30 16:39:19 +0000244const void* LTOCodeGenerator::compile(size_t* length,
245 bool disableOpt,
246 bool disableInline,
247 bool disableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000248 bool disableVectorization,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000249 std::string& errMsg) {
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000250 const char *name;
Rafael Espindola0b385c72013-09-30 16:39:19 +0000251 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000252 disableVectorization, errMsg))
Craig Topper2617dcc2014-04-15 06:32:26 +0000253 return nullptr;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000254
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000255 // read .o file into memory buffer
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000256 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
257 MemoryBuffer::getFile(name, -1, false);
258 if (std::error_code EC = BufferOrErr.getError()) {
259 errMsg = EC.message();
Rafael Espindolac80c9692013-09-04 17:44:24 +0000260 sys::fs::remove(NativeObjectPath);
Craig Topper2617dcc2014-04-15 06:32:26 +0000261 return nullptr;
Rafael Espindola26b57ff2011-03-22 20:57:13 +0000262 }
David Blaikie78fdec52014-09-02 18:21:06 +0000263 NativeObjectFile = std::move(*BufferOrErr);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000264
Shuxin Yang1826ae22013-08-12 21:07:31 +0000265 // remove temp files
Rafael Espindolac80c9692013-09-04 17:44:24 +0000266 sys::fs::remove(NativeObjectPath);
Rafael Espindolafac373c2011-02-24 21:04:06 +0000267
Shuxin Yang1826ae22013-08-12 21:07:31 +0000268 // return buffer, unless error
Craig Topper2617dcc2014-04-15 06:32:26 +0000269 if (!NativeObjectFile)
270 return nullptr;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000271 *length = NativeObjectFile->getBufferSize();
272 return NativeObjectFile->getBufferStart();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000273}
274
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000275bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000276 if (TargetMach)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000277 return true;
Daniel Dunbar0f16ea52009-08-03 04:03:51 +0000278
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000279 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000280 if (TripleStr.empty())
281 TripleStr = sys::getDefaultTargetTriple();
282 llvm::Triple Triple(TripleStr);
Bill Wendling9b2c5732008-06-18 06:35:30 +0000283
Bill Wendling45f74e32012-08-06 22:52:45 +0000284 // create target machine from info for merged modules
Bob Wilson3f7e7c02012-10-12 17:39:25 +0000285 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Craig Topper2617dcc2014-04-15 06:32:26 +0000286 if (!march)
Shuxin Yang95866fa2013-08-06 21:51:21 +0000287 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000288
Bill Wendling45f74e32012-08-06 22:52:45 +0000289 // The relocation model is actually a static member of TargetMachine and
290 // needs to be set before the TargetMachine is instantiated.
291 Reloc::Model RelocModel = Reloc::Default;
Rafael Espindolac80c9692013-09-04 17:44:24 +0000292 switch (CodeModel) {
Bill Wendling45f74e32012-08-06 22:52:45 +0000293 case LTO_CODEGEN_PIC_MODEL_STATIC:
294 RelocModel = Reloc::Static;
295 break;
296 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
297 RelocModel = Reloc::PIC_;
298 break;
299 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
300 RelocModel = Reloc::DynamicNoPIC;
301 break;
James Molloy951e5292014-04-14 13:54:16 +0000302 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
303 // RelocModel is already the default, so leave it that way.
304 break;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000305 }
Bill Wendling45f74e32012-08-06 22:52:45 +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);
Bill Wendling45f74e32012-08-06 22:52:45 +0000311 std::string 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
Rafael Espindolac80c9692013-09-04 17:44:24 +0000322 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
323 RelocModel, CodeModel::Default,
324 CodeGenOpt::Aggressive);
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
Justin Bognerb10a5202013-11-12 21:44:01 +0000371static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
372 const TargetLibraryInfo& TLI,
373 const TargetLowering *Lowering)
374{
375 // TargetLibraryInfo has info on C runtime library calls on the current
376 // target.
377 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
378 I != E; ++I) {
379 LibFunc::Func F = static_cast<LibFunc::Func>(I);
380 if (TLI.has(F))
381 Libcalls.push_back(TLI.getName(F));
382 }
383
384 // TargetLowering has info on library calls that CodeGen expects to be
385 // available, both from the C runtime and compiler-rt.
386 if (Lowering)
387 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
388 I != E; ++I)
389 if (const char *Name
390 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
391 Libcalls.push_back(Name);
392
Duncan P. N. Exon Smith0c8d6042013-11-16 16:15:56 +0000393 array_pod_sort(Libcalls.begin(), Libcalls.end());
Justin Bognerb10a5202013-11-12 21:44:01 +0000394 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
395 Libcalls.end());
396}
397
Chris Lattner2eff5052010-03-12 18:44:54 +0000398void LTOCodeGenerator::applyScopeRestrictions() {
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000399 if (ScopeRestrictionsDone)
Rafael Espindolac80c9692013-09-04 17:44:24 +0000400 return;
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000401 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000402
Chris Lattner2eff5052010-03-12 18:44:54 +0000403 // Start off with a verification pass.
404 PassManager passes;
405 passes.add(createVerifierPass());
Duncan P. N. Exon Smith6ef5f282014-04-15 16:27:38 +0000406 passes.add(createDebugInfoVerifierPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000407
Bill Wendling39d942b2012-03-31 10:50:14 +0000408 // mark which symbols can not be internalized
Eric Christopherd9134482014-08-04 21:25:23 +0000409 Mangler Mangler(TargetMach->getSubtargetImpl()->getDataLayout());
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000410 std::vector<const char*> MustPreserveList;
411 SmallPtrSet<GlobalValue*, 8> AsmUsed;
Justin Bognerb10a5202013-11-12 21:44:01 +0000412 std::vector<StringRef> Libcalls;
413 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
Eric Christopherd9134482014-08-04 21:25:23 +0000414 accumulateAndSortLibcalls(
415 Libcalls, TLI, TargetMach->getSubtargetImpl()->getTargetLowering());
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000416
417 for (Module::iterator f = mergedModule->begin(),
418 e = mergedModule->end(); f != e; ++f)
Justin Bognerb10a5202013-11-12 21:44:01 +0000419 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
Bill Wendling39d942b2012-03-31 10:50:14 +0000420 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000421 e = mergedModule->global_end(); v != e; ++v)
Justin Bognerb10a5202013-11-12 21:44:01 +0000422 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000423 for (Module::alias_iterator a = mergedModule->alias_begin(),
424 e = mergedModule->alias_end(); a != e; ++a)
Justin Bognerb10a5202013-11-12 21:44:01 +0000425 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000426
427 GlobalVariable *LLVMCompilerUsed =
428 mergedModule->getGlobalVariable("llvm.compiler.used");
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000429 findUsedValues(LLVMCompilerUsed, AsmUsed);
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000430 if (LLVMCompilerUsed)
431 LLVMCompilerUsed->eraseFromParent();
432
Rafael Espindolab7c0b4a2013-09-04 20:08:46 +0000433 if (!AsmUsed.empty()) {
Rafael Espindolac80c9692013-09-04 17:44:24 +0000434 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
Rafael Espindolacc111b22013-04-24 17:54:35 +0000435 std::vector<Constant*> asmUsed2;
Rafael Espindola9c8c96f2014-05-05 20:06:41 +0000436 for (auto *GV : AsmUsed) {
Rafael Espindolacc111b22013-04-24 17:54:35 +0000437 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
438 asmUsed2.push_back(c);
439 }
440
441 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
442 LLVMCompilerUsed =
443 new llvm::GlobalVariable(*mergedModule, ATy, false,
444 llvm::GlobalValue::AppendingLinkage,
445 llvm::ConstantArray::get(ATy, asmUsed2),
446 "llvm.compiler.used");
447
448 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner2eff5052010-03-12 18:44:54 +0000449 }
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000450
Duncan P. N. Exon Smith4680f402014-04-02 22:05:57 +0000451 passes.add(createInternalizePass(MustPreserveList));
Rafael Espindola1e49a6d2011-03-02 04:14:42 +0000452
Chris Lattner2eff5052010-03-12 18:44:54 +0000453 // apply scope restrictions
454 passes.run(*mergedModule);
Bill Wendling39d942b2012-03-31 10:50:14 +0000455
Rafael Espindolac80c9692013-09-04 17:44:24 +0000456 ScopeRestrictionsDone = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000457}
458
Nick Kledzik07b4a622008-02-26 20:26:43 +0000459/// Optimize merged modules using various IPO passes
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000460bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
Rafael Espindola0b385c72013-09-30 16:39:19 +0000461 bool DisableOpt,
462 bool DisableInline,
463 bool DisableGVNLoadPRE,
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000464 bool DisableVectorization,
Chris Lattnerf200a0a2011-05-22 00:20:07 +0000465 std::string &errMsg) {
Shuxin Yang95866fa2013-08-06 21:51:21 +0000466 if (!this->determineTarget(errMsg))
467 return false;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000468
Rafael Espindola80df4bb2014-05-03 15:28:13 +0000469 Module *mergedModule = IRLinker.getModule();
Nick Kledzik07b4a622008-02-26 20:26:43 +0000470
Bill Wendlingf44b2a22013-05-23 21:21:50 +0000471 // Mark which symbols can not be internalized
Bill Wendling383fda22012-04-09 22:18:01 +0000472 this->applyScopeRestrictions();
473
Bill Wendling0e1824c2012-03-31 11:15:43 +0000474 // Instantiate the pass manager to organize the passes.
475 PassManager passes;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000476
Micah Villmow9cfc13d2012-10-08 16:39:34 +0000477 // Add an appropriate DataLayout instance for this module...
Eric Christopherd9134482014-08-04 21:25:23 +0000478 mergedModule->setDataLayout(TargetMach->getSubtargetImpl()->getDataLayout());
Bill Wendling39d942b2012-03-31 10:50:14 +0000479
Rafael Espindola216e0c02014-08-21 18:49:52 +0000480 Triple TargetTriple(TargetMach->getTargetTriple());
Rafael Espindola7cebf362014-08-21 20:03:44 +0000481 PassManagerBuilder PMB;
482 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +0000483 PMB.LoopVectorize = !DisableVectorization;
484 PMB.SLPVectorize = !DisableVectorization;
Rafael Espindola7cebf362014-08-21 20:03:44 +0000485 if (!DisableInline)
486 PMB.Inliner = createFunctionInliningPass();
487 PMB.LibraryInfo = new TargetLibraryInfo(TargetTriple);
488 if (DisableOpt)
489 PMB.OptLevel = 0;
490 PMB.VerifyInput = true;
491 PMB.VerifyOutput = true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000492
Rafael Espindola7cebf362014-08-21 20:03:44 +0000493 PMB.populateLTOPassManager(passes, TargetMach);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000494
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000495 PassManager codeGenPasses;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000496
Rafael Espindolac435adc2014-09-10 21:27:43 +0000497 codeGenPasses.add(new DataLayoutPass());
Nick Kledzik07b4a622008-02-26 20:26:43 +0000498
Bill Wendling0e1824c2012-03-31 11:15:43 +0000499 formatted_raw_ostream Out(out);
Dan Gohmana2233f22010-09-01 14:20:41 +0000500
Bob Wilsonf36f15f2013-03-29 23:28:55 +0000501 // If the bitcode files contain ARC code and were compiled with optimization,
502 // the ObjCARCContractPass must be run, so do it unconditionally here.
503 codeGenPasses.add(createObjCARCContractPass());
504
Rafael Espindolac80c9692013-09-04 17:44:24 +0000505 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
506 TargetMachine::CGFT_ObjectFile)) {
Bill Wendling0e1824c2012-03-31 11:15:43 +0000507 errMsg = "target file type not supported";
Shuxin Yang95866fa2013-08-06 21:51:21 +0000508 return false;
Bill Wendling0e1824c2012-03-31 11:15:43 +0000509 }
Nick Kledzik07b4a622008-02-26 20:26:43 +0000510
Bill Wendling0e1824c2012-03-31 11:15:43 +0000511 // Run our queue of passes all at once now, efficiently.
512 passes.run(*mergedModule);
Nick Kledzik07b4a622008-02-26 20:26:43 +0000513
Bill Wendling0e1824c2012-03-31 11:15:43 +0000514 // Run the code generator, and write assembly file
Lang Hamesdfa3f8f2013-03-13 21:18:46 +0000515 codeGenPasses.run(*mergedModule);
Nick Lewyckyfd6a2492009-07-26 22:16:39 +0000516
Shuxin Yang95866fa2013-08-06 21:51:21 +0000517 return true;
Nick Kledzik07b4a622008-02-26 20:26:43 +0000518}
519
Bill Wendling534a6582012-03-31 10:49:43 +0000520/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
521/// LTO problems.
522void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
523 for (std::pair<StringRef, StringRef> o = getToken(options);
524 !o.first.empty(); o = getToken(o.second)) {
525 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
526 // that.
Rafael Espindolac80c9692013-09-04 17:44:24 +0000527 if (CodegenOptions.empty())
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000528 CodegenOptions.push_back(strdup("libLLVMLTO"));
Rafael Espindolac80c9692013-09-04 17:44:24 +0000529 CodegenOptions.push_back(strdup(o.first.str().c_str()));
Bill Wendling534a6582012-03-31 10:49:43 +0000530 }
Nick Kledzikc2323472008-07-08 21:14:10 +0000531}
Rafael Espindolaefa02d52013-10-02 14:36:23 +0000532
533void LTOCodeGenerator::parseCodeGenDebugOptions() {
534 // if options were requested, set them
535 if (!CodegenOptions.empty())
536 cl::ParseCommandLineOptions(CodegenOptions.size(),
537 const_cast<char **>(&CodegenOptions[0]));
538}
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000539
540void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
541 void *Context) {
542 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
543}
544
545void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
546 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
547 lto_codegen_diagnostic_severity_t Severity;
548 switch (DI.getSeverity()) {
549 case DS_Error:
550 Severity = LTO_DS_ERROR;
551 break;
552 case DS_Warning:
553 Severity = LTO_DS_WARNING;
554 break;
Tobias Grossere8d4c9a2014-02-28 09:08:45 +0000555 case DS_Remark:
556 Severity = LTO_DS_REMARK;
557 break;
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000558 case DS_Note:
559 Severity = LTO_DS_NOTE;
560 break;
561 }
562 // Create the string that will be reported to the external diagnostic handler.
Alp Tokere69170a2014-06-26 22:52:05 +0000563 std::string MsgStorage;
564 raw_string_ostream Stream(MsgStorage);
565 DiagnosticPrinterRawOStream DP(Stream);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000566 DI.print(DP);
Alp Tokere69170a2014-06-26 22:52:05 +0000567 Stream.flush();
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000568
569 // If this method has been called it means someone has set up an external
570 // diagnostic handler. Assert on that.
571 assert(DiagHandler && "Invalid diagnostic handler");
Alp Tokere69170a2014-06-26 22:52:05 +0000572 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000573}
574
575void
576LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
577 void *Ctxt) {
578 this->DiagHandler = DiagHandler;
579 this->DiagContext = Ctxt;
580 if (!DiagHandler)
Craig Topper2617dcc2014-04-15 06:32:26 +0000581 return Context.setDiagnosticHandler(nullptr, nullptr);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000582 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
583 // diagnostic to the external DiagHandler.
Duncan P. N. Exon Smithf02fe702014-10-02 21:11:04 +0000584 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
585 /* RespectFilters */ true);
Quentin Colombet5fa1f6f2014-01-15 22:04:35 +0000586}