llvm.org GIT mirror llvm / cc48854
Move LTO support library to a component, allowing it to be tested more reliably across platforms. Patch by Tom Roeder! git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@191343 91177308-0d34-0410-b5e6-96231b3b80d8 Peter Collingbourne 7 years ago
26 changed file(s) with 1828 addition(s) and 1751 deletion(s). Raw diff Collapse all Expand all
0 //===-LTOCodeGenerator.h - LLVM Link Time Optimizer -----------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the LTOCodeGenerator class.
10 //
11 // LTO compilation consists of three phases: Pre-IPO, IPO and Post-IPO.
12 //
13 // The Pre-IPO phase compiles source code into bitcode file. The resulting
14 // bitcode files, along with object files and libraries, will be fed to the
15 // linker to through the IPO and Post-IPO phases. By using obj-file extension,
16 // the resulting bitcode file disguises itself as an object file, and therefore
17 // obviates the need of writing a special set of the make-rules only for LTO
18 // compilation.
19 //
20 // The IPO phase perform inter-procedural analyses and optimizations, and
21 // the Post-IPO consists two sub-phases: intra-procedural scalar optimizations
22 // (SOPT), and intra-procedural target-dependent code generator (CG).
23 //
24 // As of this writing, we don't separate IPO and the Post-IPO SOPT. They
25 // are intermingled together, and are driven by a single pass manager (see
26 // PassManagerBuilder::populateLTOPassManager()).
27 //
28 // The "LTOCodeGenerator" is the driver for the IPO and Post-IPO stages.
29 // The "CodeGenerator" here is bit confusing. Don't confuse the "CodeGenerator"
30 // with the machine specific code generator.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #ifndef LTO_CODE_GENERATOR_H
35 #define LTO_CODE_GENERATOR_H
36
37 #include "llvm-c/lto.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/StringMap.h"
40 #include "llvm/Linker.h"
41 #include
42 #include
43
44 namespace llvm {
45 class LLVMContext;
46 class GlobalValue;
47 class Mangler;
48 class MemoryBuffer;
49 class TargetMachine;
50 class raw_ostream;
51 }
52
53 //===----------------------------------------------------------------------===//
54 /// LTOCodeGenerator - C++ class which implements the opaque lto_code_gen_t
55 /// type.
56 ///
57 struct LTOCodeGenerator {
58 static const char *getVersionString();
59
60 LTOCodeGenerator();
61 ~LTOCodeGenerator();
62
63 // Merge given module, return true on success.
64 bool addModule(struct LTOModule*, std::string &errMsg);
65
66 void setDebugInfo(lto_debug_model);
67 void setCodePICModel(lto_codegen_model);
68
69 void setCpu(const char *mCpu) { MCpu = mCpu; }
70
71 void addMustPreserveSymbol(const char *sym) { MustPreserveSymbols[sym] = 1; }
72
73 // To pass options to the driver and optimization passes. These options are
74 // not necessarily for debugging purpose (The function name is misleading).
75 // This function should be called before LTOCodeGenerator::compilexxx(),
76 // and LTOCodeGenerator::writeMergedModules().
77 //
78 void setCodeGenDebugOptions(const char *opts);
79
80 // Write the merged module to the file specified by the given path.
81 // Return true on success.
82 bool writeMergedModules(const char *path, std::string &errMsg);
83
84 // Compile the merged module into a *single* object file; the path to object
85 // file is returned to the caller via argument "name". Return true on
86 // success.
87 //
88 // NOTE that it is up to the linker to remove the intermediate object file.
89 // Do not try to remove the object file in LTOCodeGenerator's destructor
90 // as we don't who (LTOCodeGenerator or the obj file) will last longer.
91 //
92 bool compile_to_file(const char **name, std::string &errMsg);
93
94 // As with compile_to_file(), this function compiles the merged module into
95 // single object file. Instead of returning the object-file-path to the caller
96 // (linker), it brings the object to a buffer, and return the buffer to the
97 // caller. This function should delete intermediate object file once its content
98 // is brought to memory. Return NULL if the compilation was not successful.
99 //
100 const void *compile(size_t *length, std::string &errMsg);
101
102 private:
103 void initializeLTOPasses();
104
105 bool generateObjectFile(llvm::raw_ostream &out, std::string &errMsg);
106 void applyScopeRestrictions();
107 void applyRestriction(llvm::GlobalValue &GV,
108 std::vector &MustPreserveList,
109 llvm::SmallPtrSet &AsmUsed,
110 llvm::Mangler &Mangler);
111 bool determineTarget(std::string &errMsg);
112
113 typedef llvm::StringMap StringSet;
114
115 llvm::LLVMContext &Context;
116 llvm::Linker Linker;
117 llvm::TargetMachine *TargetMach;
118 bool EmitDwarfDebugInfo;
119 bool ScopeRestrictionsDone;
120 lto_codegen_model CodeModel;
121 StringSet MustPreserveSymbols;
122 StringSet AsmUndefinedRefs;
123 llvm::MemoryBuffer *NativeObjectFile;
124 std::vector CodegenOptions;
125 std::string MCpu;
126 std::string NativeObjectPath;
127 };
128
129 #endif // LTO_CODE_GENERATOR_H
0 //===-LTOModule.h - LLVM Link Time Optimizer ------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the LTOModule class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LTO_MODULE_H
14 #define LTO_MODULE_H
15
16 #include "llvm-c/lto.h"
17 #include "llvm/ADT/OwningPtr.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/Target/Mangler.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include
24 #include
25
26 // Forward references to llvm classes.
27 namespace llvm {
28 class Function;
29 class GlobalValue;
30 class MemoryBuffer;
31 class TargetOptions;
32 class Value;
33 }
34
35 //===----------------------------------------------------------------------===//
36 /// LTOModule - C++ class which implements the opaque lto_module_t type.
37 ///
38 struct LTOModule {
39 private:
40 typedef llvm::StringMap StringSet;
41
42 struct NameAndAttributes {
43 const char *name;
44 uint32_t attributes;
45 bool isFunction;
46 const llvm::GlobalValue *symbol;
47 };
48
49 llvm::OwningPtr _module;
50 llvm::OwningPtr _target;
51 std::vector _symbols;
52
53 // _defines and _undefines only needed to disambiguate tentative definitions
54 StringSet _defines;
55 llvm::StringMap _undefines;
56 std::vector _asm_undefines;
57 llvm::MCContext _context;
58
59 // Use mangler to add GlobalPrefix to names to match linker names.
60 llvm::Mangler _mangler;
61
62 LTOModule(llvm::Module *m, llvm::TargetMachine *t);
63 public:
64 /// isBitcodeFile - Returns 'true' if the file or memory contents is LLVM
65 /// bitcode.
66 static bool isBitcodeFile(const void *mem, size_t length);
67 static bool isBitcodeFile(const char *path);
68
69 /// isBitcodeFileForTarget - Returns 'true' if the file or memory contents
70 /// is LLVM bitcode for the specified triple.
71 static bool isBitcodeFileForTarget(const void *mem,
72 size_t length,
73 const char *triplePrefix);
74 static bool isBitcodeFileForTarget(const char *path,
75 const char *triplePrefix);
76
77 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership
78 /// of the buffer. The caller must have initialized the Targets, the
79 /// TargetMCs, the AsmPrinters, and the AsmParsers by calling:
80 ///
81 /// InitializeAllTargets();
82 /// InitializeAllTargetMCs();
83 /// InitializeAllAsmPrinters();
84 /// InitializeAllAsmParsers();
85 static LTOModule *makeLTOModule(const char* path,
86 std::string &errMsg);
87 static LTOModule *makeLTOModule(int fd, const char *path,
88 size_t size, std::string &errMsg);
89 static LTOModule *makeLTOModule(int fd, const char *path,
90 size_t map_size,
91 off_t offset,
92 std::string& errMsg);
93 static LTOModule *makeLTOModule(const void *mem, size_t length,
94 std::string &errMsg);
95
96 /// getTargetTriple - Return the Module's target triple.
97 const char *getTargetTriple() {
98 return _module->getTargetTriple().c_str();
99 }
100
101 /// setTargetTriple - Set the Module's target triple.
102 void setTargetTriple(const char *triple) {
103 _module->setTargetTriple(triple);
104 }
105
106 /// getSymbolCount - Get the number of symbols
107 uint32_t getSymbolCount() {
108 return _symbols.size();
109 }
110
111 /// getSymbolAttributes - Get the attributes for a symbol at the specified
112 /// index.
113 lto_symbol_attributes getSymbolAttributes(uint32_t index) {
114 if (index < _symbols.size())
115 return lto_symbol_attributes(_symbols[index].attributes);
116 return lto_symbol_attributes(0);
117 }
118
119 /// getSymbolName - Get the name of the symbol at the specified index.
120 const char *getSymbolName(uint32_t index) {
121 if (index < _symbols.size())
122 return _symbols[index].name;
123 return NULL;
124 }
125
126 /// getLLVVMModule - Return the Module.
127 llvm::Module *getLLVVMModule() { return _module.get(); }
128
129 /// getAsmUndefinedRefs -
130 const std::vector &getAsmUndefinedRefs() {
131 return _asm_undefines;
132 }
133
134 /// getTargetOptions - Fill the TargetOptions object with the options
135 /// specified on the command line.
136 static void getTargetOptions(llvm::TargetOptions &Options);
137
138 private:
139 /// parseSymbols - Parse the symbols from the module and model-level ASM and
140 /// add them to either the defined or undefined lists.
141 bool parseSymbols(std::string &errMsg);
142
143 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet
144 /// to a list to be resolved later.
145 void addPotentialUndefinedSymbol(const llvm::GlobalValue *dcl, bool isFunc);
146
147 /// addDefinedSymbol - Add a defined symbol to the list.
148 void addDefinedSymbol(const llvm::GlobalValue *def, bool isFunction);
149
150 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
151 void addDefinedFunctionSymbol(const llvm::Function *f);
152
153 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
154 void addDefinedDataSymbol(const llvm::GlobalValue *v);
155
156 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
157 /// defined or undefined lists.
158 bool addAsmGlobalSymbols(std::string &errMsg);
159
160 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
161 /// defined list.
162 void addAsmGlobalSymbol(const char *, lto_symbol_attributes scope);
163
164 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to
165 /// the undefined list.
166 void addAsmGlobalSymbolUndef(const char *);
167
168 /// addObjCClass - Parse i386/ppc ObjC class data structure.
169 void addObjCClass(const llvm::GlobalVariable *clgv);
170
171 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
172 void addObjCCategory(const llvm::GlobalVariable *clgv);
173
174 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
175 void addObjCClassRef(const llvm::GlobalVariable *clgv);
176
177 /// objcClassNameFromExpression - Get string that the data pointer points
178 /// to.
179 bool objcClassNameFromExpression(const llvm::Constant* c, std::string &name);
180
181 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
182 /// target triple.
183 static bool isTargetMatch(llvm::MemoryBuffer *memBuffer,
184 const char *triplePrefix);
185
186 /// makeLTOModule - Create an LTOModule (private version). N.B. This
187 /// method takes ownership of the buffer.
188 static LTOModule *makeLTOModule(llvm::MemoryBuffer *buffer,
189 std::string &errMsg);
190
191 /// makeBuffer - Create a MemoryBuffer from a memory range.
192 static llvm::MemoryBuffer *makeBuffer(const void *mem, size_t length);
193 };
194
195 #endif // LTO_MODULE_H
66 add_subdirectory(Transforms)
77 add_subdirectory(Linker)
88 add_subdirectory(Analysis)
9 add_subdirectory(LTO)
910 add_subdirectory(MC)
1011 add_subdirectory(Object)
1112 add_subdirectory(Option)
1515 ;===------------------------------------------------------------------------===;
1616
1717 [common]
18 subdirectories = Analysis AsmParser Bitcode CodeGen DebugInfo ExecutionEngine Linker IR IRReader MC Object Option Support TableGen Target Transforms
18 subdirectories = Analysis AsmParser Bitcode CodeGen DebugInfo ExecutionEngine Linker IR IRReader LTO MC Object Option Support TableGen Target Transforms
1919
2020 [component_0]
2121 type = Group
0 add_llvm_library(LLVMLTO
1 LTOModule.cpp
2 LTOCodeGenerator.cpp
3 )
0 ;===- ./lib/LTO/LLVMBuild.txt ----------------------------------*- Conf -*--===;
1 ;
2 ; The LLVM Compiler Infrastructure
3 ;
4 ; This file is distributed under the University of Illinois Open Source
5 ; License. See LICENSE.TXT for details.
6 ;
7 ;===------------------------------------------------------------------------===;
8 ;
9 ; This is an LLVMBuild description file for the components in this subdirectory.
10 ;
11 ; For more information on the LLVMBuild system, please see:
12 ;
13 ; http://llvm.org/docs/LLVMBuild.html
14 ;
15 ;===------------------------------------------------------------------------===;
16
17 [component_0]
18 type = Library
19 name = LTO
20 parent = Libraries
21 required_libraries = Analysis BitReader BitWriter Core IPO Linker MC MCParser Scalar Support Target Vectorize
0 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/LTO/LTOCodeGenerator.h"
15 #include "llvm/LTO/LTOModule.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Linker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/system_error.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/Mangler.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
46 #include "llvm/Transforms/ObjCARC.h"
47 using namespace llvm;
48
49 static cl::opt
50 DisableOpt("disable-opt", cl::init(false),
51 cl::desc("Do not run any optimization passes"));
52
53 static cl::opt
54 DisableInline("disable-inlining", cl::init(false),
55 cl::desc("Do not run the inliner pass"));
56
57 static cl::opt
58 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
59 cl::desc("Do not run the GVN load PRE pass"));
60
61 const char* LTOCodeGenerator::getVersionString() {
62 #ifdef LLVM_VERSION_INFO
63 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
64 #else
65 return PACKAGE_NAME " version " PACKAGE_VERSION;
66 #endif
67 }
68
69 LTOCodeGenerator::LTOCodeGenerator()
70 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
71 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
72 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
73 initializeLTOPasses();
74 }
75
76 LTOCodeGenerator::~LTOCodeGenerator() {
77 delete TargetMach;
78 delete NativeObjectFile;
79 delete Linker.getModule();
80
81 for (std::vector::iterator I = CodegenOptions.begin(),
82 E = CodegenOptions.end();
83 I != E; ++I)
84 free(*I);
85 }
86
87 // Initialize LTO passes. Please keep this funciton in sync with
88 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
89 // passes are initialized.
90 //
91 void LTOCodeGenerator::initializeLTOPasses() {
92 PassRegistry &R = *PassRegistry::getPassRegistry();
93
94 initializeInternalizePassPass(R);
95 initializeIPSCCPPass(R);
96 initializeGlobalOptPass(R);
97 initializeConstantMergePass(R);
98 initializeDAHPass(R);
99 initializeInstCombinerPass(R);
100 initializeSimpleInlinerPass(R);
101 initializePruneEHPass(R);
102 initializeGlobalDCEPass(R);
103 initializeArgPromotionPass(R);
104 initializeJumpThreadingPass(R);
105 initializeSROAPass(R);
106 initializeSROA_DTPass(R);
107 initializeSROA_SSAUpPass(R);
108 initializeFunctionAttrsPass(R);
109 initializeGlobalsModRefPass(R);
110 initializeLICMPass(R);
111 initializeGVNPass(R);
112 initializeMemCpyOptPass(R);
113 initializeDCEPass(R);
114 initializeCFGSimplifyPassPass(R);
115 }
116
117 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
118 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
119
120 const std::vector &undefs = mod->getAsmUndefinedRefs();
121 for (int i = 0, e = undefs.size(); i != e; ++i)
122 AsmUndefinedRefs[undefs[i]] = 1;
123
124 return !ret;
125 }
126
127 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
128 switch (debug) {
129 case LTO_DEBUG_MODEL_NONE:
130 EmitDwarfDebugInfo = false;
131 return;
132
133 case LTO_DEBUG_MODEL_DWARF:
134 EmitDwarfDebugInfo = true;
135 return;
136 }
137 llvm_unreachable("Unknown debug format!");
138 }
139
140 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
141 switch (model) {
142 case LTO_CODEGEN_PIC_MODEL_STATIC:
143 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
144 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
145 CodeModel = model;
146 return;
147 }
148 llvm_unreachable("Unknown PIC model!");
149 }
150
151 bool LTOCodeGenerator::writeMergedModules(const char *path,
152 std::string &errMsg) {
153 if (!determineTarget(errMsg))
154 return false;
155
156 // mark which symbols can not be internalized
157 applyScopeRestrictions();
158
159 // create output file
160 std::string ErrInfo;
161 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
162 if (!ErrInfo.empty()) {
163 errMsg = "could not open bitcode file for writing: ";
164 errMsg += path;
165 return false;
166 }
167
168 // write bitcode to it
169 WriteBitcodeToFile(Linker.getModule(), Out.os());
170 Out.os().close();
171
172 if (Out.os().has_error()) {
173 errMsg = "could not write bitcode file: ";
174 errMsg += path;
175 Out.os().clear_error();
176 return false;
177 }
178
179 Out.keep();
180 return true;
181 }
182
183 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
184 // make unique temp .o file to put generated object file
185 SmallString<128> Filename;
186 int FD;
187 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
188 if (EC) {
189 errMsg = EC.message();
190 return false;
191 }
192
193 // generate object file
194 tool_output_file objFile(Filename.c_str(), FD);
195
196 bool genResult = generateObjectFile(objFile.os(), errMsg);
197 objFile.os().close();
198 if (objFile.os().has_error()) {
199 objFile.os().clear_error();
200 sys::fs::remove(Twine(Filename));
201 return false;
202 }
203
204 objFile.keep();
205 if (!genResult) {
206 sys::fs::remove(Twine(Filename));
207 return false;
208 }
209
210 NativeObjectPath = Filename.c_str();
211 *name = NativeObjectPath.c_str();
212 return true;
213 }
214
215 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
216 const char *name;
217 if (!compile_to_file(&name, errMsg))
218 return NULL;
219
220 // remove old buffer if compile() called twice
221 delete NativeObjectFile;
222
223 // read .o file into memory buffer
224 OwningPtr BuffPtr;
225 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
226 errMsg = ec.message();
227 sys::fs::remove(NativeObjectPath);
228 return NULL;
229 }
230 NativeObjectFile = BuffPtr.take();
231
232 // remove temp files
233 sys::fs::remove(NativeObjectPath);
234
235 // return buffer, unless error
236 if (NativeObjectFile == NULL)
237 return NULL;
238 *length = NativeObjectFile->getBufferSize();
239 return NativeObjectFile->getBufferStart();
240 }
241
242 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
243 if (TargetMach != NULL)
244 return true;
245
246 // if options were requested, set them
247 if (!CodegenOptions.empty())
248 cl::ParseCommandLineOptions(CodegenOptions.size(),
249 const_cast(&CodegenOptions[0]));
250
251 std::string TripleStr = Linker.getModule()->getTargetTriple();
252 if (TripleStr.empty())
253 TripleStr = sys::getDefaultTargetTriple();
254 llvm::Triple Triple(TripleStr);
255
256 // create target machine from info for merged modules
257 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
258 if (march == NULL)
259 return false;
260
261 // The relocation model is actually a static member of TargetMachine and
262 // needs to be set before the TargetMachine is instantiated.
263 Reloc::Model RelocModel = Reloc::Default;
264 switch (CodeModel) {
265 case LTO_CODEGEN_PIC_MODEL_STATIC:
266 RelocModel = Reloc::Static;
267 break;
268 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
269 RelocModel = Reloc::PIC_;
270 break;
271 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
272 RelocModel = Reloc::DynamicNoPIC;
273 break;
274 }
275
276 // construct LTOModule, hand over ownership of module and target
277 SubtargetFeatures Features;
278 Features.getDefaultSubtargetFeatures(Triple);
279 std::string FeatureStr = Features.getString();
280 // Set a default CPU for Darwin triples.
281 if (MCpu.empty() && Triple.isOSDarwin()) {
282 if (Triple.getArch() == llvm::Triple::x86_64)
283 MCpu = "core2";
284 else if (Triple.getArch() == llvm::Triple::x86)
285 MCpu = "yonah";
286 }
287 TargetOptions Options;
288 LTOModule::getTargetOptions(Options);
289 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
290 RelocModel, CodeModel::Default,
291 CodeGenOpt::Aggressive);
292 return true;
293 }
294
295 void LTOCodeGenerator::
296 applyRestriction(GlobalValue &GV,
297 std::vector &MustPreserveList,
298 SmallPtrSet &AsmUsed,
299 Mangler &Mangler) {
300 SmallString<64> Buffer;
301 Mangler.getNameWithPrefix(Buffer, &GV, false);
302
303 if (GV.isDeclaration())
304 return;
305 if (MustPreserveSymbols.count(Buffer))
306 MustPreserveList.push_back(GV.getName().data());
307 if (AsmUndefinedRefs.count(Buffer))
308 AsmUsed.insert(&GV);
309 }
310
311 static void findUsedValues(GlobalVariable *LLVMUsed,
312 SmallPtrSet &UsedValues) {
313 if (LLVMUsed == 0) return;
314
315 ConstantArray *Inits = cast(LLVMUsed->getInitializer());
316 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
317 if (GlobalValue *GV =
318 dyn_cast(Inits->getOperand(i)->stripPointerCasts()))
319 UsedValues.insert(GV);
320 }
321
322 void LTOCodeGenerator::applyScopeRestrictions() {
323 if (ScopeRestrictionsDone)
324 return;
325 Module *mergedModule = Linker.getModule();
326
327 // Start off with a verification pass.
328 PassManager passes;
329 passes.add(createVerifierPass());
330
331 // mark which symbols can not be internalized
332 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
333 NULL);
334 Mangler Mangler(MContext, TargetMach);
335 std::vector MustPreserveList;
336 SmallPtrSet AsmUsed;
337
338 for (Module::iterator f = mergedModule->begin(),
339 e = mergedModule->end(); f != e; ++f)
340 applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
341 for (Module::global_iterator v = mergedModule->global_begin(),
342 e = mergedModule->global_end(); v != e; ++v)
343 applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
344 for (Module::alias_iterator a = mergedModule->alias_begin(),
345 e = mergedModule->alias_end(); a != e; ++a)
346 applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
347
348 GlobalVariable *LLVMCompilerUsed =
349 mergedModule->getGlobalVariable("llvm.compiler.used");
350 findUsedValues(LLVMCompilerUsed, AsmUsed);
351 if (LLVMCompilerUsed)
352 LLVMCompilerUsed->eraseFromParent();
353
354 if (!AsmUsed.empty()) {
355 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
356 std::vector asmUsed2;
357 for (SmallPtrSet::const_iterator i = AsmUsed.begin(),
358 e = AsmUsed.end(); i !=e; ++i) {
359 GlobalValue *GV = *i;
360 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
361 asmUsed2.push_back(c);
362 }
363
364 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
365 LLVMCompilerUsed =
366 new llvm::GlobalVariable(*mergedModule, ATy, false,
367 llvm::GlobalValue::AppendingLinkage,
368 llvm::ConstantArray::get(ATy, asmUsed2),
369 "llvm.compiler.used");
370
371 LLVMCompilerUsed->setSection("llvm.metadata");
372 }
373
374 passes.add(createInternalizePass(MustPreserveList));
375
376 // apply scope restrictions
377 passes.run(*mergedModule);
378
379 ScopeRestrictionsDone = true;
380 }
381
382 /// Optimize merged modules using various IPO passes
383 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
384 std::string &errMsg) {
385 if (!this->determineTarget(errMsg))
386 return false;
387
388 Module *mergedModule = Linker.getModule();
389
390 // Mark which symbols can not be internalized
391 this->applyScopeRestrictions();
392
393 // Instantiate the pass manager to organize the passes.
394 PassManager passes;
395
396 // Start off with a verification pass.
397 passes.add(createVerifierPass());
398
399 // Add an appropriate DataLayout instance for this module...
400 passes.add(new DataLayout(*TargetMach->getDataLayout()));
401 TargetMach->addAnalysisPasses(passes);
402
403 // Enabling internalize here would use its AllButMain variant. It
404 // keeps only main if it exists and does nothing for libraries. Instead
405 // we create the pass ourselves with the symbol list provided by the linker.
406 if (!DisableOpt)
407 PassManagerBuilder().populateLTOPassManager(passes,
408 /*Internalize=*/false,
409 !DisableInline,
410 DisableGVNLoadPRE);
411
412 // Make sure everything is still good.
413 passes.add(createVerifierPass());
414
415 PassManager codeGenPasses;
416
417 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
418 TargetMach->addAnalysisPasses(codeGenPasses);
419
420 formatted_raw_ostream Out(out);
421
422 // If the bitcode files contain ARC code and were compiled with optimization,
423 // the ObjCARCContractPass must be run, so do it unconditionally here.
424 codeGenPasses.add(createObjCARCContractPass());
425
426 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
427 TargetMachine::CGFT_ObjectFile)) {
428 errMsg = "target file type not supported";
429 return false;
430 }
431
432 // Run our queue of passes all at once now, efficiently.
433 passes.run(*mergedModule);
434
435 // Run the code generator, and write assembly file
436 codeGenPasses.run(*mergedModule);
437
438 return true;
439 }
440
441 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
442 /// LTO problems.
443 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
444 for (std::pair o = getToken(options);
445 !o.first.empty(); o = getToken(o.second)) {
446 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
447 // that.
448 if (CodegenOptions.empty())
449 CodegenOptions.push_back(strdup("libLLVMLTO"));
450 CodegenOptions.push_back(strdup(o.first.str().c_str()));
451 }
452 }
0 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/LTO/LTOModule.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 using namespace llvm;
41
42 static cl::opt
43 EnableFPMAD("enable-fp-mad",
44 cl::desc("Enable less precise MAD instructions to be generated"),
45 cl::init(false));
46
47 static cl::opt
48 DisableFPElim("disable-fp-elim",
49 cl::desc("Disable frame pointer elimination optimization"),
50 cl::init(false));
51
52 static cl::opt
53 EnableUnsafeFPMath("enable-unsafe-fp-math",
54 cl::desc("Enable optimizations that may decrease FP precision"),
55 cl::init(false));
56
57 static cl::opt
58 EnableNoInfsFPMath("enable-no-infs-fp-math",
59 cl::desc("Enable FP math optimizations that assume no +-Infs"),
60 cl::init(false));
61
62 static cl::opt
63 EnableNoNaNsFPMath("enable-no-nans-fp-math",
64 cl::desc("Enable FP math optimizations that assume no NaNs"),
65 cl::init(false));
66
67 static cl::opt
68 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
69 cl::Hidden,
70 cl::desc("Force codegen to assume rounding mode can change dynamically"),
71 cl::init(false));
72
73 static cl::opt
74 GenerateSoftFloatCalls("soft-float",
75 cl::desc("Generate software floating point library calls"),
76 cl::init(false));
77
78 static cl::opt
79 FloatABIForCalls("float-abi",
80 cl::desc("Choose float ABI type"),
81 cl::init(FloatABI::Default),
82 cl::values(
83 clEnumValN(FloatABI::Default, "default",
84 "Target default float ABI type"),
85 clEnumValN(FloatABI::Soft, "soft",
86 "Soft float ABI (implied by -soft-float)"),
87 clEnumValN(FloatABI::Hard, "hard",
88 "Hard float ABI (uses FP registers)"),
89 clEnumValEnd));
90
91 static cl::opt
92 FuseFPOps("fp-contract",
93 cl::desc("Enable aggresive formation of fused FP ops"),
94 cl::init(FPOpFusion::Standard),
95 cl::values(
96 clEnumValN(FPOpFusion::Fast, "fast",
97 "Fuse FP ops whenever profitable"),
98 clEnumValN(FPOpFusion::Standard, "on",
99 "Only fuse 'blessed' FP ops."),
100 clEnumValN(FPOpFusion::Strict, "off",
101 "Only fuse FP ops when the result won't be effected."),
102 clEnumValEnd));
103
104 static cl::opt
105 DontPlaceZerosInBSS("nozero-initialized-in-bss",
106 cl::desc("Don't place zero-initialized symbols into bss section"),
107 cl::init(false));
108
109 static cl::opt
110 EnableGuaranteedTailCallOpt("tailcallopt",
111 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
112 cl::init(false));
113
114 static cl::opt
115 DisableTailCalls("disable-tail-calls",
116 cl::desc("Never emit tail calls"),
117 cl::init(false));
118
119 static cl::opt
120 OverrideStackAlignment("stack-alignment",
121 cl::desc("Override default stack alignment"),
122 cl::init(0));
123
124 static cl::opt
125 TrapFuncName("trap-func", cl::Hidden,
126 cl::desc("Emit a call to trap function rather than a trap instruction"),
127 cl::init(""));
128
129 static cl::opt
130 EnablePIE("enable-pie",
131 cl::desc("Assume the creation of a position independent executable."),
132 cl::init(false));
133
134 static cl::opt
135 SegmentedStacks("segmented-stacks",
136 cl::desc("Use segmented stacks if possible."),
137 cl::init(false));
138
139 static cl::opt
140 UseInitArray("use-init-array",
141 cl::desc("Use .init_array instead of .ctors."),
142 cl::init(false));
143
144 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
145 : _module(m), _target(t),
146 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL),
147 _mangler(_context, t) {}
148
149 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
150 /// bitcode.
151 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
152 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
153 sys::fs::file_magic::bitcode;
154 }
155
156 bool LTOModule::isBitcodeFile(const char *path) {
157 sys::fs::file_magic type;
158 if (sys::fs::identify_magic(path, type))
159 return false;
160 return type == sys::fs::file_magic::bitcode;
161 }
162
163 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
164 /// LLVM bitcode for the specified triple.
165 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
166 const char *triplePrefix) {
167 MemoryBuffer *buffer = makeBuffer(mem, length);
168 if (!buffer)
169 return false;
170 return isTargetMatch(buffer, triplePrefix);
171 }
172
173 bool LTOModule::isBitcodeFileForTarget(const char *path,
174 const char *triplePrefix) {
175 OwningPtr buffer;
176 if (MemoryBuffer::getFile(path, buffer))
177 return false;
178 return isTargetMatch(buffer.take(), triplePrefix);
179 }
180
181 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
182 /// target triple.
183 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
184 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
185 delete buffer;
186 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
187 }
188
189 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
190 /// the buffer.
191 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
192 OwningPtr buffer;
193 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
194 errMsg = ec.message();
195 return NULL;
196 }
197 return makeLTOModule(buffer.take(), errMsg);
198 }
199
200 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
201 size_t size, std::string &errMsg) {
202 return makeLTOModule(fd, path, size, 0, errMsg);
203 }
204
205 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
206 size_t map_size,
207 off_t offset,
208 std::string &errMsg) {
209 OwningPtr buffer;
210 if (error_code ec =
211 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
212 errMsg = ec.message();
213 return NULL;
214 }
215 return makeLTOModule(buffer.take(), errMsg);
216 }
217
218 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
219 std::string &errMsg) {
220 OwningPtr buffer(makeBuffer(mem, length));
221 if (!buffer)
222 return NULL;
223 return makeLTOModule(buffer.take(), errMsg);
224 }
225
226 void LTOModule::getTargetOptions(TargetOptions &Options) {
227 Options.LessPreciseFPMADOption = EnableFPMAD;
228 Options.NoFramePointerElim = DisableFPElim;
229 Options.AllowFPOpFusion = FuseFPOps;
230 Options.UnsafeFPMath = EnableUnsafeFPMath;
231 Options.NoInfsFPMath = EnableNoInfsFPMath;
232 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
233 Options.HonorSignDependentRoundingFPMathOption =
234 EnableHonorSignDependentRoundingFPMath;
235 Options.UseSoftFloat = GenerateSoftFloatCalls;
236 if (FloatABIForCalls != FloatABI::Default)
237 Options.FloatABIType = FloatABIForCalls;
238 Options.NoZerosInBSS = DontPlaceZerosInBSS;
239 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
240 Options.DisableTailCalls = DisableTailCalls;
241 Options.StackAlignmentOverride = OverrideStackAlignment;
242 Options.TrapFuncName = TrapFuncName;
243 Options.PositionIndependentExecutable = EnablePIE;
244 Options.EnableSegmentedStacks = SegmentedStacks;
245 Options.UseInitArray = UseInitArray;
246 }
247
248 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
249 std::string &errMsg) {
250 // parse bitcode buffer
251 OwningPtr m(getLazyBitcodeModule(buffer, getGlobalContext(),
252 &errMsg));
253 if (!m) {
254 delete buffer;
255 return NULL;
256 }
257
258 std::string TripleStr = m->getTargetTriple();
259 if (TripleStr.empty())
260 TripleStr = sys::getDefaultTargetTriple();
261 llvm::Triple Triple(TripleStr);
262
263 // find machine architecture for this module
264 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
265 if (!march)
266 return NULL;
267
268 // construct LTOModule, hand over ownership of module and target
269 SubtargetFeatures Features;
270 Features.getDefaultSubtargetFeatures(Triple);
271 std::string FeatureStr = Features.getString();
272 // Set a default CPU for Darwin triples.
273 std::string CPU;
274 if (Triple.isOSDarwin()) {
275 if (Triple.getArch() == llvm::Triple::x86_64)
276 CPU = "core2";
277 else if (Triple.getArch() == llvm::Triple::x86)
278 CPU = "yonah";
279 }
280 TargetOptions Options;
281 getTargetOptions(Options);
282 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
283 Options);
284 LTOModule *Ret = new LTOModule(m.take(), target);
285 if (Ret->parseSymbols(errMsg)) {
286 delete Ret;
287 return NULL;
288 }
289
290 return Ret;
291 }
292
293 /// makeBuffer - Create a MemoryBuffer from a memory range.
294 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
295 const char *startPtr = (const char*)mem;
296 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
297 }
298
299 /// objcClassNameFromExpression - Get string that the data pointer points to.
300 bool
301 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
302 if (const ConstantExpr *ce = dyn_cast(c)) {
303 Constant *op = ce->getOperand(0);
304 if (GlobalVariable *gvn = dyn_cast(op)) {
305 Constant *cn = gvn->getInitializer();
306 if (ConstantDataArray *ca = dyn_cast(cn)) {
307 if (ca->isCString()) {
308 name = ".objc_class_name_" + ca->getAsCString().str();
309 return true;
310 }
311 }
312 }
313 }
314 return false;
315 }
316
317 /// addObjCClass - Parse i386/ppc ObjC class data structure.
318 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
319 const ConstantStruct *c = dyn_cast(clgv->getInitializer());
320 if (!c) return;
321
322 // second slot in __OBJC,__class is pointer to superclass name
323 std::string superclassName;
324 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
325 NameAndAttributes info;
326 StringMap::value_type &entry =
327 _undefines.GetOrCreateValue(superclassName);
328 if (!entry.getValue().name) {
329 const char *symbolName = entry.getKey().data();
330 info.name = symbolName;
331 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
332 info.isFunction = false;
333 info.symbol = clgv;
334 entry.setValue(info);
335 }
336 }
337
338 // third slot in __OBJC,__class is pointer to class name
339 std::string className;
340 if (objcClassNameFromExpression(c->getOperand(2), className)) {
341 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
342 entry.setValue(1);
343
344 NameAndAttributes info;
345 info.name = entry.getKey().data();
346 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
347 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
348 info.isFunction = false;
349 info.symbol = clgv;
350 _symbols.push_back(info);
351 }
352 }
353
354 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
355 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
356 const ConstantStruct *c = dyn_cast(clgv->getInitializer());
357 if (!c) return;
358
359 // second slot in __OBJC,__category is pointer to target class name
360 std::string targetclassName;
361 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
362 return;
363
364 NameAndAttributes info;
365 StringMap::value_type &entry =
366 _undefines.GetOrCreateValue(targetclassName);
367
368 if (entry.getValue().name)
369 return;
370
371 const char *symbolName = entry.getKey().data();
372 info.name = symbolName;
373 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
374 info.isFunction = false;
375 info.symbol = clgv;
376 entry.setValue(info);
377 }
378
379 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
380 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
381 std::string targetclassName;
382 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
383 return;
384
385 NameAndAttributes info;
386 StringMap::value_type &entry =
387 _undefines.GetOrCreateValue(targetclassName);
388 if (entry.getValue().name)
389 return;
390
391 const char *symbolName = entry.getKey().data();
392 info.name = symbolName;
393 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
394 info.isFunction = false;
395 info.symbol = clgv;
396 entry.setValue(info);
397 }
398
399 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
400 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
401 // Add to list of defined symbols.
402 addDefinedSymbol(v, false);
403
404 if (!v->hasSection() /* || !isTargetDarwin */)
405 return;
406
407 // Special case i386/ppc ObjC data structures in magic sections:
408 // The issue is that the old ObjC object format did some strange
409 // contortions to avoid real linker symbols. For instance, the
410 // ObjC class data structure is allocated statically in the executable
411 // that defines that class. That data structures contains a pointer to
412 // its superclass. But instead of just initializing that part of the
413 // struct to the address of its superclass, and letting the static and
414 // dynamic linkers do the rest, the runtime works by having that field
415 // instead point to a C-string that is the name of the superclass.
416 // At runtime the objc initialization updates that pointer and sets
417 // it to point to the actual super class. As far as the linker
418 // knows it is just a pointer to a string. But then someone wanted the
419 // linker to issue errors at build time if the superclass was not found.
420 // So they figured out a way in mach-o object format to use an absolute
421 // symbols (.objc_class_name_Foo = 0) and a floating reference
422 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
423 // a class was missing.
424 // The following synthesizes the implicit .objc_* symbols for the linker
425 // from the ObjC data structures generated by the front end.
426
427 // special case if this data blob is an ObjC class definition
428 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
429 if (const GlobalVariable *gv = dyn_cast(v)) {
430 addObjCClass(gv);
431 }
432 }
433
434 // special case if this data blob is an ObjC category definition
435 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
436 if (const GlobalVariable *gv = dyn_cast(v)) {
437 addObjCCategory(gv);
438 }
439 }
440
441 // special case if this data blob is the list of referenced classes
442 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
443 if (const GlobalVariable *gv = dyn_cast(v)) {
444 addObjCClassRef(gv);
445 }
446 }
447 }
448
449 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
450 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
451 // add to list of defined symbols
452 addDefinedSymbol(f, true);
453 }
454
455 /// addDefinedSymbol - Add a defined symbol to the list.
456 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
457 // ignore all llvm.* symbols
458 if (def->getName().startswith("llvm."))
459 return;
460
461 // string is owned by _defines
462 SmallString<64> Buffer;
463 _mangler.getNameWithPrefix(Buffer, def, false);
464
465 // set alignment part log2() can have rounding errors
466 uint32_t align = def->getAlignment();
467 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
468
469 // set permissions part
470 if (isFunction) {
471 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
472 } else {
473 const GlobalVariable *gv = dyn_cast(def);
474 if (gv && gv->isConstant())
475 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
476 else
477 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
478 }
479
480 // set definition part
481 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
482 def->hasLinkerPrivateWeakLinkage())
483 attr |= LTO_SYMBOL_DEFINITION_WEAK;
484 else if (def->hasCommonLinkage())
485 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
486 else
487 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
488
489 // set scope part
490 if (def->hasHiddenVisibility())
491 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
492 else if (def->hasProtectedVisibility())
493 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
494 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
495 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
496 def->hasLinkerPrivateWeakLinkage())
497 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
498 else if (def->hasLinkOnceODRAutoHideLinkage())
499 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
500 else
501 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
502
503 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
504 entry.setValue(1);
505
506 // fill information structure
507 NameAndAttributes info;
508 StringRef Name = entry.getKey();
509 info.name = Name.data();
510 assert(info.name[Name.size()] == '\0');
511 info.attributes = attr;
512 info.isFunction = isFunction;
513 info.symbol = def;
514
515 // add to table of symbols
516 _symbols.push_back(info);
517 }
518
519 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
520 /// defined list.
521 void LTOModule::addAsmGlobalSymbol(const char *name,
522 lto_symbol_attributes scope) {
523 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
524
525 // only add new define if not already defined
526 if (entry.getValue())
527 return;
528
529 entry.setValue(1);
530
531 NameAndAttributes &info = _undefines[entry.getKey().data()];
532
533 if (info.symbol == 0) {
534 // FIXME: This is trying to take care of module ASM like this:
535 //
536 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
537 //
538 // but is gross and its mother dresses it funny. Have the ASM parser give us
539 // more details for this type of situation so that we're not guessing so
540 // much.
541
542 // fill information structure
543 info.name = entry.getKey().data();
544 info.attributes =
545 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
546 info.isFunction = false;
547 info.symbol = 0;
548
549 // add to table of symbols
550 _symbols.push_back(info);
551 return;
552 }
553
554 if (info.isFunction)
555 addDefinedFunctionSymbol(cast(info.symbol));
556 else
557 addDefinedDataSymbol(info.symbol);
558
559 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
560 _symbols.back().attributes |= scope;
561 }
562
563 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
564 /// undefined list.
565 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
566 StringMap::value_type &entry =
567 _undefines.GetOrCreateValue(name);
568
569 _asm_undefines.push_back(entry.getKey().data());
570
571 // we already have the symbol
572 if (entry.getValue().name)
573 return;
574
575 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
576 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
577 NameAndAttributes info;
578 info.name = entry.getKey().data();
579 info.attributes = attr;
580 info.isFunction = false;
581 info.symbol = 0;
582
583 entry.setValue(info);
584 }
585
586 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
587 /// list to be resolved later.
588 void
589 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
590 // ignore all llvm.* symbols
591 if (decl->getName().startswith("llvm."))
592 return;
593
594 // ignore all aliases
595 if (isa(decl))
596 return;
597
598 SmallString<64> name;
599 _mangler.getNameWithPrefix(name, decl, false);
600
601 StringMap::value_type &entry =
602 _undefines.GetOrCreateValue(name);
603
604 // we already have the symbol
605 if (entry.getValue().name)
606 return;
607
608 NameAndAttributes info;
609
610 info.name = entry.getKey().data();
611
612 if (decl->hasExternalWeakLinkage())
613 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
614 else
615 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
616
617 info.isFunction = isFunc;
618 info.symbol = decl;
619
620 entry.setValue(info);
621 }
622
623 namespace {
624 class RecordStreamer : public MCStreamer {
625 public:
626 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
627
628 private:
629 StringMap Symbols;
630
631 void markDefined(const MCSymbol &Symbol) {
632 State &S = Symbols[Symbol.getName()];
633 switch (S) {
634 case DefinedGlobal:
635 case Global:
636 S = DefinedGlobal;
637 break;
638 case NeverSeen:
639 case Defined:
640 case Used:
641 S = Defined;
642 break;
643 }
644 }
645 void markGlobal(const MCSymbol &Symbol) {
646 State &S = Symbols[Symbol.getName()];
647 switch (S) {
648 case DefinedGlobal:
649 case Defined:
650 S = DefinedGlobal;
651 break;
652
653 case NeverSeen:
654 case Global:
655 case Used:
656 S = Global;
657 break;
658 }
659 }
660 void markUsed(const MCSymbol &Symbol) {
661 State &S = Symbols[Symbol.getName()];
662 switch (S) {
663 case DefinedGlobal:
664 case Defined:
665 case Global:
666 break;
667
668 case NeverSeen:
669 case Used:
670 S = Used;
671 break;
672 }
673 }
674
675 // FIXME: mostly copied for the obj streamer.
676 void AddValueSymbols(const MCExpr *Value) {
677 switch (Value->getKind()) {
678 case MCExpr::Target:
679 // FIXME: What should we do in here?
680 break;
681
682 case MCExpr::Constant:
683 break;
684
685 case MCExpr::Binary: {
686 const MCBinaryExpr *BE = cast(Value);
687 AddValueSymbols(BE->getLHS());
688 AddValueSymbols(BE->getRHS());
689 break;
690 }
691
692 case MCExpr::SymbolRef:
693 markUsed(cast(Value)->getSymbol());
694 break;
695
696 case MCExpr::Unary:
697 AddValueSymbols(cast(Value)->getSubExpr());
698 break;
699 }
700 }
701
702 public:
703 typedef StringMap::const_iterator const_iterator;
704
705 const_iterator begin() {
706 return Symbols.begin();
707 }
708
709 const_iterator end() {
710 return Symbols.end();
711 }
712
713 RecordStreamer(MCContext &Context)
714 : MCStreamer(SK_RecordStreamer, Context) {}
715
716 virtual void EmitInstruction(const MCInst &Inst) {
717 // Scan for values.
718 for (unsigned i = Inst.getNumOperands(); i--; )
719 if (Inst.getOperand(i).isExpr())
720 AddValueSymbols(Inst.getOperand(i).getExpr());
721 }
722 virtual void EmitLabel(MCSymbol *Symbol) {
723 Symbol->setSection(*getCurrentSection().first);
724 markDefined(*Symbol);
725 }
726 virtual void EmitDebugLabel(MCSymbol *Symbol) {
727 EmitLabel(Symbol);
728 }
729 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
730 // FIXME: should we handle aliases?
731 markDefined(*Symbol);
732 }
733 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
734 if (Attribute == MCSA_Global)
735 markGlobal(*Symbol);
736 return true;
737 }
738 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
739 uint64_t Size , unsigned ByteAlignment) {
740 markDefined(*Symbol);
741 }
742 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
743 unsigned ByteAlignment) {
744 markDefined(*Symbol);
745 }
746
747 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
748 virtual void EmitBundleLock(bool AlignToEnd) {}
749 virtual void EmitBundleUnlock() {}
750
751 // Noop calls.
752 virtual void ChangeSection(const MCSection *Section,
753 const MCExpr *Subsection) {}
754 virtual void InitToTextSection() {}
755 virtual void InitSections() {}
756 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
757 virtual void EmitThumbFunc(MCSymbol *Func) {}
758 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
759 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
760 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
761 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
762 virtual void EmitCOFFSymbolType(int Type) {}
763 virtual void EndCOFFSymbolDef() {}
764 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
765 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
766 unsigned ByteAlignment) {}
767 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
768 uint64_t Size, unsigned ByteAlignment) {}
769 virtual void EmitBytes(StringRef Data) {}
770 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
771 virtual void EmitULEB128Value(const MCExpr *Value) {}
772 virtual void EmitSLEB128Value(const MCExpr *Value) {}
773 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
774 unsigned ValueSize,
775 unsigned MaxBytesToEmit) {}
776 virtual void EmitCodeAlignment(unsigned ByteAlignment,
777 unsigned MaxBytesToEmit) {}
778 virtual bool EmitValueToOffset(const MCExpr *Offset,
779 unsigned char Value ) { return false; }
780 virtual void EmitFileDirective(StringRef Filename) {}
781 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
782 const MCSymbol *LastLabel,
783 const MCSymbol *Label,
784 unsigned PointerSize) {}
785 virtual void FinishImpl() {}
786 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
787 RecordProcEnd(Frame);
788 }
789
790 static bool classof(const MCStreamer *S) {
791 return S->getKind() == SK_RecordStreamer;
792 }
793 };
794 } // end anonymous namespace
795
796 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
797 /// defined or undefined lists.
798 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
799 const std::string &inlineAsm = _module->getModuleInlineAsm();
800 if (inlineAsm.empty())
801 return false;
802
803 OwningPtr Streamer(new RecordStreamer(_context));
804 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
805 SourceMgr SrcMgr;
806 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
807 OwningPtr Parser(createMCAsmParser(SrcMgr,
808 _context, *Streamer,
809 *_target->getMCAsmInfo()));
810 const Target &T = _target->getTarget();
811 OwningPtr MCII(T.createMCInstrInfo());
812 OwningPtr
813 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
814 _target->getTargetCPU(),
815 _target->getTargetFeatureString()));
816 OwningPtr TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
817 if (!TAP) {
818 errMsg = "target " + std::string(T.getName()) +
819 " does not define AsmParser.";
820 return true;
821 }
822
823 Parser->setTargetParser(*TAP);
824 if (Parser->Run(false))
825 return true;
826
827 for (RecordStreamer::const_iterator i = Streamer->begin(),
828 e = Streamer->end(); i != e; ++i) {
829 StringRef Key = i->first();
830 RecordStreamer::State Value = i->second;
831 if (Value == RecordStreamer::DefinedGlobal)
832 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
833 else if (Value == RecordStreamer::Defined)
834 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
835 else if (Value == RecordStreamer::Global ||
836 Value == RecordStreamer::Used)
837 addAsmGlobalSymbolUndef(Key.data());
838 }
839
840 return false;
841 }
842
843 /// isDeclaration - Return 'true' if the global value is a declaration.
844 static bool isDeclaration(const GlobalValue &V) {
845 if (V.hasAvailableExternallyLinkage())
846 return true;
847
848 if (V.isMaterializable())
849 return false;
850
851 return V.isDeclaration();
852 }
853
854 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
855 /// them to either the defined or undefined lists.
856 bool LTOModule::parseSymbols(std::string &errMsg) {
857 // add functions
858 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
859 if (isDeclaration(*f))
860 addPotentialUndefinedSymbol(f, true);
861 else
862 addDefinedFunctionSymbol(f);
863 }
864
865 // add data
866 for (Module::global_iterator v = _module->global_begin(),
867 e = _module->global_end(); v != e; ++v) {
868 if (isDeclaration(*v))
869 addPotentialUndefinedSymbol(v, false);
870 else
871 addDefinedDataSymbol(v);
872 }
873
874 // add asm globals
875 if (addAsmGlobalSymbols(errMsg))
876 return true;
877
878 // add aliases
879 for (Module::alias_iterator a = _module->alias_begin(),
880 e = _module->alias_end(); a != e; ++a) {
881 if (isDeclaration(*a->getAliasedGlobal()))
882 // Is an alias to a declaration.
883 addPotentialUndefinedSymbol(a, false);
884 else
885 addDefinedDataSymbol(a);
886 }
887
888 // make symbols for all undefines
889 for (StringMap::iterator u =_undefines.begin(),
890 e = _undefines.end(); u != e; ++u) {
891 // If this symbol also has a definition, then don't make an undefine because
892 // it is a tentative definition.
893 if (_defines.count(u->getKey())) continue;
894 NameAndAttributes info = u->getValue();
895 _symbols.push_back(info);
896 }
897
898 return false;
899 }
0 ##===- lib/Linker/Makefile ---------------------------------*- Makefile -*-===##
1 #
2 # The LLVM Compiler Infrastructure
3 #
4 # This file is distributed under the University of Illinois Open Source
5 # License. See LICENSE.TXT for details.
6 #
7 ##===----------------------------------------------------------------------===##
8
9 LEVEL = ../..
10 LIBRARYNAME = LLVMLTO
11 BUILD_ARCHIVE := 1
12
13 include $(LEVEL)/Makefile.common
14
1010 include $(LEVEL)/Makefile.config
1111
1212 PARALLEL_DIRS := IR AsmParser Bitcode Analysis Transforms CodeGen \
13 Target ExecutionEngine Linker MC Object Option DebugInfo \
13 Target ExecutionEngine Linker LTO MC Object Option DebugInfo \
1414 IRReader
1515
1616 include $(LEVEL)/Makefile.common
0 ; RUN: llvm-as < %s >%t1
1 ; RUN: llvm-lto -o %t2 %t1
2
3 target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"
4 target triple = "x86_64-unknown-linux-gnu"
5
6 module asm ".text"
7 module asm ".align 16, 0x90"
8 module asm ".type PR14512, @function"
9 module asm "PR14512:.cfi_startproc"
10 module asm "ret"
11 module asm ".cfi_endproc"
12
13 declare void @PR14512()
14
15 define i32 @main(i32 %argc, i8** %argv) {
16 call void @PR14512()
17 ret i32 0
18 }
19 ; XFAIL: win32
0 targets = set(config.root.targets_to_build.split())
1 if not 'X86' in targets:
2 config.unsupported = True
3
4 if config.root.host_os in ['Cygwin', 'MingW', 'Windows']:
5 config.unsupported = True
+0
-20
test/tools/lto/cfi_endproc.ll less more
None ; RUN: llvm-as < %s >%t1
1 ; RUN: llvm-lto -o %t2 %t1
2
3 target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"
4 target triple = "x86_64-unknown-linux-gnu"
5
6 module asm ".text"
7 module asm ".align 16, 0x90"
8 module asm ".type PR14512, @function"
9 module asm "PR14512:.cfi_startproc"
10 module asm "ret"
11 module asm ".cfi_endproc"
12
13 declare void @PR14512()
14
15 define i32 @main(i32 %argc, i8** %argv) {
16 call void @PR14512()
17 ret i32 0
18 }
19 ; XFAIL: win32
+0
-6
test/tools/lto/lit.local.cfg less more
None targets = set(config.root.targets_to_build.split())
1 if not 'X86' in targets:
2 config.unsupported = True
3
4 if config.root.host_os in ['Cygwin', 'MingW', 'Windows']:
5 config.unsupported = True
1515 ;===------------------------------------------------------------------------===;
1616
1717 [common]
18 subdirectories = bugpoint llc lli llvm-ar llvm-as llvm-bcanalyzer llvm-cov llvm-diff llvm-dis llvm-dwarfdump llvm-extract llvm-jitlistener llvm-link llvm-mc llvm-nm llvm-objdump llvm-prof llvm-rtdyld llvm-size macho-dump opt llvm-mcmarkup
18 subdirectories = bugpoint llc lli llvm-ar llvm-as llvm-bcanalyzer llvm-cov llvm-diff llvm-dis llvm-dwarfdump llvm-extract llvm-jitlistener llvm-link llvm-lto llvm-mc llvm-nm llvm-objdump llvm-prof llvm-rtdyld llvm-size macho-dump opt llvm-mcmarkup
1919
2020 [component_0]
2121 type = Group
0 set(LLVM_LINK_COMPONENTS ${LLVM_TARGETS_TO_BUILD} lto support)
1
2 add_llvm_tool(llvm-lto
13 llvm-lto.cpp
24 )
35
4 target_link_libraries(llvm-lto LTO LLVMSupport)
5
6 add_dependencies(llvm-lto lto)
0 ;===- ./tools/llvm-lto/LLVMBuild.txt ----------------------------*- Conf -*--===;
1 ;
2 ; The LLVM Compiler Infrastructure
3 ;
4 ; This file is distributed under the University of Illinois Open Source
5 ; License. See LICENSE.TXT for details.
6 ;
7 ;===------------------------------------------------------------------------===;
8 ;
9 ; This is an LLVMBuild description file for the components in this subdirectory.
10 ;
11 ; For more information on the LLVMBuild system, please see:
12 ;
13 ; http://llvm.org/docs/LLVMBuild.html
14 ;
15 ;===------------------------------------------------------------------------===;
16
17 [component_0]
18 type = Tool
19 name = llvm-lto
20 parent = Tools
21 required_libraries = LTO Support all-targets
88
99 LEVEL := ../..
1010 TOOLNAME := llvm-lto
11 LINK_COMPONENTS := support
11 LINK_COMPONENTS := lto ipo scalaropts linker bitreader bitwriter mcdisassembler support target vectorize all-targets
1212
1313 # This tool has no plugins, optimize startup time.
1414 TOOL_NO_EXPORTS := 1
1616 NO_INSTALL := 1
1717
1818 include $(LEVEL)/Makefile.common
19
20 LDFLAGS += -L$(LibDir)
21 LIBS += -lLTO
1111 //
1212 //===----------------------------------------------------------------------===//
1313
14 #include "llvm-c/lto.h"
14 #include "llvm/LTO/LTOCodeGenerator.h"
15 #include "llvm/LTO/LTOModule.h"
1516 #include "llvm/Support/CommandLine.h"
1617 #include "llvm/Support/ManagedStatic.h"
1718 #include "llvm/Support/PrettyStackTrace.h"
1819 #include "llvm/Support/Signals.h"
1920 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Support/TargetSelect.h"
2022
2123 using namespace llvm;
2224
3638 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
3739 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
3840
41 // Initialize the configured targets.
42 InitializeAllTargets();
43 InitializeAllTargetMCs();
44 InitializeAllAsmPrinters();
45 InitializeAllAsmParsers();
46
3947 unsigned BaseArg = 0;
4048 std::string ErrorMessage;
4149
42 lto_code_gen_t code_gen = lto_codegen_create();
43 if (code_gen == NULL)
44 errs() << argv[0] << ": error creating a code generation module: "
45 << lto_get_error_message() << "\n";
50 LTOCodeGenerator CodeGen;
4651
47 lto_codegen_set_pic_model(code_gen, LTO_CODEGEN_PIC_MODEL_DYNAMIC);
48 lto_codegen_set_debug_model(code_gen, LTO_DEBUG_MODEL_DWARF);
52 CodeGen.setCodePICModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC);
53 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
4954
5055 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
51 lto_module_t BitcodeModule = lto_module_create(InputFilenames[i].c_str());
52 if (BitcodeModule == NULL) {
56 std::string error;
57 OwningPtr Module(LTOModule::makeLTOModule(InputFilenames[i].c_str(),
58 error));
59 if (!error.empty()) {
5360 errs() << argv[0] << ": error loading file '" << InputFilenames[i]
54 << "': " << lto_get_error_message() << "\n";
61 << "': " << error << "\n";
5562 return 1;
5663 }
5764
58 if (lto_codegen_add_module(code_gen, BitcodeModule)) {
65
66 if (!CodeGen.addModule(Module.get(), error)) {
5967 errs() << argv[0] << ": error adding file '" << InputFilenames[i]
60 << "': " << lto_get_error_message() << "\n";
61 lto_module_dispose(BitcodeModule);
68 << "': " << error << "\n";
6269 return 1;
6370 }
64
65 lto_module_dispose(BitcodeModule);
6671 }
6772
6873 if (!OutputFilename.empty()) {
6974 size_t len = 0;
70 const void *Code = lto_codegen_compile(code_gen, &len);
75 std::string ErrorInfo;
76 const void *Code = CodeGen.compile(&len, ErrorInfo);
7177 if (Code == NULL) {
7278 errs() << argv[0]
73 << ": error compiling the code: " << lto_get_error_message()
74 << "\n";
79 << ": error compiling the code: " << ErrorInfo << "\n";
7580 return 1;
7681 }
7782
78 std::string ErrorInfo;
7983 raw_fd_ostream FileStream(OutputFilename.c_str(), ErrorInfo);
8084 if (!ErrorInfo.empty()) {
8185 errs() << argv[0] << ": error opening the file '" << OutputFilename
8589
8690 FileStream.write(reinterpret_cast(Code), len);
8791 } else {
92 std::string ErrorInfo;
8893 const char *OutputName = NULL;
89 if (lto_codegen_compile_to_file(code_gen, &OutputName)) {
94 if (!CodeGen.compile_to_file(&OutputName, ErrorInfo)) {
9095 errs() << argv[0]
91 << ": error compiling the code: " << lto_get_error_message()
96 << ": error compiling the code: " << ErrorInfo
9297 << "\n";
9398 return 1;
9499 }
96101 outs() << "Wrote native object file '" << OutputName << "'\n";
97102 }
98103
99 lto_codegen_dispose(code_gen);
100
101104 return 0;
102105 }
0 set(LLVM_LINK_COMPONENTS
11 ${LLVM_TARGETS_TO_BUILD}
2 ipo scalaropts linker bitreader bitwriter mcdisassembler vectorize)
2 ipo scalaropts linker bitreader bitwriter lto mcdisassembler vectorize)
33
44 add_definitions( -DLLVM_VERSION_INFO=\"${PACKAGE_VERSION}\" )
55
66 set(SOURCES
7 LTOCodeGenerator.cpp
87 LTODisassembler.cpp
98 lto.cpp
10 LTOModule.cpp
119 )
1210
1311 if( NOT WIN32 AND LLVM_ENABLE_PIC )
+0
-458
tools/lto/LTOCodeGenerator.cpp less more
None //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LTOCodeGenerator.h"
15 #include "LTOModule.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/InitializePasses.h"
27 #include "llvm/Linker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/system_error.h"
42 #include "llvm/Target/Mangler.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegisterInfo.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include "llvm/Transforms/ObjCARC.h"
49 using namespace llvm;
50
51 static cl::opt
52 DisableOpt("disable-opt", cl::init(false),
53 cl::desc("Do not run any optimization passes"));
54
55 static cl::opt
56 DisableInline("disable-inlining", cl::init(false),
57 cl::desc("Do not run the inliner pass"));
58
59 static cl::opt
60 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
61 cl::desc("Do not run the GVN load PRE pass"));
62
63 const char* LTOCodeGenerator::getVersionString() {
64 #ifdef LLVM_VERSION_INFO
65 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
66 #else
67 return PACKAGE_NAME " version " PACKAGE_VERSION;
68 #endif
69 }
70
71 LTOCodeGenerator::LTOCodeGenerator()
72 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
73 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
74 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
75 InitializeAllTargets();
76 InitializeAllTargetMCs();
77 InitializeAllAsmPrinters();
78 initializeLTOPasses();
79 }
80
81 LTOCodeGenerator::~LTOCodeGenerator() {
82 delete TargetMach;
83 delete NativeObjectFile;
84 delete Linker.getModule();
85
86 for (std::vector::iterator I = CodegenOptions.begin(),
87 E = CodegenOptions.end();
88 I != E; ++I)
89 free(*I);
90 }
91
92 // Initialize LTO passes. Please keep this funciton in sync with
93 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
94 // passes are initialized.
95 //
96 void LTOCodeGenerator::initializeLTOPasses() {
97 PassRegistry &R = *PassRegistry::getPassRegistry();
98
99 initializeInternalizePassPass(R);
100 initializeIPSCCPPass(R);
101 initializeGlobalOptPass(R);
102 initializeConstantMergePass(R);
103 initializeDAHPass(R);
104 initializeInstCombinerPass(R);
105 initializeSimpleInlinerPass(R);
106 initializePruneEHPass(R);
107 initializeGlobalDCEPass(R);
108 initializeArgPromotionPass(R);
109 initializeJumpThreadingPass(R);
110 initializeSROAPass(R);
111 initializeSROA_DTPass(R);
112 initializeSROA_SSAUpPass(R);
113 initializeFunctionAttrsPass(R);
114 initializeGlobalsModRefPass(R);
115 initializeLICMPass(R);
116 initializeGVNPass(R);
117 initializeMemCpyOptPass(R);
118 initializeDCEPass(R);
119 initializeCFGSimplifyPassPass(R);
120 }
121
122 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
123 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
124
125 const std::vector &undefs = mod->getAsmUndefinedRefs();
126 for (int i = 0, e = undefs.size(); i != e; ++i)
127 AsmUndefinedRefs[undefs[i]] = 1;
128
129 return !ret;
130 }
131
132 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
133 switch (debug) {
134 case LTO_DEBUG_MODEL_NONE:
135 EmitDwarfDebugInfo = false;
136 return;
137
138 case LTO_DEBUG_MODEL_DWARF:
139 EmitDwarfDebugInfo = true;
140 return;
141 }
142 llvm_unreachable("Unknown debug format!");
143 }
144
145 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
146 switch (model) {
147 case LTO_CODEGEN_PIC_MODEL_STATIC:
148 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
149 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
150 CodeModel = model;
151 return;
152 }
153 llvm_unreachable("Unknown PIC model!");
154 }
155
156 bool LTOCodeGenerator::writeMergedModules(const char *path,
157 std::string &errMsg) {
158 if (!determineTarget(errMsg))
159 return false;
160
161 // mark which symbols can not be internalized
162 applyScopeRestrictions();
163
164 // create output file
165 std::string ErrInfo;
166 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
167 if (!ErrInfo.empty()) {
168 errMsg = "could not open bitcode file for writing: ";
169 errMsg += path;
170 return false;
171 }
172
173 // write bitcode to it
174 WriteBitcodeToFile(Linker.getModule(), Out.os());
175 Out.os().close();
176
177 if (Out.os().has_error()) {
178 errMsg = "could not write bitcode file: ";
179 errMsg += path;
180 Out.os().clear_error();
181 return false;
182 }
183
184 Out.keep();
185 return true;
186 }
187
188 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
189 // make unique temp .o file to put generated object file
190 SmallString<128> Filename;
191 int FD;
192 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
193 if (EC) {
194 errMsg = EC.message();
195 return false;
196 }
197
198 // generate object file
199 tool_output_file objFile(Filename.c_str(), FD);
200
201 bool genResult = generateObjectFile(objFile.os(), errMsg);
202 objFile.os().close();
203 if (objFile.os().has_error()) {
204 objFile.os().clear_error();
205 sys::fs::remove(Twine(Filename));
206 return false;
207 }
208
209 objFile.keep();
210 if (!genResult) {
211 sys::fs::remove(Twine(Filename));
212 return false;
213 }
214
215 NativeObjectPath = Filename.c_str();
216 *name = NativeObjectPath.c_str();
217 return true;
218 }
219
220 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
221 const char *name;
222 if (!compile_to_file(&name, errMsg))
223 return NULL;
224
225 // remove old buffer if compile() called twice
226 delete NativeObjectFile;
227
228 // read .o file into memory buffer
229 OwningPtr BuffPtr;
230 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
231 errMsg = ec.message();
232 sys::fs::remove(NativeObjectPath);
233 return NULL;
234 }
235 NativeObjectFile = BuffPtr.take();
236
237 // remove temp files
238 sys::fs::remove(NativeObjectPath);
239
240 // return buffer, unless error
241 if (NativeObjectFile == NULL)
242 return NULL;
243 *length = NativeObjectFile->getBufferSize();
244 return NativeObjectFile->getBufferStart();
245 }
246
247 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
248 if (TargetMach != NULL)
249 return true;
250
251 // if options were requested, set them
252 if (!CodegenOptions.empty())
253 cl::ParseCommandLineOptions(CodegenOptions.size(),
254 const_cast(&CodegenOptions[0]));
255
256 std::string TripleStr = Linker.getModule()->getTargetTriple();
257 if (TripleStr.empty())
258 TripleStr = sys::getDefaultTargetTriple();
259 llvm::Triple Triple(TripleStr);
260
261 // create target machine from info for merged modules
262 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
263 if (march == NULL)
264 return false;
265
266 // The relocation model is actually a static member of TargetMachine and
267 // needs to be set before the TargetMachine is instantiated.
268 Reloc::Model RelocModel = Reloc::Default;
269 switch (CodeModel) {
270 case LTO_CODEGEN_PIC_MODEL_STATIC:
271 RelocModel = Reloc::Static;
272 break;
273 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
274 RelocModel = Reloc::PIC_;
275 break;
276 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
277 RelocModel = Reloc::DynamicNoPIC;
278 break;
279 }
280
281 // construct LTOModule, hand over ownership of module and target
282 SubtargetFeatures Features;
283 Features.getDefaultSubtargetFeatures(Triple);
284 std::string FeatureStr = Features.getString();
285 // Set a default CPU for Darwin triples.
286 if (MCpu.empty() && Triple.isOSDarwin()) {
287 if (Triple.getArch() == llvm::Triple::x86_64)
288 MCpu = "core2";
289 else if (Triple.getArch() == llvm::Triple::x86)
290 MCpu = "yonah";
291 }
292 TargetOptions Options;
293 LTOModule::getTargetOptions(Options);
294 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
295 RelocModel, CodeModel::Default,
296 CodeGenOpt::Aggressive);
297 return true;
298 }
299
300 void LTOCodeGenerator::
301 applyRestriction(GlobalValue &GV,
302 std::vector &MustPreserveList,
303 SmallPtrSet &AsmUsed,
304 Mangler &Mangler) {
305 SmallString<64> Buffer;
306 Mangler.getNameWithPrefix(Buffer, &GV, false);
307
308 if (GV.isDeclaration())
309 return;
310 if (MustPreserveSymbols.count(Buffer))
311 MustPreserveList.push_back(GV.getName().data());
312 if (AsmUndefinedRefs.count(Buffer))
313 AsmUsed.insert(&GV);
314 }
315
316 static void findUsedValues(GlobalVariable *LLVMUsed,
317 SmallPtrSet &UsedValues) {
318 if (LLVMUsed == 0) return;
319
320 ConstantArray *Inits = cast(LLVMUsed->getInitializer());
321 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
322 if (GlobalValue *GV =
323 dyn_cast(Inits->getOperand(i)->stripPointerCasts()))
324 UsedValues.insert(GV);
325 }
326
327 void LTOCodeGenerator::applyScopeRestrictions() {
328 if (ScopeRestrictionsDone)
329 return;
330 Module *mergedModule = Linker.getModule();
331
332 // Start off with a verification pass.
333 PassManager passes;
334 passes.add(createVerifierPass());
335
336 // mark which symbols can not be internalized
337 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
338 NULL);
339 Mangler Mangler(MContext, TargetMach);
340 std::vector MustPreserveList;
341 SmallPtrSet AsmUsed;
342
343 for (Module::iterator f = mergedModule->begin(),
344 e = mergedModule->end(); f != e; ++f)
345 applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
346 for (Module::global_iterator v = mergedModule->global_begin(),
347 e = mergedModule->global_end(); v != e; ++v)
348 applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
349 for (Module::alias_iterator a = mergedModule->alias_begin(),
350 e = mergedModule->alias_end(); a != e; ++a)
351 applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
352
353 GlobalVariable *LLVMCompilerUsed =
354 mergedModule->getGlobalVariable("llvm.compiler.used");
355 findUsedValues(LLVMCompilerUsed, AsmUsed);
356 if (LLVMCompilerUsed)
357 LLVMCompilerUsed->eraseFromParent();
358
359 if (!AsmUsed.empty()) {
360 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
361 std::vector asmUsed2;
362 for (SmallPtrSet::const_iterator i = AsmUsed.begin(),
363 e = AsmUsed.end(); i !=e; ++i) {
364 GlobalValue *GV = *i;
365 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
366 asmUsed2.push_back(c);
367 }
368
369 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
370 LLVMCompilerUsed =
371 new llvm::GlobalVariable(*mergedModule, ATy, false,
372 llvm::GlobalValue::AppendingLinkage,
373 llvm::ConstantArray::get(ATy, asmUsed2),
374 "llvm.compiler.used");
375
376 LLVMCompilerUsed->setSection("llvm.metadata");
377 }
378
379 passes.add(createInternalizePass(MustPreserveList));
380
381 // apply scope restrictions
382 passes.run(*mergedModule);
383
384 ScopeRestrictionsDone = true;
385 }
386
387 /// Optimize merged modules using various IPO passes
388 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
389 std::string &errMsg) {
390 if (!this->determineTarget(errMsg))
391 return false;
392
393 Module *mergedModule = Linker.getModule();
394
395 // Mark which symbols can not be internalized
396 this->applyScopeRestrictions();
397
398 // Instantiate the pass manager to organize the passes.
399 PassManager passes;
400
401 // Start off with a verification pass.
402 passes.add(createVerifierPass());
403
404 // Add an appropriate DataLayout instance for this module...
405 passes.add(new DataLayout(*TargetMach->getDataLayout()));
406 TargetMach->addAnalysisPasses(passes);
407
408 // Enabling internalize here would use its AllButMain variant. It
409 // keeps only main if it exists and does nothing for libraries. Instead
410 // we create the pass ourselves with the symbol list provided by the linker.
411 if (!DisableOpt)
412 PassManagerBuilder().populateLTOPassManager(passes,
413 /*Internalize=*/false,
414 !DisableInline,
415 DisableGVNLoadPRE);
416
417 // Make sure everything is still good.
418 passes.add(createVerifierPass());
419
420 PassManager codeGenPasses;
421
422 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
423 TargetMach->addAnalysisPasses(codeGenPasses);
424
425 formatted_raw_ostream Out(out);
426
427 // If the bitcode files contain ARC code and were compiled with optimization,
428 // the ObjCARCContractPass must be run, so do it unconditionally here.
429 codeGenPasses.add(createObjCARCContractPass());
430
431 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
432 TargetMachine::CGFT_ObjectFile)) {
433 errMsg = "target file type not supported";
434 return false;
435 }
436
437 // Run our queue of passes all at once now, efficiently.
438 passes.run(*mergedModule);
439
440 // Run the code generator, and write assembly file
441 codeGenPasses.run(*mergedModule);
442
443 return true;
444 }
445
446 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
447 /// LTO problems.
448 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
449 for (std::pair o = getToken(options);
450 !o.first.empty(); o = getToken(o.second)) {
451 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
452 // that.
453 if (CodegenOptions.empty())
454 CodegenOptions.push_back(strdup("libLTO"));
455 CodegenOptions.push_back(strdup(o.first.str().c_str()));
456 }
457 }
+0
-130
tools/lto/LTOCodeGenerator.h less more
None //===-LTOCodeGenerator.h - LLVM Link Time Optimizer -----------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the LTOCodeGenerator class.
10 //
11 // LTO compilation consists of three phases: Pre-IPO, IPO and Post-IPO.
12 //
13 // The Pre-IPO phase compiles source code into bitcode file. The resulting
14 // bitcode files, along with object files and libraries, will be fed to the
15 // linker to through the IPO and Post-IPO phases. By using obj-file extension,
16 // the resulting bitcode file disguises itself as an object file, and therefore
17 // obviates the need of writing a special set of the make-rules only for LTO
18 // compilation.
19 //
20 // The IPO phase perform inter-procedural analyses and optimizations, and
21 // the Post-IPO consists two sub-phases: intra-procedural scalar optimizations
22 // (SOPT), and intra-procedural target-dependent code generator (CG).
23 //
24 // As of this writing, we don't separate IPO and the Post-IPO SOPT. They
25 // are intermingled together, and are driven by a single pass manager (see
26 // PassManagerBuilder::populateLTOPassManager()).
27 //
28 // The "LTOCodeGenerator" is the driver for the IPO and Post-IPO stages.
29 // The "CodeGenerator" here is bit confusing. Don't confuse the "CodeGenerator"
30 // with the machine specific code generator.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #ifndef LTO_CODE_GENERATOR_H
35 #define LTO_CODE_GENERATOR_H
36
37 #include "llvm-c/lto.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/StringMap.h"
40 #include "llvm/Linker.h"
41 #include
42 #include
43
44 namespace llvm {
45 class LLVMContext;
46 class GlobalValue;
47 class Mangler;
48 class MemoryBuffer;
49 class TargetMachine;
50 class raw_ostream;
51 }
52
53 //===----------------------------------------------------------------------===//
54 /// LTOCodeGenerator - C++ class which implements the opaque lto_code_gen_t
55 /// type.
56 ///
57 struct LTOCodeGenerator {
58 static const char *getVersionString();
59
60 LTOCodeGenerator();
61 ~LTOCodeGenerator();
62
63 // Merge given module, return true on success.
64 bool addModule(struct LTOModule*, std::string &errMsg);
65
66 void setDebugInfo(lto_debug_model);
67 void setCodePICModel(lto_codegen_model);
68
69 void setCpu(const char *mCpu) { MCpu = mCpu; }
70
71 void addMustPreserveSymbol(const char *sym) { MustPreserveSymbols[sym] = 1; }
72
73 // To pass options to the driver and optimization passes. These options are
74 // not necessarily for debugging purpose (The function name is misleading).
75 // This function should be called before LTOCodeGenerator::compilexxx(),
76 // and LTOCodeGenerator::writeMergedModules().
77 //
78 void setCodeGenDebugOptions(const char *opts);
79
80 // Write the merged module to the file specified by the given path.
81 // Return true on success.
82 bool writeMergedModules(const char *path, std::string &errMsg);
83
84 // Compile the merged module into a *single* object file; the path to object
85 // file is returned to the caller via argument "name". Return true on
86 // success.
87 //
88 // NOTE that it is up to the linker to remove the intermediate object file.
89 // Do not try to remove the object file in LTOCodeGenerator's destructor
90 // as we don't who (LTOCodeGenerator or the obj file) will last longer.
91 //
92 bool compile_to_file(const char **name, std::string &errMsg);
93
94 // As with compile_to_file(), this function compiles the merged module into
95 // single object file. Instead of returning the object-file-path to the caller
96 // (linker), it brings the object to a buffer, and return the buffer to the
97 // caller. This function should delete intermediate object file once its content
98 // is brought to memory. Return NULL is the compilation was not successful.
99 //
100 const void *compile(size_t *length, std::string &errMsg);
101
102 private:
103 void initializeLTOPasses();
104
105 bool generateObjectFile(llvm::raw_ostream &out, std::string &errMsg);
106 void applyScopeRestrictions();
107 void applyRestriction(llvm::GlobalValue &GV,
108 std::vector &MustPreserveList,
109 llvm::SmallPtrSet &AsmUsed,
110 llvm::Mangler &Mangler);
111 bool determineTarget(std::string &errMsg);
112
113 typedef llvm::StringMap StringSet;
114
115 llvm::LLVMContext &Context;
116 llvm::Linker Linker;
117 llvm::TargetMachine *TargetMach;
118 bool EmitDwarfDebugInfo;
119 bool ScopeRestrictionsDone;
120 lto_codegen_model CodeModel;
121 StringSet MustPreserveSymbols;
122 StringSet AsmUndefinedRefs;
123 llvm::MemoryBuffer *NativeObjectFile;
124 std::vector CodegenOptions;
125 std::string MCpu;
126 std::string NativeObjectPath;
127 };
128
129 #endif // LTO_CODE_GENERATOR_H
+0
-908
tools/lto/LTOModule.cpp less more
None //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "LTOModule.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCParser/MCAsmParser.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/MC/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/SourceMgr.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 using namespace llvm;
41
42 static cl::opt
43 EnableFPMAD("enable-fp-mad",
44 cl::desc("Enable less precise MAD instructions to be generated"),
45 cl::init(false));
46
47 static cl::opt
48 DisableFPElim("disable-fp-elim",
49 cl::desc("Disable frame pointer elimination optimization"),
50 cl::init(false));
51
52 static cl::opt
53 EnableUnsafeFPMath("enable-unsafe-fp-math",
54 cl::desc("Enable optimizations that may decrease FP precision"),
55 cl::init(false));
56
57 static cl::opt
58 EnableNoInfsFPMath("enable-no-infs-fp-math",
59 cl::desc("Enable FP math optimizations that assume no +-Infs"),
60 cl::init(false));
61
62 static cl::opt
63 EnableNoNaNsFPMath("enable-no-nans-fp-math",
64 cl::desc("Enable FP math optimizations that assume no NaNs"),
65 cl::init(false));
66
67 static cl::opt
68 EnableHonorSignDependentRoundingFPMath("enable-sign-dependent-rounding-fp-math",
69 cl::Hidden,
70 cl::desc("Force codegen to assume rounding mode can change dynamically"),
71 cl::init(false));
72
73 static cl::opt
74 GenerateSoftFloatCalls("soft-float",
75 cl::desc("Generate software floating point library calls"),
76 cl::init(false));
77
78 static cl::opt
79 FloatABIForCalls("float-abi",
80 cl::desc("Choose float ABI type"),
81 cl::init(FloatABI::Default),
82 cl::values(
83 clEnumValN(FloatABI::Default, "default",
84 "Target default float ABI type"),
85 clEnumValN(FloatABI::Soft, "soft",
86 "Soft float ABI (implied by -soft-float)"),
87 clEnumValN(FloatABI::Hard, "hard",
88 "Hard float ABI (uses FP registers)"),
89 clEnumValEnd));
90
91 static cl::opt
92 FuseFPOps("fp-contract",
93 cl::desc("Enable aggresive formation of fused FP ops"),
94 cl::init(FPOpFusion::Standard),
95 cl::values(
96 clEnumValN(FPOpFusion::Fast, "fast",
97 "Fuse FP ops whenever profitable"),
98 clEnumValN(FPOpFusion::Standard, "on",
99 "Only fuse 'blessed' FP ops."),
100 clEnumValN(FPOpFusion::Strict, "off",
101 "Only fuse FP ops when the result won't be effected."),
102 clEnumValEnd));
103
104 static cl::opt
105 DontPlaceZerosInBSS("nozero-initialized-in-bss",
106 cl::desc("Don't place zero-initialized symbols into bss section"),
107 cl::init(false));
108
109 static cl::opt
110 EnableGuaranteedTailCallOpt("tailcallopt",
111 cl::desc("Turn fastcc calls into tail calls by (potentially) changing ABI."),
112 cl::init(false));
113
114 static cl::opt
115 DisableTailCalls("disable-tail-calls",
116 cl::desc("Never emit tail calls"),
117 cl::init(false));
118
119 static cl::opt
120 OverrideStackAlignment("stack-alignment",
121 cl::desc("Override default stack alignment"),
122 cl::init(0));
123
124 static cl::opt
125 TrapFuncName("trap-func", cl::Hidden,
126 cl::desc("Emit a call to trap function rather than a trap instruction"),
127 cl::init(""));
128
129 static cl::opt
130 EnablePIE("enable-pie",
131 cl::desc("Assume the creation of a position independent executable."),
132 cl::init(false));
133
134 static cl::opt
135 SegmentedStacks("segmented-stacks",
136 cl::desc("Use segmented stacks if possible."),
137 cl::init(false));
138
139 static cl::opt
140 UseInitArray("use-init-array",
141 cl::desc("Use .init_array instead of .ctors."),
142 cl::init(false));
143
144 LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t)
145 : _module(m), _target(t),
146 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL),
147 _mangler(_context, t) {}
148
149 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
150 /// bitcode.
151 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
152 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
153 sys::fs::file_magic::bitcode;
154 }
155
156 bool LTOModule::isBitcodeFile(const char *path) {
157 sys::fs::file_magic type;
158 if (sys::fs::identify_magic(path, type))
159 return false;
160 return type == sys::fs::file_magic::bitcode;
161 }
162
163 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
164 /// LLVM bitcode for the specified triple.
165 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
166 const char *triplePrefix) {
167 MemoryBuffer *buffer = makeBuffer(mem, length);
168 if (!buffer)
169 return false;
170 return isTargetMatch(buffer, triplePrefix);
171 }
172
173 bool LTOModule::isBitcodeFileForTarget(const char *path,
174 const char *triplePrefix) {
175 OwningPtr buffer;
176 if (MemoryBuffer::getFile(path, buffer))
177 return false;
178 return isTargetMatch(buffer.take(), triplePrefix);
179 }
180
181 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
182 /// target triple.
183 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
184 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
185 delete buffer;
186 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
187 }
188
189 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
190 /// the buffer.
191 LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
192 OwningPtr buffer;
193 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
194 errMsg = ec.message();
195 return NULL;
196 }
197 return makeLTOModule(buffer.take(), errMsg);
198 }
199
200 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
201 size_t size, std::string &errMsg) {
202 return makeLTOModule(fd, path, size, 0, errMsg);
203 }
204
205 LTOModule *LTOModule::makeLTOModule(int fd, const char *path,
206 size_t map_size,
207 off_t offset,
208 std::string &errMsg) {
209 OwningPtr buffer;
210 if (error_code ec =
211 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
212 errMsg = ec.message();
213 return NULL;
214 }
215 return makeLTOModule(buffer.take(), errMsg);
216 }
217
218 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
219 std::string &errMsg) {
220 OwningPtr buffer(makeBuffer(mem, length));
221 if (!buffer)
222 return NULL;
223 return makeLTOModule(buffer.take(), errMsg);
224 }
225
226 void LTOModule::getTargetOptions(TargetOptions &Options) {
227 Options.LessPreciseFPMADOption = EnableFPMAD;
228 Options.NoFramePointerElim = DisableFPElim;
229 Options.AllowFPOpFusion = FuseFPOps;
230 Options.UnsafeFPMath = EnableUnsafeFPMath;
231 Options.NoInfsFPMath = EnableNoInfsFPMath;
232 Options.NoNaNsFPMath = EnableNoNaNsFPMath;
233 Options.HonorSignDependentRoundingFPMathOption =
234 EnableHonorSignDependentRoundingFPMath;
235 Options.UseSoftFloat = GenerateSoftFloatCalls;
236 if (FloatABIForCalls != FloatABI::Default)
237 Options.FloatABIType = FloatABIForCalls;
238 Options.NoZerosInBSS = DontPlaceZerosInBSS;
239 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
240 Options.DisableTailCalls = DisableTailCalls;
241 Options.StackAlignmentOverride = OverrideStackAlignment;
242 Options.TrapFuncName = TrapFuncName;
243 Options.PositionIndependentExecutable = EnablePIE;
244 Options.EnableSegmentedStacks = SegmentedStacks;
245 Options.UseInitArray = UseInitArray;
246 }
247
248 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
249 std::string &errMsg) {
250 static bool Initialized = false;
251 if (!Initialized) {
252 InitializeAllTargets();
253 InitializeAllTargetMCs();
254 InitializeAllAsmParsers();
255 Initialized = true;
256 }
257
258 // parse bitcode buffer
259 OwningPtr m(getLazyBitcodeModule(buffer, getGlobalContext(),
260 &errMsg));
261 if (!m) {
262 delete buffer;
263 return NULL;
264 }
265
266 std::string TripleStr = m->getTargetTriple();
267 if (TripleStr.empty())
268 TripleStr = sys::getDefaultTargetTriple();
269 llvm::Triple Triple(TripleStr);
270
271 // find machine architecture for this module
272 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
273 if (!march)
274 return NULL;
275
276 // construct LTOModule, hand over ownership of module and target
277 SubtargetFeatures Features;
278 Features.getDefaultSubtargetFeatures(Triple);
279 std::string FeatureStr = Features.getString();
280 // Set a default CPU for Darwin triples.
281 std::string CPU;
282 if (Triple.isOSDarwin()) {
283 if (Triple.getArch() == llvm::Triple::x86_64)
284 CPU = "core2";
285 else if (Triple.getArch() == llvm::Triple::x86)
286 CPU = "yonah";
287 }
288 TargetOptions Options;
289 getTargetOptions(Options);
290 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
291 Options);
292 LTOModule *Ret = new LTOModule(m.take(), target);
293 if (Ret->parseSymbols(errMsg)) {
294 delete Ret;
295 return NULL;
296 }
297
298 return Ret;
299 }
300
301 /// makeBuffer - Create a MemoryBuffer from a memory range.
302 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
303 const char *startPtr = (const char*)mem;
304 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false);
305 }
306
307 /// objcClassNameFromExpression - Get string that the data pointer points to.
308 bool
309 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
310 if (const ConstantExpr *ce = dyn_cast(c)) {
311 Constant *op = ce->getOperand(0);
312 if (GlobalVariable *gvn = dyn_cast(op)) {
313 Constant *cn = gvn->getInitializer();
314 if (ConstantDataArray *ca = dyn_cast(cn)) {
315 if (ca->isCString()) {
316 name = ".objc_class_name_" + ca->getAsCString().str();
317 return true;
318 }
319 }
320 }
321 }
322 return false;
323 }
324
325 /// addObjCClass - Parse i386/ppc ObjC class data structure.
326 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
327 const ConstantStruct *c = dyn_cast(clgv->getInitializer());
328 if (!c) return;
329
330 // second slot in __OBJC,__class is pointer to superclass name
331 std::string superclassName;
332 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
333 NameAndAttributes info;
334 StringMap::value_type &entry =
335 _undefines.GetOrCreateValue(superclassName);
336 if (!entry.getValue().name) {
337 const char *symbolName = entry.getKey().data();
338 info.name = symbolName;
339 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
340 info.isFunction = false;
341 info.symbol = clgv;
342 entry.setValue(info);
343 }
344 }
345
346 // third slot in __OBJC,__class is pointer to class name
347 std::string className;
348 if (objcClassNameFromExpression(c->getOperand(2), className)) {
349 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
350 entry.setValue(1);
351
352 NameAndAttributes info;
353 info.name = entry.getKey().data();
354 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
355 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
356 info.isFunction = false;
357 info.symbol = clgv;
358 _symbols.push_back(info);
359 }
360 }
361
362 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
363 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
364 const ConstantStruct *c = dyn_cast(clgv->getInitializer());
365 if (!c) return;
366
367 // second slot in __OBJC,__category is pointer to target class name
368 std::string targetclassName;
369 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
370 return;
371
372 NameAndAttributes info;
373 StringMap::value_type &entry =
374 _undefines.GetOrCreateValue(targetclassName);
375
376 if (entry.getValue().name)
377 return;
378
379 const char *symbolName = entry.getKey().data();
380 info.name = symbolName;
381 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
382 info.isFunction = false;
383 info.symbol = clgv;
384 entry.setValue(info);
385 }
386
387 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
388 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
389 std::string targetclassName;
390 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
391 return;
392
393 NameAndAttributes info;
394 StringMap::value_type &entry =
395 _undefines.GetOrCreateValue(targetclassName);
396 if (entry.getValue().name)
397 return;
398
399 const char *symbolName = entry.getKey().data();
400 info.name = symbolName;
401 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
402 info.isFunction = false;
403 info.symbol = clgv;
404 entry.setValue(info);
405 }
406
407 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
408 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
409 // Add to list of defined symbols.
410 addDefinedSymbol(v, false);
411
412 if (!v->hasSection() /* || !isTargetDarwin */)
413 return;
414
415 // Special case i386/ppc ObjC data structures in magic sections:
416 // The issue is that the old ObjC object format did some strange
417 // contortions to avoid real linker symbols. For instance, the
418 // ObjC class data structure is allocated statically in the executable
419 // that defines that class. That data structures contains a pointer to
420 // its superclass. But instead of just initializing that part of the
421 // struct to the address of its superclass, and letting the static and
422 // dynamic linkers do the rest, the runtime works by having that field
423 // instead point to a C-string that is the name of the superclass.
424 // At runtime the objc initialization updates that pointer and sets
425 // it to point to the actual super class. As far as the linker
426 // knows it is just a pointer to a string. But then someone wanted the
427 // linker to issue errors at build time if the superclass was not found.
428 // So they figured out a way in mach-o object format to use an absolute
429 // symbols (.objc_class_name_Foo = 0) and a floating reference
430 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
431 // a class was missing.
432 // The following synthesizes the implicit .objc_* symbols for the linker
433 // from the ObjC data structures generated by the front end.
434
435 // special case if this data blob is an ObjC class definition
436 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
437 if (const GlobalVariable *gv = dyn_cast(v)) {
438 addObjCClass(gv);
439 }
440 }
441
442 // special case if this data blob is an ObjC category definition
443 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
444 if (const GlobalVariable *gv = dyn_cast(v)) {
445 addObjCCategory(gv);
446 }
447 }
448
449 // special case if this data blob is the list of referenced classes
450 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
451 if (const GlobalVariable *gv = dyn_cast(v)) {
452 addObjCClassRef(gv);
453 }
454 }
455 }
456
457 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
458 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
459 // add to list of defined symbols
460 addDefinedSymbol(f, true);
461 }
462
463 /// addDefinedSymbol - Add a defined symbol to the list.
464 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
465 // ignore all llvm.* symbols
466 if (def->getName().startswith("llvm."))
467 return;
468
469 // string is owned by _defines
470 SmallString<64> Buffer;
471 _mangler.getNameWithPrefix(Buffer, def, false);
472
473 // set alignment part log2() can have rounding errors
474 uint32_t align = def->getAlignment();
475 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0;
476
477 // set permissions part
478 if (isFunction) {
479 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
480 } else {
481 const GlobalVariable *gv = dyn_cast(def);
482 if (gv && gv->isConstant())
483 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
484 else
485 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
486 }
487
488 // set definition part
489 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
490 def->hasLinkerPrivateWeakLinkage())
491 attr |= LTO_SYMBOL_DEFINITION_WEAK;
492 else if (def->hasCommonLinkage())
493 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
494 else
495 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
496
497 // set scope part
498 if (def->hasHiddenVisibility())
499 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
500 else if (def->hasProtectedVisibility())
501 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
502 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
503 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
504 def->hasLinkerPrivateWeakLinkage())
505 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
506 else if (def->hasLinkOnceODRAutoHideLinkage())
507 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
508 else
509 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
510
511 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
512 entry.setValue(1);
513
514 // fill information structure
515 NameAndAttributes info;
516 StringRef Name = entry.getKey();
517 info.name = Name.data();
518 assert(info.name[Name.size()] == '\0');
519 info.attributes = attr;
520 info.isFunction = isFunction;
521 info.symbol = def;
522
523 // add to table of symbols
524 _symbols.push_back(info);
525 }
526
527 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
528 /// defined list.
529 void LTOModule::addAsmGlobalSymbol(const char *name,
530 lto_symbol_attributes scope) {
531 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
532
533 // only add new define if not already defined
534 if (entry.getValue())
535 return;
536
537 entry.setValue(1);
538
539 NameAndAttributes &info = _undefines[entry.getKey().data()];
540
541 if (info.symbol == 0) {
542 // FIXME: This is trying to take care of module ASM like this:
543 //
544 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
545 //
546 // but is gross and its mother dresses it funny. Have the ASM parser give us
547 // more details for this type of situation so that we're not guessing so
548 // much.
549
550 // fill information structure
551 info.name = entry.getKey().data();
552 info.attributes =
553 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
554 info.isFunction = false;
555 info.symbol = 0;
556
557 // add to table of symbols
558 _symbols.push_back(info);
559 return;
560 }
561
562 if (info.isFunction)
563 addDefinedFunctionSymbol(cast(info.symbol));
564 else
565 addDefinedDataSymbol(info.symbol);
566
567 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
568 _symbols.back().attributes |= scope;
569 }
570
571 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
572 /// undefined list.
573 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
574 StringMap::value_type &entry =
575 _undefines.GetOrCreateValue(name);
576
577 _asm_undefines.push_back(entry.getKey().data());
578
579 // we already have the symbol
580 if (entry.getValue().name)
581 return;
582
583 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;;
584 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
585 NameAndAttributes info;
586 info.name = entry.getKey().data();
587 info.attributes = attr;
588 info.isFunction = false;
589 info.symbol = 0;
590
591 entry.setValue(info);
592 }
593
594 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
595 /// list to be resolved later.
596 void
597 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
598 // ignore all llvm.* symbols
599 if (decl->getName().startswith("llvm."))
600 return;
601
602 // ignore all aliases
603 if (isa(decl))
604 return;
605
606 SmallString<64> name;
607 _mangler.getNameWithPrefix(name, decl, false);
608
609 StringMap::value_type &entry =
610 _undefines.GetOrCreateValue(name);
611
612 // we already have the symbol
613 if (entry.getValue().name)
614 return;
615
616 NameAndAttributes info;
617
618 info.name = entry.getKey().data();
619
620 if (decl->hasExternalWeakLinkage())
621 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
622 else
623 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
624
625 info.isFunction = isFunc;
626 info.symbol = decl;
627
628 entry.setValue(info);
629 }
630
631 namespace {
632 class RecordStreamer : public MCStreamer {
633 public:
634 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used };
635
636 private:
637 StringMap Symbols;
638
639 void markDefined(const MCSymbol &Symbol) {
640 State &S = Symbols[Symbol.getName()];
641 switch (S) {
642 case DefinedGlobal:
643 case Global:
644 S = DefinedGlobal;
645 break;
646 case NeverSeen:
647 case Defined:
648 case Used:
649 S = Defined;
650 break;
651 }
652 }
653 void markGlobal(const MCSymbol &Symbol) {
654 State &S = Symbols[Symbol.getName()];
655 switch (S) {
656 case DefinedGlobal:
657 case Defined:
658 S = DefinedGlobal;
659 break;
660
661 case NeverSeen:
662 case Global:
663 case Used:
664 S = Global;
665 break;
666 }
667 }
668 void markUsed(const MCSymbol &Symbol) {
669 State &S = Symbols[Symbol.getName()];
670 switch (S) {
671 case DefinedGlobal:
672 case Defined:
673 case Global:
674 break;
675
676 case NeverSeen:
677 case Used:
678 S = Used;
679 break;
680 }
681 }
682
683 // FIXME: mostly copied for the obj streamer.
684 void AddValueSymbols(const MCExpr *Value) {
685 switch (Value->getKind()) {
686 case MCExpr::Target:
687 // FIXME: What should we do in here?
688 break;
689
690 case MCExpr::Constant:
691 break;
692
693 case MCExpr::Binary: {
694 const MCBinaryExpr *BE = cast(Value);
695 AddValueSymbols(BE->getLHS());
696 AddValueSymbols(BE->getRHS());
697 break;
698 }
699
700 case MCExpr::SymbolRef:
701 markUsed(cast(Value)->getSymbol());
702 break;
703
704 case MCExpr::Unary:
705 AddValueSymbols(cast(Value)->getSubExpr());
706 break;
707 }
708 }
709
710 public:
711 typedef StringMap::const_iterator const_iterator;
712
713 const_iterator begin() {
714 return Symbols.begin();
715 }
716
717 const_iterator end() {
718 return Symbols.end();
719 }
720
721 RecordStreamer(MCContext &Context)
722 : MCStreamer(SK_RecordStreamer, Context) {}
723
724 virtual void EmitInstruction(const MCInst &Inst) {
725 // Scan for values.
726 for (unsigned i = Inst.getNumOperands(); i--; )
727 if (Inst.getOperand(i).isExpr())
728 AddValueSymbols(Inst.getOperand(i).getExpr());
729 }
730 virtual void EmitLabel(MCSymbol *Symbol) {
731 Symbol->setSection(*getCurrentSection().first);
732 markDefined(*Symbol);
733 }
734 virtual void EmitDebugLabel(MCSymbol *Symbol) {
735 EmitLabel(Symbol);
736 }
737 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
738 // FIXME: should we handle aliases?
739 markDefined(*Symbol);
740 }
741 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) {
742 if (Attribute == MCSA_Global)
743 markGlobal(*Symbol);
744 return true;
745 }
746 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
747 uint64_t Size , unsigned ByteAlignment) {
748 markDefined(*Symbol);
749 }
750 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
751 unsigned ByteAlignment) {
752 markDefined(*Symbol);
753 }
754
755 virtual void EmitBundleAlignMode(unsigned AlignPow2) {}
756 virtual void EmitBundleLock(bool AlignToEnd) {}
757 virtual void EmitBundleUnlock() {}
758
759 // Noop calls.
760 virtual void ChangeSection(const MCSection *Section,
761 const MCExpr *Subsection) {}
762 virtual void InitToTextSection() {}
763 virtual void InitSections() {}
764 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {}
765 virtual void EmitThumbFunc(MCSymbol *Func) {}
766 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {}
767 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {}
768 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {}
769 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {}
770 virtual void EmitCOFFSymbolType(int Type) {}
771 virtual void EndCOFFSymbolDef() {}
772 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {}
773 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
774 unsigned ByteAlignment) {}
775 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
776 uint64_t Size, unsigned ByteAlignment) {}
777 virtual void EmitBytes(StringRef Data) {}
778 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {}
779 virtual void EmitULEB128Value(const MCExpr *Value) {}
780 virtual void EmitSLEB128Value(const MCExpr *Value) {}
781 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
782 unsigned ValueSize,
783 unsigned MaxBytesToEmit) {}
784 virtual void EmitCodeAlignment(unsigned ByteAlignment,
785 unsigned MaxBytesToEmit) {}
786 virtual bool EmitValueToOffset(const MCExpr *Offset,
787 unsigned char Value ) { return false; }
788 virtual void EmitFileDirective(StringRef Filename) {}
789 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
790 const MCSymbol *LastLabel,
791 const MCSymbol *Label,
792 unsigned PointerSize) {}
793 virtual void FinishImpl() {}
794 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
795 RecordProcEnd(Frame);
796 }
797
798 static bool classof(const MCStreamer *S) {
799 return S->getKind() == SK_RecordStreamer;
800 }
801 };
802 } // end anonymous namespace
803
804 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
805 /// defined or undefined lists.
806 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
807 const std::string &inlineAsm = _module->getModuleInlineAsm();
808 if (inlineAsm.empty())
809 return false;
810
811 OwningPtr Streamer(new RecordStreamer(_context));
812 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
813 SourceMgr SrcMgr;
814 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
815 OwningPtr Parser(createMCAsmParser(SrcMgr,
816 _context, *Streamer,
817 *_target->getMCAsmInfo()));
818 const Target &T = _target->getTarget();
819 OwningPtr MCII(T.createMCInstrInfo());
820 OwningPtr
821 STI(T.createMCSubtargetInfo(_target->getTargetTriple(),
822 _target->getTargetCPU(),
823 _target->getTargetFeatureString()));
824 OwningPtr TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII));
825 if (!TAP) {
826 errMsg = "target " + std::string(T.getName()) +
827 " does not define AsmParser.";
828 return true;
829 }
830
831 Parser->setTargetParser(*TAP);
832 if (Parser->Run(false))
833 return true;
834
835 for (RecordStreamer::const_iterator i = Streamer->begin(),
836 e = Streamer->end(); i != e; ++i) {
837 StringRef Key = i->first();
838 RecordStreamer::State Value = i->second;
839 if (Value == RecordStreamer::DefinedGlobal)
840 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
841 else if (Value == RecordStreamer::Defined)
842 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
843 else if (Value == RecordStreamer::Global ||
844 Value == RecordStreamer::Used)
845 addAsmGlobalSymbolUndef(Key.data());
846 }
847
848 return false;
849 }
850
851 /// isDeclaration - Return 'true' if the global value is a declaration.
852 static bool isDeclaration(const GlobalValue &V) {
853 if (V.hasAvailableExternallyLinkage())
854 return true;
855
856 if (V.isMaterializable())
857 return false;
858
859 return V.isDeclaration();
860 }
861
862 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
863 /// them to either the defined or undefined lists.
864 bool LTOModule::parseSymbols(std::string &errMsg) {
865 // add functions
866 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
867 if (isDeclaration(*f))
868 addPotentialUndefinedSymbol(f, true);
869 else
870 addDefinedFunctionSymbol(f);
871 }
872
873 // add data
874 for (Module::global_iterator v = _module->global_begin(),
875 e = _module->global_end(); v != e; ++v) {
876 if (isDeclaration(*v))
877 addPotentialUndefinedSymbol(v, false);
878 else
879 addDefinedDataSymbol(v);
880 }
881
882 // add asm globals
883 if (addAsmGlobalSymbols(errMsg))
884 return true;
885
886 // add aliases
887 for (Module::alias_iterator a = _module->alias_begin(),
888 e = _module->alias_end(); a != e; ++a) {
889 if (isDeclaration(*a->getAliasedGlobal()))
890 // Is an alias to a declaration.
891 addPotentialUndefinedSymbol(a, false);
892 else
893 addDefinedDataSymbol(a);
894 }
895
896 // make symbols for all undefines
897 for (StringMap::iterator u =_undefines.begin(),
898 e = _undefines.end(); u != e; ++u) {
899 // If this symbol also has a definition, then don't make an undefine because
900 // it is a tentative definition.
901 if (_defines.count(u->getKey())) continue;
902 NameAndAttributes info = u->getValue();
903 _symbols.push_back(info);
904 }
905
906 return false;
907 }
+0
-190
tools/lto/LTOModule.h less more
None //===-LTOModule.h - LLVM Link Time Optimizer ------------------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the LTOModule class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #ifndef LTO_MODULE_H
14 #define LTO_MODULE_H
15
16 #include "llvm-c/lto.h"
17 #include "llvm/ADT/OwningPtr.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/Target/Mangler.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include
24 #include
25
26 // Forward references to llvm classes.
27 namespace llvm {
28 class Function;
29 class GlobalValue;
30 class MemoryBuffer;
31 class TargetOptions;
32 class Value;
33 }
34
35 //===----------------------------------------------------------------------===//
36 /// LTOModule - C++ class which implements the opaque lto_module_t type.
37 ///
38 struct LTOModule {
39 private:
40 typedef llvm::StringMap StringSet;
41
42 struct NameAndAttributes {
43 const char *name;
44 uint32_t attributes;
45 bool isFunction;
46 const llvm::GlobalValue *symbol;
47 };
48
49 llvm::OwningPtr _module;
50 llvm::OwningPtr _target;
51 std::vector _symbols;
52
53 // _defines and _undefines only needed to disambiguate tentative definitions
54 StringSet _defines;
55 llvm::StringMap _undefines;
56 std::vector _asm_undefines;
57 llvm::MCContext _context;
58
59 // Use mangler to add GlobalPrefix to names to match linker names.
60 llvm::Mangler _mangler;
61
62 LTOModule(llvm::Module *m, llvm::TargetMachine *t);
63 public:
64 /// isBitcodeFile - Returns 'true' if the file or memory contents is LLVM
65 /// bitcode.
66 static bool isBitcodeFile(const void *mem, size_t length);
67 static bool isBitcodeFile(const char *path);
68
69 /// isBitcodeFileForTarget - Returns 'true' if the file or memory contents
70 /// is LLVM bitcode for the specified triple.
71 static bool isBitcodeFileForTarget(const void *mem,
72 size_t length,
73 const char *triplePrefix);
74 static bool isBitcodeFileForTarget(const char *path,
75 const char *triplePrefix);
76
77 /// makeLTOModule - Create an LTOModule. N.B. These methods take ownership
78 /// of the buffer.
79 static LTOModule *makeLTOModule(const char* path,
80 std::string &errMsg);
81 static LTOModule *makeLTOModule(int fd, const char *path,
82 size_t size, std::string &errMsg);
83 static LTOModule *makeLTOModule(int fd, const char *path,
84 size_t map_size,
85 off_t offset,
86 std::string& errMsg);
87 static LTOModule *makeLTOModule(const void *mem, size_t length,
88 std::string &err