]> git.saurik.com Git - apple/ld64.git/blob - src/ld/parsers/lto_file.cpp
ld64-224.1.tar.gz
[apple/ld64.git] / src / ld / parsers / lto_file.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2006-2010 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 #ifndef __LTO_READER_H__
26 #define __LTO_READER_H__
27
28 #include <stdlib.h>
29 #include <sys/param.h>
30 #include <sys/fcntl.h>
31 #include <sys/stat.h>
32 #include <errno.h>
33 #include <pthread.h>
34 #include <mach-o/dyld.h>
35 #include <vector>
36 #include <unordered_set>
37 #include <unordered_map>
38
39 #include "MachOFileAbstraction.hpp"
40 #include "Architectures.hpp"
41 #include "ld.hpp"
42 #include "macho_relocatable_file.h"
43 #include "lto_file.h"
44
45 // #defines are a work around for <rdar://problem/8760268>
46 #define __STDC_LIMIT_MACROS 1
47 #define __STDC_CONSTANT_MACROS 1
48 #include "llvm-c/lto.h"
49
50
51 namespace lto {
52
53
54 //
55 // ld64 only tracks non-internal symbols from an llvm bitcode file.
56 // We model this by having an InternalAtom which represent all internal functions and data.
57 // All non-interal symbols from a bitcode file are represented by an Atom
58 // and each Atom has a reference to the InternalAtom. The InternalAtom
59 // also has references to each symbol external to the bitcode file.
60 //
61 class InternalAtom : public ld::Atom
62 {
63 public:
64 InternalAtom(class File& f);
65 // overrides of ld::Atom
66 virtual ld::File* file() const { return &_file; }
67 virtual const char* name() const { return "import-atom"; }
68 virtual uint64_t size() const { return 0; }
69 virtual uint64_t objectAddress() const { return 0; }
70 virtual void copyRawContent(uint8_t buffer[]) const { }
71 virtual void setScope(Scope) { }
72 virtual ld::Fixup::iterator fixupsBegin() const { return &_undefs[0]; }
73 virtual ld::Fixup::iterator fixupsEnd() const { return &_undefs[_undefs.size()]; }
74
75 // for adding references to symbols outside bitcode file
76 void addReference(const char* nm)
77 { _undefs.push_back(ld::Fixup(0, ld::Fixup::k1of1,
78 ld::Fixup::kindNone, false, nm)); }
79 private:
80
81 ld::File& _file;
82 mutable std::vector<ld::Fixup> _undefs;
83 };
84
85
86 //
87 // LLVM bitcode file
88 //
89 class File : public ld::relocatable::File
90 {
91 public:
92 File(const char* path, time_t mTime, ld::File::Ordinal ordinal,
93 const uint8_t* content, uint32_t contentLength, cpu_type_t arch);
94 virtual ~File();
95
96 // overrides of ld::File
97 virtual bool forEachAtom(ld::File::AtomHandler&) const;
98 virtual bool justInTimeforEachAtom(const char* name, ld::File::AtomHandler&) const
99 { return false; }
100 virtual uint32_t cpuSubType() const { return _cpuSubType; }
101
102 // overrides of ld::relocatable::File
103 virtual DebugInfoKind debugInfo() const { return _debugInfo; }
104 virtual const char* debugInfoPath() const { return _debugInfoPath; }
105 virtual time_t debugInfoModificationTime() const
106 { return _debugInfoModTime; }
107 virtual const std::vector<ld::relocatable::File::Stab>* stabs() const { return NULL; }
108 virtual bool canScatterAtoms() const { return true; }
109 virtual LinkerOptionsList* linkerOptions() const { return NULL; }
110
111
112 lto_module_t module() { return _module; }
113 class InternalAtom& internalAtom() { return _internalAtom; }
114 void setDebugInfo(ld::relocatable::File::DebugInfoKind k,
115 const char* pth, time_t modTime, uint32_t subtype)
116 { _debugInfo = k;
117 _debugInfoPath = pth;
118 _debugInfoModTime = modTime;
119 _cpuSubType = subtype;}
120
121 private:
122 friend class Atom;
123 friend class InternalAtom;
124 friend class Parser;
125
126 cpu_type_t _architecture;
127 class InternalAtom _internalAtom;
128 class Atom* _atomArray;
129 uint32_t _atomArrayCount;
130 lto_module_t _module;
131 const char* _debugInfoPath;
132 time_t _debugInfoModTime;
133 ld::Section _section;
134 ld::Fixup _fixupToInternal;
135 ld::relocatable::File::DebugInfoKind _debugInfo;
136 uint32_t _cpuSubType;
137 };
138
139 //
140 // Atom acts as a proxy Atom for the symbols that are exported by LLVM bitcode file. Initially,
141 // Reader creates Atoms to allow linker proceed with usual symbol resolution phase. After
142 // optimization is performed, real Atoms are created for these symobls. However these real Atoms
143 // are not inserted into global symbol table. Atom holds real Atom and forwards appropriate
144 // methods to real atom.
145 //
146 class Atom : public ld::Atom
147 {
148 public:
149 Atom(File& f, const char* name, ld::Atom::Scope s,
150 ld::Atom::Definition d, ld::Atom::Combine c, ld::Atom::Alignment a, bool ah);
151
152 // overrides of ld::Atom
153 virtual ld::File* file() const { return &_file; }
154 virtual const char* translationUnitSource() const
155 { return (_compiledAtom ? _compiledAtom->translationUnitSource() : NULL); }
156 virtual const char* name() const { return _name; }
157 virtual uint64_t size() const { return (_compiledAtom ? _compiledAtom->size() : 0); }
158 virtual uint64_t objectAddress() const { return (_compiledAtom ? _compiledAtom->objectAddress() : 0); }
159 virtual void copyRawContent(uint8_t buffer[]) const
160 { if (_compiledAtom) _compiledAtom->copyRawContent(buffer); }
161 virtual const uint8_t* rawContentPointer() const
162 { return (_compiledAtom ? _compiledAtom->rawContentPointer() : NULL); }
163 virtual unsigned long contentHash(const class ld::IndirectBindingTable& ibt) const
164 { return (_compiledAtom ? _compiledAtom->contentHash(ibt) : 0); }
165 virtual bool canCoalesceWith(const ld::Atom& rhs, const class ld::IndirectBindingTable& ibt) const
166 { return (_compiledAtom ? _compiledAtom->canCoalesceWith(rhs,ibt) : false); }
167 virtual ld::Fixup::iterator fixupsBegin() const
168 { return (_compiledAtom ? _compiledAtom->fixupsBegin() : (ld::Fixup*)&_file._fixupToInternal); }
169 virtual ld::Fixup::iterator fixupsEnd() const
170 { return (_compiledAtom ? _compiledAtom->fixupsEnd() : &((ld::Fixup*)&_file._fixupToInternal)[1]); }
171 virtual ld::Atom::UnwindInfo::iterator beginUnwind() const
172 { return (_compiledAtom ? _compiledAtom->beginUnwind() : NULL); }
173 virtual ld::Atom::UnwindInfo::iterator endUnwind() const
174 { return (_compiledAtom ? _compiledAtom->endUnwind() : NULL); }
175 virtual ld::Atom::LineInfo::iterator beginLineInfo() const
176 { return (_compiledAtom ? _compiledAtom->beginLineInfo() : NULL); }
177 virtual ld::Atom::LineInfo::iterator endLineInfo() const
178 { return (_compiledAtom ? _compiledAtom->endLineInfo() : NULL); }
179
180 const ld::Atom* compiledAtom() { return _compiledAtom; }
181 void setCompiledAtom(const ld::Atom& atom);
182
183 private:
184
185 File& _file;
186 const char* _name;
187 const ld::Atom* _compiledAtom;
188 };
189
190
191
192
193
194
195
196 class Parser
197 {
198 public:
199 static bool validFile(const uint8_t* fileContent, uint64_t fileLength, cpu_type_t architecture, cpu_subtype_t subarch);
200 static const char* fileKind(const uint8_t* fileContent, uint64_t fileLength);
201 static File* parse(const uint8_t* fileContent, uint64_t fileLength, const char* path,
202 time_t modTime, ld::File::Ordinal ordinal, cpu_type_t architecture, cpu_subtype_t subarch, bool logAllFiles);
203 static bool libLTOisLoaded() { return (::lto_get_version() != NULL); }
204 static bool optimize( const std::vector<const ld::Atom*>& allAtoms,
205 ld::Internal& state,
206 const OptimizeOptions& options,
207 ld::File::AtomHandler& handler,
208 std::vector<const ld::Atom*>& newAtoms,
209 std::vector<const char*>& additionalUndefines);
210
211 static const char* ltoVersion() { return ::lto_get_version(); }
212
213 private:
214 static const char* tripletPrefixForArch(cpu_type_t arch);
215 static ld::relocatable::File* parseMachOFile(const uint8_t* p, size_t len, const OptimizeOptions& options);
216
217 typedef std::unordered_set<const char*, ld::CStringHash, ld::CStringEquals> CStringSet;
218 typedef std::unordered_map<const char*, Atom*, ld::CStringHash, ld::CStringEquals> CStringToAtom;
219
220 class AtomSyncer : public ld::File::AtomHandler {
221 public:
222 AtomSyncer(std::vector<const char*>& a, std::vector<const ld::Atom*>&na,
223 CStringToAtom la, CStringToAtom dla, const OptimizeOptions& options) :
224 _options(options), _additionalUndefines(a), _newAtoms(na), _llvmAtoms(la), _deadllvmAtoms(dla) { }
225 virtual void doAtom(const class ld::Atom&);
226 virtual void doFile(const class ld::File&) { }
227
228 const OptimizeOptions& _options;
229 std::vector<const char*>& _additionalUndefines;
230 std::vector<const ld::Atom*>& _newAtoms;
231 CStringToAtom _llvmAtoms;
232 CStringToAtom _deadllvmAtoms;
233 };
234
235 static std::vector<File*> _s_files;
236 };
237
238 std::vector<File*> Parser::_s_files;
239
240
241 bool Parser::validFile(const uint8_t* fileContent, uint64_t fileLength, cpu_type_t architecture, cpu_subtype_t subarch)
242 {
243 for (const ArchInfo* t=archInfoArray; t->archName != NULL; ++t) {
244 if ( (architecture == t->cpuType) && (!(t->isSubType) || (subarch == t->cpuSubType)) ) {
245 bool result = ::lto_module_is_object_file_in_memory_for_target(fileContent, fileLength, t->llvmTriplePrefix);
246 if ( !result ) {
247 // <rdar://problem/8434487> LTO only supports thumbv7 not armv7
248 if ( t->llvmTriplePrefixAlt[0] != '\0' ) {
249 result = ::lto_module_is_object_file_in_memory_for_target(fileContent, fileLength, t->llvmTriplePrefixAlt);
250 }
251 }
252 return result;
253 }
254 }
255 return false;
256 }
257
258 const char* Parser::fileKind(const uint8_t* p, uint64_t fileLength)
259 {
260 if ( (p[0] == 0xDE) && (p[1] == 0xC0) && (p[2] == 0x17) && (p[3] == 0x0B) ) {
261 cpu_type_t arch = LittleEndian::get32(*((uint32_t*)(&p[16])));
262 for (const ArchInfo* t=archInfoArray; t->archName != NULL; ++t) {
263 if ( arch == t->cpuType ) {
264 if ( t->isSubType ) {
265 if ( ::lto_module_is_object_file_in_memory_for_target(p, fileLength, t->llvmTriplePrefix) )
266 return t->archName;
267 }
268 else {
269 return t->archName;
270 }
271 }
272 }
273 return "unknown bitcode architecture";
274 }
275 return NULL;
276 }
277
278 File* Parser::parse(const uint8_t* fileContent, uint64_t fileLength, const char* path, time_t modTime, ld::File::Ordinal ordinal,
279 cpu_type_t architecture, cpu_subtype_t subarch, bool logAllFiles)
280 {
281 File* f = new File(path, modTime, ordinal, fileContent, fileLength, architecture);
282 _s_files.push_back(f);
283 if ( logAllFiles )
284 printf("%s\n", path);
285 return f;
286 }
287
288
289 ld::relocatable::File* Parser::parseMachOFile(const uint8_t* p, size_t len, const OptimizeOptions& options)
290 {
291 mach_o::relocatable::ParserOptions objOpts;
292 objOpts.architecture = options.arch;
293 objOpts.objSubtypeMustMatch = false;
294 objOpts.logAllFiles = false;
295 objOpts.warnUnwindConversionProblems = options.needsUnwindInfoSection;
296 objOpts.keepDwarfUnwind = options.keepDwarfUnwind;
297 objOpts.forceDwarfConversion = false;
298 objOpts.subType = 0;
299
300 // mach-o parsing is done in-memory, but need path for debug notes
301 const char* path = "/tmp/lto.o";
302 time_t modTime = 0;
303 if ( options.tmpObjectFilePath != NULL ) {
304 path = options.tmpObjectFilePath;
305 struct stat statBuffer;
306 if ( stat(options.tmpObjectFilePath, &statBuffer) == 0 )
307 modTime = statBuffer.st_mtime;
308 }
309
310 ld::relocatable::File* result = mach_o::relocatable::parse(p, len, path, modTime, ld::File::Ordinal::LTOOrdinal(), objOpts);
311 if ( result != NULL )
312 return result;
313 throw "LLVM LTO, file is not of required architecture";
314 }
315
316
317
318 File::File(const char* pth, time_t mTime, ld::File::Ordinal ordinal, const uint8_t* content, uint32_t contentLength, cpu_type_t arch)
319 : ld::relocatable::File(pth,mTime,ordinal), _architecture(arch), _internalAtom(*this),
320 _atomArray(NULL), _atomArrayCount(0), _module(NULL), _debugInfoPath(pth),
321 _section("__TEXT_", "__tmp_lto", ld::Section::typeTempLTO),
322 _fixupToInternal(0, ld::Fixup::k1of1, ld::Fixup::kindNone, &_internalAtom),
323 _debugInfo(ld::relocatable::File::kDebugInfoNone), _cpuSubType(0)
324 {
325 const bool log = false;
326
327 // create llvm module
328 _module = ::lto_module_create_from_memory(content, contentLength);
329 if ( _module == NULL )
330 throwf("could not parse object file %s: '%s', using libLTO version '%s'", pth, ::lto_get_error_message(), ::lto_get_version());
331
332 if ( log ) fprintf(stderr, "bitcode file: %s\n", pth);
333
334 // create atom for each global symbol in module
335 uint32_t count = ::lto_module_get_num_symbols(_module);
336 _atomArray = (Atom*)malloc(sizeof(Atom)*count);
337 for (uint32_t i=0; i < count; ++i) {
338 const char* name = ::lto_module_get_symbol_name(_module, i);
339 lto_symbol_attributes attr = lto_module_get_symbol_attribute(_module, i);
340
341 // <rdar://problem/6378110> LTO doesn't like dtrace symbols
342 // ignore dtrace static probes for now
343 // later when codegen is done and a mach-o file is produces the probes will be processed
344 if ( (strncmp(name, "___dtrace_probe$", 16) == 0) || (strncmp(name, "___dtrace_isenabled$", 20) == 0) )
345 continue;
346
347 ld::Atom::Definition def;
348 ld::Atom::Combine combine = ld::Atom::combineNever;
349 switch ( attr & LTO_SYMBOL_DEFINITION_MASK ) {
350 case LTO_SYMBOL_DEFINITION_REGULAR:
351 def = ld::Atom::definitionRegular;
352 break;
353 case LTO_SYMBOL_DEFINITION_TENTATIVE:
354 def = ld::Atom::definitionTentative;
355 break;
356 case LTO_SYMBOL_DEFINITION_WEAK:
357 def = ld::Atom::definitionRegular;
358 combine = ld::Atom::combineByName;
359 break;
360 case LTO_SYMBOL_DEFINITION_UNDEFINED:
361 case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
362 def = ld::Atom::definitionProxy;
363 break;
364 default:
365 throwf("unknown definition kind for symbol %s in bitcode file %s", name, pth);
366 }
367
368 // make LLVM atoms for definitions and a reference for undefines
369 if ( def != ld::Atom::definitionProxy ) {
370 ld::Atom::Scope scope;
371 bool autohide = false;
372 switch ( attr & LTO_SYMBOL_SCOPE_MASK) {
373 case LTO_SYMBOL_SCOPE_INTERNAL:
374 scope = ld::Atom::scopeTranslationUnit;
375 break;
376 case LTO_SYMBOL_SCOPE_HIDDEN:
377 scope = ld::Atom::scopeLinkageUnit;
378 break;
379 case LTO_SYMBOL_SCOPE_DEFAULT:
380 scope = ld::Atom::scopeGlobal;
381 break;
382 #if LTO_API_VERSION >= 4
383 case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
384 scope = ld::Atom::scopeGlobal;
385 autohide = true;
386 break;
387 #endif
388 default:
389 throwf("unknown scope for symbol %s in bitcode file %s", name, pth);
390 }
391 // only make atoms for non-internal symbols
392 if ( scope == ld::Atom::scopeTranslationUnit )
393 continue;
394 uint8_t alignment = (attr & LTO_SYMBOL_ALIGNMENT_MASK);
395 // make Atom using placement new operator
396 new (&_atomArray[_atomArrayCount++]) Atom(*this, name, scope, def, combine, alignment, autohide);
397 if ( scope != ld::Atom::scopeTranslationUnit )
398 _internalAtom.addReference(name);
399 if ( log ) fprintf(stderr, "\t0x%08X %s\n", attr, name);
400 }
401 else {
402 // add to list of external references
403 _internalAtom.addReference(name);
404 if ( log ) fprintf(stderr, "\t%s (undefined)\n", name);
405 }
406 }
407 }
408
409 File::~File()
410 {
411 if ( _module != NULL )
412 ::lto_module_dispose(_module);
413 }
414
415 bool File::forEachAtom(ld::File::AtomHandler& handler) const
416 {
417 handler.doAtom(_internalAtom);
418 for(uint32_t i=0; i < _atomArrayCount; ++i) {
419 handler.doAtom(_atomArray[i]);
420 }
421 return true;
422 }
423
424 InternalAtom::InternalAtom(File& f)
425 : ld::Atom(f._section, ld::Atom::definitionRegular, ld::Atom::combineNever, ld::Atom::scopeTranslationUnit,
426 ld::Atom::typeLTOtemporary, ld::Atom::symbolTableNotIn, true, false, false, ld::Atom::Alignment(0)),
427 _file(f)
428 {
429 }
430
431 Atom::Atom(File& f, const char* nm, ld::Atom::Scope s, ld::Atom::Definition d, ld::Atom::Combine c,
432 ld::Atom::Alignment a, bool ah)
433 : ld::Atom(f._section, d, c, s, ld::Atom::typeLTOtemporary,
434 ld::Atom::symbolTableIn, false, false, false, a),
435 _file(f), _name(nm), _compiledAtom(NULL)
436 {
437 if ( ah )
438 this->setAutoHide();
439 }
440
441 void Atom::setCompiledAtom(const ld::Atom& atom)
442 {
443 // set delegate so virtual methods go to it
444 _compiledAtom = &atom;
445
446 //fprintf(stderr, "setting lto atom %p to delegate to mach-o atom %p (%s)\n", this, &atom, atom.name());
447
448 // update fields in ld::Atom to match newly constructed mach-o atom
449 (const_cast<Atom*>(this))->setAttributesFromAtom(atom);
450 }
451
452
453
454 // <rdar://problem/12379604> The order that files are merged must match command line order
455 struct CommandLineOrderFileSorter
456 {
457 bool operator()(File* left, File* right)
458 {
459 return ( left->ordinal() < right->ordinal() );
460 }
461 };
462
463
464 bool Parser::optimize( const std::vector<const ld::Atom*>& allAtoms,
465 ld::Internal& state,
466 const OptimizeOptions& options,
467 ld::File::AtomHandler& handler,
468 std::vector<const ld::Atom*>& newAtoms,
469 std::vector<const char*>& additionalUndefines)
470 {
471 const bool logMustPreserve = false;
472 const bool logExtraOptions = false;
473 const bool logBitcodeFiles = false;
474 const bool logAtomsBeforeSync = false;
475
476 // exit quickly if nothing to do
477 if ( _s_files.size() == 0 )
478 return false;
479
480 // print out LTO version string if -v was used
481 if ( options.verbose )
482 fprintf(stderr, "%s\n", ::lto_get_version());
483
484 // create optimizer and add each Reader
485 lto_code_gen_t generator = ::lto_codegen_create();
486 // <rdar://problem/12379604> The order that files are merged must match command line order
487 std::sort(_s_files.begin(), _s_files.end(), CommandLineOrderFileSorter());
488 ld::File::Ordinal lastOrdinal;
489 for (std::vector<File*>::iterator it=_s_files.begin(); it != _s_files.end(); ++it) {
490 File* f = *it;
491 assert(f->ordinal() > lastOrdinal);
492 if ( logBitcodeFiles ) fprintf(stderr, "lto_codegen_add_module(%s)\n", f->path());
493 if ( ::lto_codegen_add_module(generator, f->module()) )
494 throwf("lto: could not merge in %s because '%s', using libLTO version '%s'", f->path(), ::lto_get_error_message(), ::lto_get_version());
495 lastOrdinal = f->ordinal();
496 }
497
498 // add any -mllvm command line options
499 for (std::vector<const char*>::const_iterator it=options.llvmOptions->begin(); it != options.llvmOptions->end(); ++it) {
500 if ( logExtraOptions ) fprintf(stderr, "passing option to llvm: %s\n", *it);
501 ::lto_codegen_debug_options(generator, *it);
502 }
503
504 // <rdar://problem/13687397> Need a way for LTO to get cpu variants (until that info is in bitcode)
505 if ( options.mcpu != NULL )
506 ::lto_codegen_set_cpu(generator, options.mcpu);
507
508 // The atom graph uses directed edges (references). Collect all references where
509 // originating atom is not part of any LTO Reader. This allows optimizer to optimize an
510 // external (i.e. not originated from same .o file) reference if all originating atoms are also
511 // defined in llvm bitcode file.
512 CStringSet nonLLVMRefs;
513 CStringToAtom llvmAtoms;
514 bool hasNonllvmAtoms = false;
515 for (std::vector<const ld::Atom*>::const_iterator it = allAtoms.begin(); it != allAtoms.end(); ++it) {
516 const ld::Atom* atom = *it;
517 // only look at references that come from an atom that is not an llvm atom
518 if ( atom->contentType() != ld::Atom::typeLTOtemporary ) {
519 if ( (atom->section().type() != ld::Section::typeMachHeader) && (atom->definition() != ld::Atom::definitionProxy) ) {
520 hasNonllvmAtoms = true;
521 }
522 const ld::Atom* target;
523 for (ld::Fixup::iterator fit=atom->fixupsBegin(); fit != atom->fixupsEnd(); ++fit) {
524 switch ( fit->binding ) {
525 case ld::Fixup::bindingDirectlyBound:
526 // that reference an llvm atom
527 if ( fit->u.target->contentType() == ld::Atom::typeLTOtemporary )
528 nonLLVMRefs.insert(fit->u.target->name());
529 break;
530 case ld::Fixup::bindingsIndirectlyBound:
531 target = state.indirectBindingTable[fit->u.bindingIndex];
532 if ( target == NULL )
533 throwf("'%s' in %s contains undefined reference", atom->name(), atom->file()->path());
534 assert(target != NULL);
535 if ( target->contentType() == ld::Atom::typeLTOtemporary )
536 nonLLVMRefs.insert(target->name());
537 default:
538 break;
539 }
540 }
541 }
542 else {
543 llvmAtoms[atom->name()] = (Atom*)atom;
544 }
545 }
546 // if entry point is in a llvm bitcode file, it must be preserved by LTO
547 if ( state.entryPoint!= NULL ) {
548 if ( state.entryPoint->contentType() == ld::Atom::typeLTOtemporary )
549 nonLLVMRefs.insert(state.entryPoint->name());
550 }
551
552 // deadAtoms are the atoms that the linker coalesced. For instance weak or tentative definitions
553 // overriden by another atom. If any of these deadAtoms are llvm atoms and they were replaced
554 // with a mach-o atom, we need to tell the lto engine to preserve (not optimize away) its dead
555 // atom so that the linker can replace it with the mach-o one later.
556 CStringToAtom deadllvmAtoms;
557 for (std::vector<const ld::Atom*>::const_iterator it = allAtoms.begin(); it != allAtoms.end(); ++it) {
558 const ld::Atom* atom = *it;
559 if ( atom->coalescedAway() && (atom->contentType() == ld::Atom::typeLTOtemporary) ) {
560 const char* name = atom->name();
561 if ( logMustPreserve ) fprintf(stderr, "lto_codegen_add_must_preserve_symbol(%s) because linker coalesce away and replace with a mach-o atom\n", name);
562 ::lto_codegen_add_must_preserve_symbol(generator, name);
563 deadllvmAtoms[name] = (Atom*)atom;
564 }
565 }
566 for (std::vector<File*>::iterator it=_s_files.begin(); it != _s_files.end(); ++it) {
567 File* file = *it;
568 for(uint32_t i=0; i < file->_atomArrayCount; ++i) {
569 Atom* llvmAtom = &file->_atomArray[i];
570 if ( llvmAtom->coalescedAway() ) {
571 const char* name = llvmAtom->name();
572 if ( deadllvmAtoms.find(name) == deadllvmAtoms.end() ) {
573 if ( logMustPreserve )
574 fprintf(stderr, "lto_codegen_add_must_preserve_symbol(%s) because linker coalesce away and replace with a mach-o atom\n", name);
575 ::lto_codegen_add_must_preserve_symbol(generator, name);
576 deadllvmAtoms[name] = (Atom*)llvmAtom;
577 }
578 }
579 else if ( options.linkerDeadStripping && !llvmAtom->live() ) {
580 const char* name = llvmAtom->name();
581 deadllvmAtoms[name] = (Atom*)llvmAtom;
582 }
583 }
584 }
585
586 // tell code generator about symbols that must be preserved
587 for (CStringToAtom::iterator it = llvmAtoms.begin(); it != llvmAtoms.end(); ++it) {
588 const char* name = it->first;
589 Atom* atom = it->second;
590 // Include llvm Symbol in export list if it meets one of following two conditions
591 // 1 - atom scope is global (and not linkage unit).
592 // 2 - included in nonLLVMRefs set.
593 // If a symbol is not listed in exportList then LTO is free to optimize it away.
594 if ( (atom->scope() == ld::Atom::scopeGlobal) && options.preserveAllGlobals ) {
595 if ( logMustPreserve ) fprintf(stderr, "lto_codegen_add_must_preserve_symbol(%s) because global symbol\n", name);
596 ::lto_codegen_add_must_preserve_symbol(generator, name);
597 }
598 else if ( nonLLVMRefs.find(name) != nonLLVMRefs.end() ) {
599 if ( logMustPreserve ) fprintf(stderr, "lto_codegen_add_must_preserve_symbol(%s) because referenced by a mach-o atom\n", name);
600 ::lto_codegen_add_must_preserve_symbol(generator, name);
601 }
602 }
603
604 // special case running ld -r on all bitcode files to produce another bitcode file (instead of mach-o)
605 if ( options.relocatable && !hasNonllvmAtoms ) {
606 if ( ! ::lto_codegen_write_merged_modules(generator, options.outputFilePath) ) {
607 // HACK, no good way to tell linker we are all done, so just quit
608 exit(0);
609 }
610 warning("could not produce merged bitcode file");
611 }
612
613 // set code-gen model
614 lto_codegen_model model = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
615 if ( options.mainExecutable ) {
616 if ( options.staticExecutable ) {
617 // x86_64 "static" or any "-static -pie" is really dynamic code model
618 if ( (options.arch == CPU_TYPE_X86_64) || options.pie )
619 model = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
620 else
621 model = LTO_CODEGEN_PIC_MODEL_STATIC;
622 }
623 else {
624 if ( options.pie )
625 model = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
626 else
627 model = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
628 }
629 }
630 else {
631 if ( options.allowTextRelocs )
632 model = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
633 else
634 model = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
635 }
636 if ( ::lto_codegen_set_pic_model(generator, model) )
637 throwf("could not create set codegen model: %s", lto_get_error_message());
638
639 // if requested, save off merged bitcode file
640 if ( options.saveTemps ) {
641 char tempBitcodePath[MAXPATHLEN];
642 strcpy(tempBitcodePath, options.outputFilePath);
643 strcat(tempBitcodePath, ".lto.bc");
644 ::lto_codegen_write_merged_modules(generator, tempBitcodePath);
645 }
646
647 #if LTO_API_VERSION >= 3
648 // find assembler next to linker
649 char path[PATH_MAX];
650 uint32_t bufSize = PATH_MAX;
651 if ( _NSGetExecutablePath(path, &bufSize) != -1 ) {
652 char* lastSlash = strrchr(path, '/');
653 if ( lastSlash != NULL ) {
654 strcpy(lastSlash+1, "as");
655 struct stat statInfo;
656 if ( stat(path, &statInfo) == 0 )
657 ::lto_codegen_set_assembler_path(generator, path);
658 }
659 }
660 #endif
661 // run code generator
662 size_t machOFileLen;
663 const uint8_t* machOFile = (uint8_t*)::lto_codegen_compile(generator, &machOFileLen);
664 if ( machOFile == NULL )
665 throwf("could not do LTO codegen: '%s', using libLTO version '%s'", ::lto_get_error_message(), ::lto_get_version());
666
667 // if requested, save off temp mach-o file
668 if ( options.saveTemps ) {
669 char tempMachoPath[MAXPATHLEN];
670 strcpy(tempMachoPath, options.outputFilePath);
671 strcat(tempMachoPath, ".lto.o");
672 int fd = ::open(tempMachoPath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
673 if ( fd != -1) {
674 ::write(fd, machOFile, machOFileLen);
675 ::close(fd);
676 }
677 // save off merged bitcode file
678 char tempOptBitcodePath[MAXPATHLEN];
679 strcpy(tempOptBitcodePath, options.outputFilePath);
680 strcat(tempOptBitcodePath, ".lto.opt.bc");
681 ::lto_codegen_write_merged_modules(generator, tempOptBitcodePath);
682 }
683
684 // if needed, save temp mach-o file to specific location
685 if ( options.tmpObjectFilePath != NULL ) {
686 int fd = ::open(options.tmpObjectFilePath, O_CREAT | O_WRONLY | O_TRUNC, 0666);
687 if ( fd != -1) {
688 ::write(fd, machOFile, machOFileLen);
689 ::close(fd);
690 }
691 else {
692 warning("could not write LTO temp file '%s', errno=%d", options.tmpObjectFilePath, errno);
693 }
694 }
695
696 // parse generated mach-o file into a MachOReader
697 ld::relocatable::File* machoFile = parseMachOFile(machOFile, machOFileLen, options);
698
699 // sync generated mach-o atoms with existing atoms ld knows about
700 if ( logAtomsBeforeSync ) {
701 fprintf(stderr, "llvmAtoms:\n");
702 for (CStringToAtom::iterator it = llvmAtoms.begin(); it != llvmAtoms.end(); ++it) {
703 const char* name = it->first;
704 //Atom* atom = it->second;
705 fprintf(stderr, "\t%s\n", name);
706 }
707 fprintf(stderr, "deadllvmAtoms:\n");
708 for (CStringToAtom::iterator it = deadllvmAtoms.begin(); it != deadllvmAtoms.end(); ++it) {
709 const char* name = it->first;
710 //Atom* atom = it->second;
711 fprintf(stderr, "\t%s\n", name);
712 }
713 }
714 AtomSyncer syncer(additionalUndefines, newAtoms, llvmAtoms, deadllvmAtoms, options);
715 machoFile->forEachAtom(syncer);
716
717 // Remove InternalAtoms from ld
718 for (std::vector<File*>::iterator it=_s_files.begin(); it != _s_files.end(); ++it) {
719 (*it)->internalAtom().setCoalescedAway();
720 }
721 // Remove Atoms from ld if code generator optimized them away
722 for (CStringToAtom::iterator li = llvmAtoms.begin(), le = llvmAtoms.end(); li != le; ++li) {
723 // check if setRealAtom() called on this Atom
724 if ( li->second->compiledAtom() == NULL ) {
725 //fprintf(stderr, "llvm optimized away %p %s\n", li->second, li->second->name());
726 li->second->setCoalescedAway();
727 }
728 }
729
730 // notify about file level attributes
731 handler.doFile(*machoFile);
732
733 // if final mach-o file has debug info, update original bitcode files to match
734 for (std::vector<File*>::iterator it=_s_files.begin(); it != _s_files.end(); ++it) {
735 (*it)->setDebugInfo(machoFile->debugInfo(), machoFile->path(),
736 machoFile->modificationTime(), machoFile->cpuSubType());
737 }
738
739 return true;
740 }
741
742
743 void Parser::AtomSyncer::doAtom(const ld::Atom& machoAtom)
744 {
745 // update proxy atoms to point to real atoms and find new atoms
746 const char* name = machoAtom.name();
747 if ( machoAtom.scope() >= ld::Atom::scopeLinkageUnit ) {
748 CStringToAtom::iterator pos = _llvmAtoms.find(name);
749 if ( pos != _llvmAtoms.end() ) {
750 // turn Atom into a proxy for this mach-o atom
751 pos->second->setCompiledAtom(machoAtom);
752 }
753 else {
754 // an atom of this name was not in the allAtoms list the linker gave us
755 if ( _deadllvmAtoms.find(name) != _deadllvmAtoms.end() ) {
756 // this corresponding to an atom that the linker coalesced away or marked not-live
757 if ( _options.linkerDeadStripping ) {
758 // llvm seems to want this atom and -dead_strip is enabled, so it will be deleted if not needed, so add back
759 Atom* llvmAtom = _deadllvmAtoms[name];
760 llvmAtom->setCompiledAtom(machoAtom);
761 _newAtoms.push_back(&machoAtom);
762 }
763 else {
764 // Don't pass it back as a new atom
765 }
766 }
767 else
768 {
769 // this is something new that lto conjured up, tell ld its new
770 _newAtoms.push_back(&machoAtom);
771 }
772 }
773 }
774 else {
775 // ld only knew about non-static atoms, so this one must be new
776 _newAtoms.push_back(&machoAtom);
777 }
778
779 // adjust fixups to go through proxy atoms
780 //fprintf(stderr, "adjusting fixups in atom: %s\n", machoAtom.name());
781 for (ld::Fixup::iterator fit=machoAtom.fixupsBegin(); fit != machoAtom.fixupsEnd(); ++fit) {
782 switch ( fit->binding ) {
783 case ld::Fixup::bindingNone:
784 break;
785 case ld::Fixup::bindingByNameUnbound:
786 // don't know if this target has been seen by linker before or if it is new
787 // be conservative and tell linker it is new
788 _additionalUndefines.push_back(fit->u.name);
789 //fprintf(stderr, " by name ref to: %s\n", fit->u.name);
790 break;
791 case ld::Fixup::bindingDirectlyBound:
792 // If mach-o atom is referencing another mach-o atom then
793 // reference is not going through Atom proxy. Fix it here to ensure that all
794 // llvm symbol references always go through Atom proxy.
795 if ( fit->u.target->scope() != ld::Atom::scopeTranslationUnit ) {
796 const char* targetName = fit->u.target->name();
797 CStringToAtom::iterator pos = _llvmAtoms.find(targetName);
798 if ( pos != _llvmAtoms.end() ) {
799 fit->u.target = pos->second;
800 }
801 else {
802 // <rdar://problem/12859831> Don't unbind follow-on reference into by-name reference
803 if ( (_deadllvmAtoms.find(targetName) != _deadllvmAtoms.end()) && (fit->kind != ld::Fixup::kindNoneFollowOn) ) {
804 // target was coalesed away and replace by mach-o atom from a non llvm .o file
805 fit->binding = ld::Fixup::bindingByNameUnbound;
806 fit->u.name = targetName;
807 }
808 }
809 }
810 //fprintf(stderr, " direct ref to: %s (scope=%d)\n", fit->u.target->name(), fit->u.target->scope());
811 break;
812 case ld::Fixup::bindingByContentBound:
813 //fprintf(stderr, " direct by content to: %s\n", fit->u.target->name());
814 break;
815 case ld::Fixup::bindingsIndirectlyBound:
816 assert(0 && "indirect binding found in initial mach-o file?");
817 //fprintf(stderr, " indirect by content to: %u\n", fit->u.bindingIndex);
818 break;
819 }
820 }
821
822 }
823
824 class Mutex {
825 static pthread_mutex_t lto_lock;
826 public:
827 Mutex() { pthread_mutex_lock(&lto_lock); }
828 ~Mutex() { pthread_mutex_unlock(&lto_lock); }
829 };
830 pthread_mutex_t Mutex::lto_lock = PTHREAD_MUTEX_INITIALIZER;
831
832 //
833 // Used by archive reader to see if member is an llvm bitcode file
834 //
835 bool isObjectFile(const uint8_t* fileContent, uint64_t fileLength, cpu_type_t architecture, cpu_subtype_t subarch)
836 {
837 Mutex lock;
838 return Parser::validFile(fileContent, fileLength, architecture, subarch);
839 }
840
841
842 //
843 // main function used by linker to instantiate ld::Files
844 //
845 ld::relocatable::File* parse(const uint8_t* fileContent, uint64_t fileLength,
846 const char* path, time_t modTime, ld::File::Ordinal ordinal,
847 cpu_type_t architecture, cpu_subtype_t subarch, bool logAllFiles)
848 {
849 Mutex lock;
850 if ( Parser::validFile(fileContent, fileLength, architecture, subarch) )
851 return Parser::parse(fileContent, fileLength, path, modTime, ordinal, architecture, subarch, logAllFiles);
852 else
853 return NULL;
854 }
855
856 //
857 // used by "ld -v" to report version of libLTO.dylib being used
858 //
859 const char* version()
860 {
861 Mutex lock;
862 return ::lto_get_version();
863 }
864
865
866 //
867 // used by ld for error reporting
868 //
869 bool libLTOisLoaded()
870 {
871 Mutex lock;
872 return (::lto_get_version() != NULL);
873 }
874
875 //
876 // used by ld for error reporting
877 //
878 const char* archName(const uint8_t* fileContent, uint64_t fileLength)
879 {
880 Mutex lock;
881 return Parser::fileKind(fileContent, fileLength);
882 }
883
884 //
885 // used by ld for doing link time optimization
886 //
887 bool optimize( const std::vector<const ld::Atom*>& allAtoms,
888 ld::Internal& state,
889 const OptimizeOptions& options,
890 ld::File::AtomHandler& handler,
891 std::vector<const ld::Atom*>& newAtoms,
892 std::vector<const char*>& additionalUndefines)
893 {
894 Mutex lock;
895 return Parser::optimize(allAtoms, state, options, handler, newAtoms, additionalUndefines);
896 }
897
898
899
900 }; // namespace lto
901
902
903 #endif
904