blob: bcbd01752a4cba4b5b075831a9162750f4f5158b [file] [log] [blame]
Nick Kledzik77595fc2008-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 Wendling76b13ed2012-03-31 10:50:14 +00007//
Nick Kledzik77595fc2008-02-26 20:26:43 +00008//===----------------------------------------------------------------------===//
9//
Bill Wendling76b13ed2012-03-31 10:50:14 +000010// This file implements the Link Time Optimization library. This library is
Nick Kledzik77595fc2008-02-26 20:26:43 +000011// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Nick Kledzikef194ed2008-02-27 22:25:36 +000015#include "LTOCodeGenerator.h"
Bill Wendlingab53bc72012-03-31 11:10:35 +000016#include "LTOModule.h"
Shuxin Yang67d135a2013-08-12 18:29:43 +000017#include "LTOPartition.h"
18#include "LTOPostIPODriver.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000019#include "llvm/ADT/StringExtras.h"
Nick Lewycky8189d402009-06-17 06:52:10 +000020#include "llvm/Analysis/Passes.h"
Rafael Espindolac684e832011-08-02 21:50:27 +000021#include "llvm/Analysis/Verifier.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000022#include "llvm/Bitcode/ReaderWriter.h"
Bill Wendlingc94c5622012-03-31 11:15:43 +000023#include "llvm/Config/config.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
Shuxin Yang8945f752013-07-22 18:40:34 +000029#include "llvm/InitializePasses.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000030#include "llvm/Linker.h"
Chris Lattner5ef31a02010-03-12 18:44:54 +000031#include "llvm/MC/MCAsmInfo.h"
32#include "llvm/MC/MCContext.h"
Evan Chengab8be962011-06-29 01:14:12 +000033#include "llvm/MC/SubtargetFeature.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000034#include "llvm/PassManager.h"
Nick Kledzik920ae982008-07-08 21:14:10 +000035#include "llvm/Support/CommandLine.h"
Rafael Espindola68c0efa2013-06-17 18:05:35 +000036#include "llvm/Support/FileSystem.h"
David Greene71847812009-07-14 20:18:05 +000037#include "llvm/Support/FormattedStream.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000038#include "llvm/Support/Host.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000039#include "llvm/Support/MemoryBuffer.h"
Shuxin Yang67d135a2013-08-12 18:29:43 +000040#include "llvm/Support/Program.h"
Michael J. Spencer3cc52ea2010-11-29 18:47:54 +000041#include "llvm/Support/Signals.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000042#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000044#include "llvm/Support/ToolOutputFile.h"
Michael J. Spencerf2f516f2010-12-09 18:06:07 +000045#include "llvm/Support/system_error.h"
Shuxin Yang67d135a2013-08-12 18:29:43 +000046#include "llvm/Support/SourceMgr.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000047#include "llvm/Target/Mangler.h"
48#include "llvm/Target/TargetMachine.h"
49#include "llvm/Target/TargetOptions.h"
50#include "llvm/Target/TargetRegisterInfo.h"
51#include "llvm/Transforms/IPO.h"
52#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Bob Wilsond6965442013-03-29 23:28:55 +000053#include "llvm/Transforms/ObjCARC.h"
Nick Kledzik77595fc2008-02-26 20:26:43 +000054
Shuxin Yang67d135a2013-08-12 18:29:43 +000055using namespace llvm;
56using namespace lto;
57
58// /////////////////////////////////////////////////////////////////////////////
59//
60// Internal options. To avoid collision, most options start with "lto-".
61//
62// /////////////////////////////////////////////////////////////////////////////
63//
Bill Wendling9ac0aaa2012-08-06 21:34:54 +000064static cl::opt<bool>
Bill Wendling6303b662013-02-28 14:11:10 +000065DisableOpt("disable-opt", cl::init(false),
66 cl::desc("Do not run any optimization passes"));
67
68static cl::opt<bool>
Bill Wendling9ac0aaa2012-08-06 21:34:54 +000069DisableInline("disable-inlining", cl::init(false),
Nick Kledzik920ae982008-07-08 21:14:10 +000070 cl::desc("Do not run the inliner pass"));
Nick Kledzik77595fc2008-02-26 20:26:43 +000071
Bill Wendling9ac0aaa2012-08-06 21:34:54 +000072static cl::opt<bool>
73DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
Bill Wendling3197b442012-04-02 22:16:50 +000074 cl::desc("Do not run the GVN load PRE pass"));
75
Shuxin Yang67d135a2013-08-12 18:29:43 +000076// To break merged module into partitions, and compile them independently.
77static cl::opt<bool>
78EnablePartition("lto-partition", cl::init(false),
79 cl::desc("Partition program and compile each piece in parallel"));
80
81// Specify the work-directory for the LTO compilation. All intermeidate
82// files will be created immediately under this dir. If it is not
83// specified, compiler will create an unique directory under current-dir.
84//
85static cl::opt<std::string>
86TmpWorkDir("lto-workdir", cl::init(""), cl::desc("Specify working directory"));
87
88static cl::opt<bool>
89KeepWorkDir("lto-keep", cl::init(false), cl::desc("Keep working directory"));
90
91
92// /////////////////////////////////////////////////////////////////////////////
93//
94// Implementation of LTOCodeGenerator
95//
96// /////////////////////////////////////////////////////////////////////////////
97//
Bill Wendlingcaf71d42012-03-31 10:49:43 +000098const char* LTOCodeGenerator::getVersionString() {
Nick Kledzik77595fc2008-02-26 20:26:43 +000099#ifdef LLVM_VERSION_INFO
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000100 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000101#else
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000102 return PACKAGE_NAME " version " PACKAGE_VERSION;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000103#endif
104}
105
Bill Wendling76b13ed2012-03-31 10:50:14 +0000106LTOCodeGenerator::LTOCodeGenerator()
Bill Wendlingc94c5622012-03-31 11:15:43 +0000107 : _context(getGlobalContext()),
Rafael Espindola10519372013-05-04 02:43:00 +0000108 _linker(new Module("ld-temp.o", _context)), _target(NULL),
Bill Wendlingc94c5622012-03-31 11:15:43 +0000109 _emitDwarfDebugInfo(false), _scopeRestrictionsDone(false),
Bill Wendling50f31832012-12-10 21:33:45 +0000110 _codeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
Shuxin Yang67d135a2013-08-12 18:29:43 +0000111 _nativeObjectFile(NULL), PartitionMgr(FileMgr),
112 OptionsParsed(false) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000113 InitializeAllTargets();
114 InitializeAllTargetMCs();
115 InitializeAllAsmPrinters();
Shuxin Yang8945f752013-07-22 18:40:34 +0000116 initializeLTOPasses();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000117}
118
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000119LTOCodeGenerator::~LTOCodeGenerator() {
120 delete _target;
121 delete _nativeObjectFile;
Rafael Espindola10519372013-05-04 02:43:00 +0000122 delete _linker.getModule();
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000123
Bill Wendlingf2cc2ee2012-03-31 10:51:45 +0000124 for (std::vector<char*>::iterator I = _codegenOptions.begin(),
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000125 E = _codegenOptions.end(); I != E; ++I)
126 free(*I);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000127}
128
Shuxin Yang8945f752013-07-22 18:40:34 +0000129// Initialize LTO passes. Please keep this funciton in sync with
Shuxin Yangc679d6b2013-07-23 06:44:34 +0000130// PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
Shuxin Yang8945f752013-07-22 18:40:34 +0000131// passes are initialized.
132//
133void LTOCodeGenerator::initializeLTOPasses() {
134 PassRegistry &R = *PassRegistry::getPassRegistry();
135
136 initializeInternalizePassPass(R);
137 initializeIPSCCPPass(R);
138 initializeGlobalOptPass(R);
139 initializeConstantMergePass(R);
140 initializeDAHPass(R);
141 initializeInstCombinerPass(R);
142 initializeSimpleInlinerPass(R);
143 initializePruneEHPass(R);
144 initializeGlobalDCEPass(R);
145 initializeArgPromotionPass(R);
146 initializeJumpThreadingPass(R);
147 initializeSROAPass(R);
148 initializeSROA_DTPass(R);
149 initializeSROA_SSAUpPass(R);
150 initializeFunctionAttrsPass(R);
151 initializeGlobalsModRefPass(R);
152 initializeLICMPass(R);
153 initializeGVNPass(R);
154 initializeMemCpyOptPass(R);
155 initializeDCEPass(R);
Tom Stellard01d72032013-08-06 02:43:45 +0000156 initializeCFGSimplifyPassPass(R);
Shuxin Yang8945f752013-07-22 18:40:34 +0000157}
158
Bill Wendlingc94c5622012-03-31 11:15:43 +0000159bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
Rafael Espindolafca88632013-05-04 03:06:50 +0000160 bool ret = _linker.linkInModule(mod->getLLVVMModule(), &errMsg);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000161
162 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
163 for (int i = 0, e = undefs.size(); i != e; ++i)
164 _asmUndefinedRefs[undefs[i]] = 1;
165
Shuxin Yang235089b2013-08-07 05:19:23 +0000166 return !ret;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000167}
Bill Wendling76b13ed2012-03-31 10:50:14 +0000168
Shuxin Yang235089b2013-08-07 05:19:23 +0000169void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000170 switch (debug) {
171 case LTO_DEBUG_MODEL_NONE:
172 _emitDwarfDebugInfo = false;
Shuxin Yang235089b2013-08-07 05:19:23 +0000173 return;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000174
Bill Wendlingc94c5622012-03-31 11:15:43 +0000175 case LTO_DEBUG_MODEL_DWARF:
176 _emitDwarfDebugInfo = true;
Shuxin Yang235089b2013-08-07 05:19:23 +0000177 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000178 }
179 llvm_unreachable("Unknown debug format!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000180}
181
Shuxin Yang235089b2013-08-07 05:19:23 +0000182void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000183 switch (model) {
184 case LTO_CODEGEN_PIC_MODEL_STATIC:
185 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
186 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
187 _codeModel = model;
Shuxin Yang235089b2013-08-07 05:19:23 +0000188 return;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000189 }
190 llvm_unreachable("Unknown PIC model!");
Nick Kledzik77595fc2008-02-26 20:26:43 +0000191}
192
Chris Lattnerb515d752009-08-23 07:49:08 +0000193bool LTOCodeGenerator::writeMergedModules(const char *path,
194 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000195 if (!determineTarget(errMsg))
Shuxin Yang235089b2013-08-07 05:19:23 +0000196 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000197
Bill Wendling6ba2ed52013-08-08 23:51:04 +0000198 // mark which symbols can not be internalized
199 applyScopeRestrictions();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000200
Chris Lattnerb515d752009-08-23 07:49:08 +0000201 // create output file
202 std::string ErrInfo;
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000203 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
Chris Lattnerb515d752009-08-23 07:49:08 +0000204 if (!ErrInfo.empty()) {
205 errMsg = "could not open bitcode file for writing: ";
206 errMsg += path;
Shuxin Yang235089b2013-08-07 05:19:23 +0000207 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000208 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000209
Chris Lattnerb515d752009-08-23 07:49:08 +0000210 // write bitcode to it
Dan Gohmand4c45432010-09-01 14:20:41 +0000211 WriteBitcodeToFile(_linker.getModule(), Out.os());
212 Out.os().close();
Dan Gohman4b7416b2010-05-27 20:19:47 +0000213
Dan Gohmand4c45432010-09-01 14:20:41 +0000214 if (Out.os().has_error()) {
Chris Lattnerb515d752009-08-23 07:49:08 +0000215 errMsg = "could not write bitcode file: ";
216 errMsg += path;
Dan Gohmand4c45432010-09-01 14:20:41 +0000217 Out.os().clear_error();
Shuxin Yang235089b2013-08-07 05:19:23 +0000218 return false;
Chris Lattnerb515d752009-08-23 07:49:08 +0000219 }
Bill Wendling76b13ed2012-03-31 10:50:14 +0000220
Dan Gohmanf2914012010-08-20 16:59:15 +0000221 Out.keep();
Shuxin Yang235089b2013-08-07 05:19:23 +0000222 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000223}
224
Shuxin Yang67d135a2013-08-12 18:29:43 +0000225// This function is to ensure cl::ParseCommandLineOptions() is called no more
226// than once. It would otherwise complain and exit the compilation prematurely.
227//
228void LTOCodeGenerator::parseOptions() {
229 if (OptionsParsed)
230 return;
231
232 if (!_codegenOptions.empty())
233 cl::ParseCommandLineOptions(_codegenOptions.size(),
234 const_cast<char **>(&_codegenOptions[0]));
235
236 OptionsParsed = true;
237}
238
239// Do some prepartion right before compilation starts.
240bool LTOCodeGenerator::prepareBeforeCompile(std::string &ErrMsg) {
241 parseOptions();
242
243 if (!determineTarget(ErrMsg))
Shuxin Yang235089b2013-08-07 05:19:23 +0000244 return false;
Rafael Espindola6421a882011-03-22 20:57:13 +0000245
Shuxin Yang67d135a2013-08-12 18:29:43 +0000246 FileMgr.setWorkDir(TmpWorkDir.c_str());
247 FileMgr.setKeepWorkDir(KeepWorkDir);
248 return FileMgr.createWorkDir(ErrMsg);
249}
Bill Wendlingc94c5622012-03-31 11:15:43 +0000250
Shuxin Yang67d135a2013-08-12 18:29:43 +0000251bool LTOCodeGenerator::compile_to_file(const char** Name, std::string& ErrMsg) {
252 if (!prepareBeforeCompile(ErrMsg))
Shuxin Yang235089b2013-08-07 05:19:23 +0000253 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000254
Shuxin Yang67d135a2013-08-12 18:29:43 +0000255 performIPO(EnablePartition, ErrMsg);
256 if (!performPostIPO(ErrMsg))
Shuxin Yang235089b2013-08-07 05:19:23 +0000257 return false;
Rafael Espindola6421a882011-03-22 20:57:13 +0000258
Shuxin Yang67d135a2013-08-12 18:29:43 +0000259 *Name = PartitionMgr.getSinglePartition()->getObjFilePath().c_str();
Shuxin Yang235089b2013-08-07 05:19:23 +0000260 return true;
Rafael Espindola6421a882011-03-22 20:57:13 +0000261}
262
Bill Wendlingc94c5622012-03-31 11:15:43 +0000263const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
Rafael Espindola6421a882011-03-22 20:57:13 +0000264 const char *name;
Shuxin Yang235089b2013-08-07 05:19:23 +0000265 if (!compile_to_file(&name, errMsg))
Rafael Espindola6421a882011-03-22 20:57:13 +0000266 return NULL;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000267
Rafael Espindola6421a882011-03-22 20:57:13 +0000268 // remove old buffer if compile() called twice
269 delete _nativeObjectFile;
Nick Kledzikef194ed2008-02-27 22:25:36 +0000270
Rafael Espindola6421a882011-03-22 20:57:13 +0000271 // read .o file into memory buffer
272 OwningPtr<MemoryBuffer> BuffPtr;
Shuxin Yang67d135a2013-08-12 18:29:43 +0000273 const char *BufStart = 0;
274
Rafael Espindola6421a882011-03-22 20:57:13 +0000275 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
276 errMsg = ec.message();
Shuxin Yang67d135a2013-08-12 18:29:43 +0000277 _nativeObjectFile = 0;
278 } else {
279 if ((_nativeObjectFile = BuffPtr.take())) {
280 *length = _nativeObjectFile->getBufferSize();
281 BufStart = _nativeObjectFile->getBufferStart();
282 }
Rafael Espindola6421a882011-03-22 20:57:13 +0000283 }
Rafael Espindolae9efea12011-02-24 21:04:06 +0000284
Shuxin Yang67d135a2013-08-12 18:29:43 +0000285 // Now that the resulting single object file is handed to linker via memory
286 // buffer, it is safe to remove all intermediate files now.
287 //
288 FileMgr.removeAllUnneededFiles();
Rafael Espindolae9efea12011-02-24 21:04:06 +0000289
Shuxin Yang67d135a2013-08-12 18:29:43 +0000290 return BufStart;
291}
292
293const char *LTOCodeGenerator::getFilesNeedToRemove() {
294 IPOFileMgr::FileNameVect ToRm;
295 FileMgr.getFilesNeedToRemove(ToRm);
296
297 ConcatStrings.clear();
298 for (IPOFileMgr::FileNameVect::iterator I = ToRm.begin(), E = ToRm.end();
299 I != E; I++) {
300 StringRef S(*I);
301 ConcatStrings.append(S.begin(), S.end());
302 ConcatStrings.push_back('\0');
303 }
304 ConcatStrings.push_back('\0');
305 ConcatStrings.push_back('\0');
306
307 return ConcatStrings.data();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000308}
309
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000310bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
Bill Wendling0ca36af2012-08-08 22:03:50 +0000311 if (_target != NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000312 return true;
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000313
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000314 // if options were requested, set them
Shuxin Yang67d135a2013-08-12 18:29:43 +0000315 parseOptions();
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000316
Bob Wilson47ed8a12012-10-12 17:39:25 +0000317 std::string TripleStr = _linker.getModule()->getTargetTriple();
318 if (TripleStr.empty())
319 TripleStr = sys::getDefaultTargetTriple();
320 llvm::Triple Triple(TripleStr);
Bill Wendling604a8182008-06-18 06:35:30 +0000321
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000322 // create target machine from info for merged modules
Bob Wilson47ed8a12012-10-12 17:39:25 +0000323 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
Bill Wendling0ca36af2012-08-08 22:03:50 +0000324 if (march == NULL)
Shuxin Yang08809392013-08-06 21:51:21 +0000325 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000326
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000327 // The relocation model is actually a static member of TargetMachine and
328 // needs to be set before the TargetMachine is instantiated.
329 Reloc::Model RelocModel = Reloc::Default;
Bill Wendling0ca36af2012-08-08 22:03:50 +0000330 switch (_codeModel) {
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000331 case LTO_CODEGEN_PIC_MODEL_STATIC:
332 RelocModel = Reloc::Static;
333 break;
334 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
335 RelocModel = Reloc::PIC_;
336 break;
337 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
338 RelocModel = Reloc::DynamicNoPIC;
339 break;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000340 }
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000341
342 // construct LTOModule, hand over ownership of module and target
343 SubtargetFeatures Features;
Bob Wilson47ed8a12012-10-12 17:39:25 +0000344 Features.getDefaultSubtargetFeatures(Triple);
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000345 std::string FeatureStr = Features.getString();
Bob Wilson47ed8a12012-10-12 17:39:25 +0000346 // Set a default CPU for Darwin triples.
347 if (_mCpu.empty() && Triple.isOSDarwin()) {
348 if (Triple.getArch() == llvm::Triple::x86_64)
349 _mCpu = "core2";
350 else if (Triple.getArch() == llvm::Triple::x86)
351 _mCpu = "yonah";
352 }
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000353 TargetOptions Options;
354 LTOModule::getTargetOptions(Options);
Bob Wilson47ed8a12012-10-12 17:39:25 +0000355 _target = march->createTargetMachine(TripleStr, _mCpu, FeatureStr, Options,
Bill Wendlingeda3fc62012-08-06 22:52:45 +0000356 RelocModel, CodeModel::Default,
357 CodeGenOpt::Aggressive);
Shuxin Yang08809392013-08-06 21:51:21 +0000358 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000359}
360
Bill Wendlingc94c5622012-03-31 11:15:43 +0000361void LTOCodeGenerator::
362applyRestriction(GlobalValue &GV,
363 std::vector<const char*> &mustPreserveList,
364 SmallPtrSet<GlobalValue*, 8> &asmUsed,
365 Mangler &mangler) {
Rafael Espindola38c4e532011-03-02 04:14:42 +0000366 SmallString<64> Buffer;
367 mangler.getNameWithPrefix(Buffer, &GV, false);
368
369 if (GV.isDeclaration())
370 return;
371 if (_mustPreserveSymbols.count(Buffer))
372 mustPreserveList.push_back(GV.getName().data());
373 if (_asmUndefinedRefs.count(Buffer))
374 asmUsed.insert(&GV);
375}
376
377static void findUsedValues(GlobalVariable *LLVMUsed,
378 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
379 if (LLVMUsed == 0) return;
380
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000381 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
Rafael Espindola38c4e532011-03-02 04:14:42 +0000382 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
Bill Wendling76b13ed2012-03-31 10:50:14 +0000383 if (GlobalValue *GV =
Bill Wendlingc94c5622012-03-31 11:15:43 +0000384 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
Rafael Espindola38c4e532011-03-02 04:14:42 +0000385 UsedValues.insert(GV);
386}
387
Chris Lattner5ef31a02010-03-12 18:44:54 +0000388void LTOCodeGenerator::applyScopeRestrictions() {
389 if (_scopeRestrictionsDone) return;
390 Module *mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000391
Chris Lattner5ef31a02010-03-12 18:44:54 +0000392 // Start off with a verification pass.
393 PassManager passes;
394 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000395
Bill Wendling76b13ed2012-03-31 10:50:14 +0000396 // mark which symbols can not be internalized
Bill Wendling99cb6222013-06-18 07:20:20 +0000397 MCContext Context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL);
Bill Wendlingcc5a8822013-05-29 20:37:19 +0000398 Mangler mangler(Context, _target);
Rafael Espindola38c4e532011-03-02 04:14:42 +0000399 std::vector<const char*> mustPreserveList;
400 SmallPtrSet<GlobalValue*, 8> asmUsed;
401
402 for (Module::iterator f = mergedModule->begin(),
403 e = mergedModule->end(); f != e; ++f)
404 applyRestriction(*f, mustPreserveList, asmUsed, mangler);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000405 for (Module::global_iterator v = mergedModule->global_begin(),
Rafael Espindola38c4e532011-03-02 04:14:42 +0000406 e = mergedModule->global_end(); v != e; ++v)
407 applyRestriction(*v, mustPreserveList, asmUsed, mangler);
408 for (Module::alias_iterator a = mergedModule->alias_begin(),
409 e = mergedModule->alias_end(); a != e; ++a)
410 applyRestriction(*a, mustPreserveList, asmUsed, mangler);
411
412 GlobalVariable *LLVMCompilerUsed =
413 mergedModule->getGlobalVariable("llvm.compiler.used");
414 findUsedValues(LLVMCompilerUsed, asmUsed);
415 if (LLVMCompilerUsed)
416 LLVMCompilerUsed->eraseFromParent();
417
Rafael Espindolad4ee3922013-04-24 17:54:35 +0000418 if (!asmUsed.empty()) {
419 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
420 std::vector<Constant*> asmUsed2;
421 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
422 e = asmUsed.end(); i !=e; ++i) {
423 GlobalValue *GV = *i;
424 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
425 asmUsed2.push_back(c);
426 }
427
428 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
429 LLVMCompilerUsed =
430 new llvm::GlobalVariable(*mergedModule, ATy, false,
431 llvm::GlobalValue::AppendingLinkage,
432 llvm::ConstantArray::get(ATy, asmUsed2),
433 "llvm.compiler.used");
434
435 LLVMCompilerUsed->setSection("llvm.metadata");
Chris Lattner5ef31a02010-03-12 18:44:54 +0000436 }
Rafael Espindola38c4e532011-03-02 04:14:42 +0000437
Bill Wendling50f31832012-12-10 21:33:45 +0000438 passes.add(createInternalizePass(mustPreserveList));
Rafael Espindola38c4e532011-03-02 04:14:42 +0000439
Chris Lattner5ef31a02010-03-12 18:44:54 +0000440 // apply scope restrictions
441 passes.run(*mergedModule);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000442
Chris Lattner5ef31a02010-03-12 18:44:54 +0000443 _scopeRestrictionsDone = true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000444}
445
Shuxin Yang67d135a2013-08-12 18:29:43 +0000446void LTOCodeGenerator::performIPO(bool ToPartition, std::string &errMsg) {
447 // Mark which symbols can not be internalized
448 applyScopeRestrictions();
449
450 // Instantiate the pass manager to organize the passes.
451 PassManager Passes;
452
453 // Start off with a verification pass.
454 Passes.add(createVerifierPass());
455
456 // Add an appropriate DataLayout instance for this module...
457 Passes.add(new DataLayout(*_target->getDataLayout()));
458 _target->addAnalysisPasses(Passes);
459
460 // Enabling internalize here would use its AllButMain variant. It
461 // keeps only main if it exists and does nothing for libraries. Instead
462 // we create the pass ourselves with the symbol list provided by the linker.
463 if (!DisableOpt)
464 PassManagerBuilder().populateLTOPassManager(Passes,
465 /*Internalize=*/false,
466 !DisableInline,
467 DisableGVNLoadPRE);
468 // Make sure everything is still good.
469 Passes.add(createVerifierPass());
470
471 Module* M = _linker.getModule();
472 if (ToPartition)
473 assert(false && "TBD");
474 else {
475 Passes.run(*M);
476
477 // Create a partition for the merged module.
478 PartitionMgr.createIPOPart(M);
479 }
480}
481
482// Perform Post-IPO compilation. If the partition is enabled, there may
483// be multiple partitions, and therefore there may be multiple objects.
484// In this case, "MergeObjs" indicates to merge all object together (via ld -r)
485// and return the path to the merged object via "MergObjPath".
486//
487bool LTOCodeGenerator::performPostIPO(std::string &ErrMsg,
488 bool MergeObjs,
489 const char **MergObjPath) {
490 // Determine the variant of post-ipo driver
491 PostIPODriver::VariantTy DrvTy;
492 if (!EnablePartition) {
493 assert(!MergeObjs && !MergObjPath && "Invalid parameter");
494 DrvTy = PostIPODriver::PIDV_SERIAL;
495 } else {
496 DrvTy = PostIPODriver::PIDV_Invalid;
497 assert(false && "TBD");
498 }
499
500 PostIPODriver D(DrvTy, _target, PartitionMgr, FileMgr, MergeObjs);
501 if (D.Compile(ErrMsg)) {
502 if (MergeObjs)
503 *MergObjPath = D.getSingleObjFile()->getPath().c_str();
504 return true;
505 }
506
507 return false;
508}
509
Nick Kledzik77595fc2008-02-26 20:26:43 +0000510/// Optimize merged modules using various IPO passes
Chris Lattner817a01f2011-05-22 00:20:07 +0000511bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
512 std::string &errMsg) {
Shuxin Yang08809392013-08-06 21:51:21 +0000513 if (!this->determineTarget(errMsg))
514 return false;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000515
Bill Wendlingc94c5622012-03-31 11:15:43 +0000516 Module* mergedModule = _linker.getModule();
Nick Kledzik77595fc2008-02-26 20:26:43 +0000517
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000518 // Mark which symbols can not be internalized
Bill Wendling64d5b282012-04-09 22:18:01 +0000519 this->applyScopeRestrictions();
520
Bill Wendlingc94c5622012-03-31 11:15:43 +0000521 // Instantiate the pass manager to organize the passes.
522 PassManager passes;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000523
Bill Wendlingc94c5622012-03-31 11:15:43 +0000524 // Start off with a verification pass.
525 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000526
Micah Villmow791cfc22012-10-08 16:39:34 +0000527 // Add an appropriate DataLayout instance for this module...
528 passes.add(new DataLayout(*_target->getDataLayout()));
Chandler Carruthaeef83c2013-01-07 01:37:14 +0000529 _target->addAnalysisPasses(passes);
Bill Wendling76b13ed2012-03-31 10:50:14 +0000530
Rafael Espindola4d2e9d92012-04-16 10:58:38 +0000531 // Enabling internalize here would use its AllButMain variant. It
532 // keeps only main if it exists and does nothing for libraries. Instead
533 // we create the pass ourselves with the symbol list provided by the linker.
Bill Wendling8c18a6f2013-05-23 21:21:50 +0000534 if (!DisableOpt)
Bill Wendling6303b662013-02-28 14:11:10 +0000535 PassManagerBuilder().populateLTOPassManager(passes,
Bill Wendling50f31832012-12-10 21:33:45 +0000536 /*Internalize=*/false,
Bill Wendling3197b442012-04-02 22:16:50 +0000537 !DisableInline,
538 DisableGVNLoadPRE);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000539
Bill Wendlingc94c5622012-03-31 11:15:43 +0000540 // Make sure everything is still good.
541 passes.add(createVerifierPass());
Nick Kledzik77595fc2008-02-26 20:26:43 +0000542
Lang Hamesa991b252013-03-13 21:18:46 +0000543 PassManager codeGenPasses;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000544
Lang Hamesa991b252013-03-13 21:18:46 +0000545 codeGenPasses.add(new DataLayout(*_target->getDataLayout()));
546 _target->addAnalysisPasses(codeGenPasses);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000547
Bill Wendlingc94c5622012-03-31 11:15:43 +0000548 formatted_raw_ostream Out(out);
Dan Gohmand4c45432010-09-01 14:20:41 +0000549
Bob Wilsond6965442013-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
Lang Hamesa991b252013-03-13 21:18:46 +0000554 if (_target->addPassesToEmitFile(codeGenPasses, Out,
David Blaikie4f56a302012-05-30 18:42:51 +0000555 TargetMachine::CGFT_ObjectFile)) {
Bill Wendlingc94c5622012-03-31 11:15:43 +0000556 errMsg = "target file type not supported";
Shuxin Yang08809392013-08-06 21:51:21 +0000557 return false;
Bill Wendlingc94c5622012-03-31 11:15:43 +0000558 }
Nick Kledzik77595fc2008-02-26 20:26:43 +0000559
Bill Wendlingc94c5622012-03-31 11:15:43 +0000560 // Run our queue of passes all at once now, efficiently.
561 passes.run(*mergedModule);
Nick Kledzik77595fc2008-02-26 20:26:43 +0000562
Bill Wendlingc94c5622012-03-31 11:15:43 +0000563 // Run the code generator, and write assembly file
Lang Hamesa991b252013-03-13 21:18:46 +0000564 codeGenPasses.run(*mergedModule);
Nick Lewyckyd42b58b2009-07-26 22:16:39 +0000565
Shuxin Yang08809392013-08-06 21:51:21 +0000566 return true;
Nick Kledzik77595fc2008-02-26 20:26:43 +0000567}
568
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000569/// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
570/// LTO problems.
571void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
572 for (std::pair<StringRef, StringRef> o = getToken(options);
573 !o.first.empty(); o = getToken(o.second)) {
574 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
575 // that.
Bill Wendling0ca36af2012-08-08 22:03:50 +0000576 if (_codegenOptions.empty())
Bill Wendlingcaf71d42012-03-31 10:49:43 +0000577 _codegenOptions.push_back(strdup("libLTO"));
578 _codegenOptions.push_back(strdup(o.first.str().c_str()));
579 }
Nick Kledzik920ae982008-07-08 21:14:10 +0000580}