1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the target-independent Mach-O writer. This file writes
11 // out the Mach-O file in the following order:
13 // #1 FatHeader (universal-only)
14 // #2 FatArch (universal-only, 1 per universal arch)
23 //===----------------------------------------------------------------------===//
26 #include "MachOWriter.h"
27 #include "MachOCodeEmitter.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Module.h"
31 #include "llvm/PassManager.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetMachOWriterInfo.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/OutputBuffer.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
43 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
45 ObjectCodeEmitter
*AddMachOWriter(PassManagerBase
&PM
,
48 MachOWriter
*MOW
= new MachOWriter(O
, TM
);
50 return MOW
->getObjectCodeEmitter();
53 //===----------------------------------------------------------------------===//
54 // MachOWriter Implementation
55 //===----------------------------------------------------------------------===//
57 char MachOWriter::ID
= 0;
59 MachOWriter::MachOWriter(raw_ostream
&o
, TargetMachine
&tm
)
60 : MachineFunctionPass(&ID
), O(o
), TM(tm
) {
61 is64Bit
= TM
.getTargetData()->getPointerSizeInBits() == 64;
62 isLittleEndian
= TM
.getTargetData()->isLittleEndian();
64 MAI
= TM
.getMCAsmInfo();
66 // Create the machine code emitter object for this target.
67 MachOCE
= new MachOCodeEmitter(*this, *getTextSection(true));
70 MachOWriter::~MachOWriter() {
74 bool MachOWriter::doInitialization(Module
&M
) {
75 // Set the magic value, now that we know the pointer size and endianness
76 Header
.setMagic(isLittleEndian
, is64Bit
);
79 // FIXME: this only works for object files, we do not support the creation
80 // of dynamic libraries or executables at this time.
81 Header
.filetype
= MachOHeader::MH_OBJECT
;
83 Mang
= new Mangler(M
);
87 bool MachOWriter::runOnMachineFunction(MachineFunction
&MF
) {
91 /// doFinalization - Now that the module has been completely processed, emit
92 /// the Mach-O file to 'O'.
93 bool MachOWriter::doFinalization(Module
&M
) {
94 // FIXME: we don't handle debug info yet, we should probably do that.
95 // Okay, the.text section has been completed, build the .data, .bss, and
96 // "common" sections next.
98 for (Module::global_iterator I
= M
.global_begin(), E
= M
.global_end();
102 // Emit the header and load commands.
103 EmitHeaderAndLoadCommands();
105 // Emit the various sections and their relocation info.
109 // Write the symbol table and the string table to the end of the file.
110 O
.write((char*)&SymT
[0], SymT
.size());
111 O
.write((char*)&StrT
[0], StrT
.size());
113 // We are done with the abstract symbols.
116 DynamicSymbolTable
.clear();
118 // Release the name mangler object.
119 delete Mang
; Mang
= 0;
123 // getConstSection - Get constant section for Constant 'C'
124 MachOSection
*MachOWriter::getConstSection(Constant
*C
) {
125 const ConstantArray
*CVA
= dyn_cast
<ConstantArray
>(C
);
126 if (CVA
&& CVA
->isCString())
127 return getSection("__TEXT", "__cstring",
128 MachOSection::S_CSTRING_LITERALS
);
130 const Type
*Ty
= C
->getType();
131 if (Ty
->isPrimitiveType() || Ty
->isInteger()) {
132 unsigned Size
= TM
.getTargetData()->getTypeAllocSize(Ty
);
134 default: break; // Fall through to __TEXT,__const
136 return getSection("__TEXT", "__literal4",
137 MachOSection::S_4BYTE_LITERALS
);
139 return getSection("__TEXT", "__literal8",
140 MachOSection::S_8BYTE_LITERALS
);
142 return getSection("__TEXT", "__literal16",
143 MachOSection::S_16BYTE_LITERALS
);
146 return getSection("__TEXT", "__const");
149 // getJumpTableSection - Select the Jump Table section
150 MachOSection
*MachOWriter::getJumpTableSection() {
151 if (TM
.getRelocationModel() == Reloc::PIC_
)
152 return getTextSection(false);
154 return getSection("__TEXT", "__const");
157 // getSection - Return the section with the specified name, creating a new
158 // section if one does not already exist.
159 MachOSection
*MachOWriter::getSection(const std::string
&seg
,
160 const std::string
§
,
161 unsigned Flags
/* = 0 */ ) {
162 MachOSection
*MOS
= SectionLookup
[seg
+sect
];
165 MOS
= new MachOSection(seg
, sect
);
166 SectionList
.push_back(MOS
);
167 MOS
->Index
= SectionList
.size();
168 MOS
->flags
= MachOSection::S_REGULAR
| Flags
;
169 SectionLookup
[seg
+sect
] = MOS
;
173 // getTextSection - Return text section with different flags for code/data
174 MachOSection
*MachOWriter::getTextSection(bool isCode
/* = true */ ) {
176 return getSection("__TEXT", "__text",
177 MachOSection::S_ATTR_PURE_INSTRUCTIONS
|
178 MachOSection::S_ATTR_SOME_INSTRUCTIONS
);
180 return getSection("__TEXT", "__text");
183 MachOSection
*MachOWriter::getBSSSection() {
184 return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL
);
187 // GetJTRelocation - Get a relocation a new BB relocation based
188 // on target information.
189 MachineRelocation
MachOWriter::GetJTRelocation(unsigned Offset
,
190 MachineBasicBlock
*MBB
) const {
191 return TM
.getMachOWriterInfo()->GetJTRelocation(Offset
, MBB
);
194 // GetTargetRelocation - Returns the number of relocations.
195 unsigned MachOWriter::GetTargetRelocation(MachineRelocation
&MR
,
196 unsigned FromIdx
, unsigned ToAddr
,
197 unsigned ToIndex
, OutputBuffer
&RelocOut
,
198 OutputBuffer
&SecOut
, bool Scattered
,
200 return TM
.getMachOWriterInfo()->GetTargetRelocation(MR
, FromIdx
, ToAddr
,
206 void MachOWriter::AddSymbolToSection(MachOSection
*Sec
, GlobalVariable
*GV
) {
207 const Type
*Ty
= GV
->getType()->getElementType();
208 unsigned Size
= TM
.getTargetData()->getTypeAllocSize(Ty
);
209 unsigned Align
= TM
.getTargetData()->getPreferredAlignment(GV
);
211 // Reserve space in the .bss section for this symbol while maintaining the
212 // desired section alignment, which must be at least as much as required by
214 OutputBuffer
SecDataOut(Sec
->getData(), is64Bit
, isLittleEndian
);
217 Align
= Log2_32(Align
);
218 Sec
->align
= std::max(unsigned(Sec
->align
), Align
);
220 Sec
->emitAlignment(Sec
->align
);
222 // Globals without external linkage apparently do not go in the symbol table.
223 if (!GV
->hasLocalLinkage()) {
224 MachOSym
Sym(GV
, Mang
->getMangledName(GV
), Sec
->Index
, MAI
);
225 Sym
.n_value
= Sec
->size();
226 SymbolTable
.push_back(Sym
);
229 // Record the offset of the symbol, and then allocate space for it.
230 // FIXME: remove when we have unified size + output buffer
232 // Now that we know what section the GlovalVariable is going to be emitted
233 // into, update our mappings.
234 // FIXME: We may also need to update this when outputting non-GlobalVariable
235 // GlobalValues such as functions.
238 GVOffset
[GV
] = Sec
->size();
240 // Allocate space in the section for the global.
241 for (unsigned i
= 0; i
< Size
; ++i
)
242 SecDataOut
.outbyte(0);
245 void MachOWriter::EmitGlobal(GlobalVariable
*GV
) {
246 const Type
*Ty
= GV
->getType()->getElementType();
247 unsigned Size
= TM
.getTargetData()->getTypeAllocSize(Ty
);
248 bool NoInit
= !GV
->hasInitializer();
250 // If this global has a zero initializer, it is part of the .bss or common
252 if (NoInit
|| GV
->getInitializer()->isNullValue()) {
253 // If this global is part of the common block, add it now. Variables are
254 // part of the common block if they are zero initialized and allowed to be
255 // merged with other symbols.
256 if (NoInit
|| GV
->hasLinkOnceLinkage() || GV
->hasWeakLinkage() ||
257 GV
->hasCommonLinkage()) {
258 MachOSym
ExtOrCommonSym(GV
, Mang
->getMangledName(GV
),
259 MachOSym::NO_SECT
, MAI
);
260 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
261 // bytes of the symbol.
262 ExtOrCommonSym
.n_value
= Size
;
263 SymbolTable
.push_back(ExtOrCommonSym
);
264 // Remember that we've seen this symbol
268 // Otherwise, this symbol is part of the .bss section.
269 MachOSection
*BSS
= getBSSSection();
270 AddSymbolToSection(BSS
, GV
);
274 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
275 // 16 bytes, or a cstring. Other read only data goes into a regular const
276 // section. Read-write data goes in the data section.
277 MachOSection
*Sec
= GV
->isConstant() ? getConstSection(GV
->getInitializer()) :
279 AddSymbolToSection(Sec
, GV
);
280 InitMem(GV
->getInitializer(), GVOffset
[GV
], TM
.getTargetData(), Sec
);
285 void MachOWriter::EmitHeaderAndLoadCommands() {
286 // Step #0: Fill in the segment load command size, since we need it to figure
287 // out the rest of the header fields
289 MachOSegment
SEG("", is64Bit
);
290 SEG
.nsects
= SectionList
.size();
291 SEG
.cmdsize
= SEG
.cmdSize(is64Bit
) +
292 SEG
.nsects
* SectionList
[0]->cmdSize(is64Bit
);
294 // Step #1: calculate the number of load commands. We always have at least
295 // one, for the LC_SEGMENT load command, plus two for the normal
296 // and dynamic symbol tables, if there are any symbols.
297 Header
.ncmds
= SymbolTable
.empty() ? 1 : 3;
299 // Step #2: calculate the size of the load commands
300 Header
.sizeofcmds
= SEG
.cmdsize
;
301 if (!SymbolTable
.empty())
302 Header
.sizeofcmds
+= SymTab
.cmdsize
+ DySymTab
.cmdsize
;
304 // Step #3: write the header to the file
305 // Local alias to shortenify coming code.
306 std::vector
<unsigned char> &FH
= Header
.HeaderData
;
307 OutputBuffer
FHOut(FH
, is64Bit
, isLittleEndian
);
309 FHOut
.outword(Header
.magic
);
310 FHOut
.outword(TM
.getMachOWriterInfo()->getCPUType());
311 FHOut
.outword(TM
.getMachOWriterInfo()->getCPUSubType());
312 FHOut
.outword(Header
.filetype
);
313 FHOut
.outword(Header
.ncmds
);
314 FHOut
.outword(Header
.sizeofcmds
);
315 FHOut
.outword(Header
.flags
);
317 FHOut
.outword(Header
.reserved
);
319 // Step #4: Finish filling in the segment load command and write it out
320 for (std::vector
<MachOSection
*>::iterator I
= SectionList
.begin(),
321 E
= SectionList
.end(); I
!= E
; ++I
)
322 SEG
.filesize
+= (*I
)->size();
324 SEG
.vmsize
= SEG
.filesize
;
325 SEG
.fileoff
= Header
.cmdSize(is64Bit
) + Header
.sizeofcmds
;
327 FHOut
.outword(SEG
.cmd
);
328 FHOut
.outword(SEG
.cmdsize
);
329 FHOut
.outstring(SEG
.segname
, 16);
330 FHOut
.outaddr(SEG
.vmaddr
);
331 FHOut
.outaddr(SEG
.vmsize
);
332 FHOut
.outaddr(SEG
.fileoff
);
333 FHOut
.outaddr(SEG
.filesize
);
334 FHOut
.outword(SEG
.maxprot
);
335 FHOut
.outword(SEG
.initprot
);
336 FHOut
.outword(SEG
.nsects
);
337 FHOut
.outword(SEG
.flags
);
339 // Step #5: Finish filling in the fields of the MachOSections
340 uint64_t currentAddr
= 0;
341 for (std::vector
<MachOSection
*>::iterator I
= SectionList
.begin(),
342 E
= SectionList
.end(); I
!= E
; ++I
) {
343 MachOSection
*MOS
= *I
;
344 MOS
->addr
= currentAddr
;
345 MOS
->offset
= currentAddr
+ SEG
.fileoff
;
346 // FIXME: do we need to do something with alignment here?
347 currentAddr
+= MOS
->size();
350 // Step #6: Emit the symbol table to temporary buffers, so that we know the
351 // size of the string table when we write the next load command. This also
352 // sorts and assigns indices to each of the symbols, which is necessary for
353 // emitting relocations to externally-defined objects.
354 BufferSymbolAndStringTable();
356 // Step #7: Calculate the number of relocations for each section and write out
357 // the section commands for each section
358 currentAddr
+= SEG
.fileoff
;
359 for (std::vector
<MachOSection
*>::iterator I
= SectionList
.begin(),
360 E
= SectionList
.end(); I
!= E
; ++I
) {
361 MachOSection
*MOS
= *I
;
363 // Convert the relocations to target-specific relocations, and fill in the
364 // relocation offset for this section.
365 CalculateRelocations(*MOS
);
366 MOS
->reloff
= MOS
->nreloc
? currentAddr
: 0;
367 currentAddr
+= MOS
->nreloc
* 8;
369 // write the finalized section command to the output buffer
370 FHOut
.outstring(MOS
->sectname
, 16);
371 FHOut
.outstring(MOS
->segname
, 16);
372 FHOut
.outaddr(MOS
->addr
);
373 FHOut
.outaddr(MOS
->size());
374 FHOut
.outword(MOS
->offset
);
375 FHOut
.outword(MOS
->align
);
376 FHOut
.outword(MOS
->reloff
);
377 FHOut
.outword(MOS
->nreloc
);
378 FHOut
.outword(MOS
->flags
);
379 FHOut
.outword(MOS
->reserved1
);
380 FHOut
.outword(MOS
->reserved2
);
382 FHOut
.outword(MOS
->reserved3
);
385 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
386 SymTab
.symoff
= currentAddr
;
387 SymTab
.nsyms
= SymbolTable
.size();
388 SymTab
.stroff
= SymTab
.symoff
+ SymT
.size();
389 SymTab
.strsize
= StrT
.size();
390 FHOut
.outword(SymTab
.cmd
);
391 FHOut
.outword(SymTab
.cmdsize
);
392 FHOut
.outword(SymTab
.symoff
);
393 FHOut
.outword(SymTab
.nsyms
);
394 FHOut
.outword(SymTab
.stroff
);
395 FHOut
.outword(SymTab
.strsize
);
397 // FIXME: set DySymTab fields appropriately
398 // We should probably just update these in BufferSymbolAndStringTable since
399 // thats where we're partitioning up the different kinds of symbols.
400 FHOut
.outword(DySymTab
.cmd
);
401 FHOut
.outword(DySymTab
.cmdsize
);
402 FHOut
.outword(DySymTab
.ilocalsym
);
403 FHOut
.outword(DySymTab
.nlocalsym
);
404 FHOut
.outword(DySymTab
.iextdefsym
);
405 FHOut
.outword(DySymTab
.nextdefsym
);
406 FHOut
.outword(DySymTab
.iundefsym
);
407 FHOut
.outword(DySymTab
.nundefsym
);
408 FHOut
.outword(DySymTab
.tocoff
);
409 FHOut
.outword(DySymTab
.ntoc
);
410 FHOut
.outword(DySymTab
.modtaboff
);
411 FHOut
.outword(DySymTab
.nmodtab
);
412 FHOut
.outword(DySymTab
.extrefsymoff
);
413 FHOut
.outword(DySymTab
.nextrefsyms
);
414 FHOut
.outword(DySymTab
.indirectsymoff
);
415 FHOut
.outword(DySymTab
.nindirectsyms
);
416 FHOut
.outword(DySymTab
.extreloff
);
417 FHOut
.outword(DySymTab
.nextrel
);
418 FHOut
.outword(DySymTab
.locreloff
);
419 FHOut
.outword(DySymTab
.nlocrel
);
421 O
.write((char*)&FH
[0], FH
.size());
424 /// EmitSections - Now that we have constructed the file header and load
425 /// commands, emit the data for each section to the file.
426 void MachOWriter::EmitSections() {
427 for (std::vector
<MachOSection
*>::iterator I
= SectionList
.begin(),
428 E
= SectionList
.end(); I
!= E
; ++I
)
429 // Emit the contents of each section
431 O
.write((char*)&(*I
)->getData()[0], (*I
)->size());
434 /// EmitRelocations - emit relocation data from buffer.
435 void MachOWriter::EmitRelocations() {
436 for (std::vector
<MachOSection
*>::iterator I
= SectionList
.begin(),
437 E
= SectionList
.end(); I
!= E
; ++I
)
438 // Emit the relocation entry data for each section.
439 if ((*I
)->RelocBuffer
.size())
440 O
.write((char*)&(*I
)->RelocBuffer
[0], (*I
)->RelocBuffer
.size());
443 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
444 /// each a string table index so that they appear in the correct order in the
446 void MachOWriter::BufferSymbolAndStringTable() {
447 // The order of the symbol table is:
449 // 2. defined external symbols (sorted by name)
450 // 3. undefined external symbols (sorted by name)
452 // Before sorting the symbols, check the PendingGlobals for any undefined
453 // globals that need to be put in the symbol table.
454 for (std::vector
<GlobalValue
*>::iterator I
= PendingGlobals
.begin(),
455 E
= PendingGlobals
.end(); I
!= E
; ++I
) {
456 if (GVOffset
[*I
] == 0 && GVSection
[*I
] == 0) {
457 MachOSym
UndfSym(*I
, Mang
->getMangledName(*I
), MachOSym::NO_SECT
, MAI
);
458 SymbolTable
.push_back(UndfSym
);
463 // Sort the symbols by name, so that when we partition the symbols by scope
464 // of definition, we won't have to sort by name within each partition.
465 std::sort(SymbolTable
.begin(), SymbolTable
.end(), MachOSym::SymCmp());
467 // Parition the symbol table entries so that all local symbols come before
468 // all symbols with external linkage. { 1 | 2 3 }
469 std::partition(SymbolTable
.begin(), SymbolTable
.end(),
470 MachOSym::PartitionByLocal
);
472 // Advance iterator to beginning of external symbols and partition so that
473 // all external symbols defined in this module come before all external
474 // symbols defined elsewhere. { 1 | 2 | 3 }
475 for (std::vector
<MachOSym
>::iterator I
= SymbolTable
.begin(),
476 E
= SymbolTable
.end(); I
!= E
; ++I
) {
477 if (!MachOSym::PartitionByLocal(*I
)) {
478 std::partition(I
, E
, MachOSym::PartitionByDefined
);
483 // Calculate the starting index for each of the local, extern defined, and
484 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
486 for (std::vector
<MachOSym
>::iterator I
= SymbolTable
.begin(),
487 E
= SymbolTable
.end(); I
!= E
; ++I
) {
488 if (MachOSym::PartitionByLocal(*I
)) {
489 ++DySymTab
.nlocalsym
;
490 ++DySymTab
.iextdefsym
;
491 ++DySymTab
.iundefsym
;
492 } else if (MachOSym::PartitionByDefined(*I
)) {
493 ++DySymTab
.nextdefsym
;
494 ++DySymTab
.iundefsym
;
496 ++DySymTab
.nundefsym
;
500 // Write out a leading zero byte when emitting string table, for n_strx == 0
501 // which means an empty string.
502 OutputBuffer
StrTOut(StrT
, is64Bit
, isLittleEndian
);
505 // The order of the string table is:
506 // 1. strings for external symbols
507 // 2. strings for local symbols
508 // Since this is the opposite order from the symbol table, which we have just
509 // sorted, we can walk the symbol table backwards to output the string table.
510 for (std::vector
<MachOSym
>::reverse_iterator I
= SymbolTable
.rbegin(),
511 E
= SymbolTable
.rend(); I
!= E
; ++I
) {
512 if (I
->GVName
== "") {
515 I
->n_strx
= StrT
.size();
516 StrTOut
.outstring(I
->GVName
, I
->GVName
.length()+1);
520 OutputBuffer
SymTOut(SymT
, is64Bit
, isLittleEndian
);
523 for (std::vector
<MachOSym
>::iterator I
= SymbolTable
.begin(),
524 E
= SymbolTable
.end(); I
!= E
; ++I
, ++index
) {
525 // Add the section base address to the section offset in the n_value field
526 // to calculate the full address.
527 // FIXME: handle symbols where the n_value field is not the address
528 GlobalValue
*GV
= const_cast<GlobalValue
*>(I
->GV
);
529 if (GV
&& GVSection
[GV
])
530 I
->n_value
+= GVSection
[GV
]->addr
;
531 if (GV
&& (GVOffset
[GV
] == -1))
532 GVOffset
[GV
] = index
;
534 // Emit nlist to buffer
535 SymTOut
.outword(I
->n_strx
);
536 SymTOut
.outbyte(I
->n_type
);
537 SymTOut
.outbyte(I
->n_sect
);
538 SymTOut
.outhalf(I
->n_desc
);
539 SymTOut
.outaddr(I
->n_value
);
543 /// CalculateRelocations - For each MachineRelocation in the current section,
544 /// calculate the index of the section containing the object to be relocated,
545 /// and the offset into that section. From this information, create the
546 /// appropriate target-specific MachORelocation type and add buffer it to be
547 /// written out after we are finished writing out sections.
548 void MachOWriter::CalculateRelocations(MachOSection
&MOS
) {
549 std::vector
<MachineRelocation
> Relocations
= MOS
.getRelocations();
550 for (unsigned i
= 0, e
= Relocations
.size(); i
!= e
; ++i
) {
551 MachineRelocation
&MR
= Relocations
[i
];
552 unsigned TargetSection
= MR
.getConstantVal();
553 unsigned TargetAddr
= 0;
554 unsigned TargetIndex
= 0;
556 // This is a scattered relocation entry if it points to a global value with
557 // a non-zero offset.
558 bool Scattered
= false;
561 // Since we may not have seen the GlobalValue we were interested in yet at
562 // the time we emitted the relocation for it, fix it up now so that it
563 // points to the offset into the correct section.
564 if (MR
.isGlobalValue()) {
565 GlobalValue
*GV
= MR
.getGlobalValue();
566 MachOSection
*MOSPtr
= GVSection
[GV
];
567 intptr_t Offset
= GVOffset
[GV
];
569 // If we have never seen the global before, it must be to a symbol
570 // defined in another module (N_UNDF).
572 // FIXME: need to append stub suffix
575 TargetIndex
= GVOffset
[GV
];
577 Scattered
= TargetSection
!= 0;
578 TargetSection
= MOSPtr
->Index
;
580 MR
.setResultPointer((void*)Offset
);
583 // If the symbol is locally defined, pass in the address of the section and
584 // the section index to the code which will generate the target relocation.
586 MachOSection
&To
= *SectionList
[TargetSection
- 1];
587 TargetAddr
= To
.addr
;
588 TargetIndex
= To
.Index
;
591 OutputBuffer
RelocOut(MOS
.RelocBuffer
, is64Bit
, isLittleEndian
);
592 OutputBuffer
SecOut(MOS
.getData(), is64Bit
, isLittleEndian
);
594 MOS
.nreloc
+= GetTargetRelocation(MR
, MOS
.Index
, TargetAddr
, TargetIndex
,
595 RelocOut
, SecOut
, Scattered
, Extern
);
599 // InitMem - Write the value of a Constant to the specified memory location,
600 // converting it into bytes and relocations.
601 void MachOWriter::InitMem(const Constant
*C
, uintptr_t Offset
,
602 const TargetData
*TD
, MachOSection
* mos
) {
603 typedef std::pair
<const Constant
*, intptr_t> CPair
;
604 std::vector
<CPair
> WorkList
;
605 uint8_t *Addr
= &mos
->getData()[0];
607 WorkList
.push_back(CPair(C
,(intptr_t)Addr
+ Offset
));
609 intptr_t ScatteredOffset
= 0;
611 while (!WorkList
.empty()) {
612 const Constant
*PC
= WorkList
.back().first
;
613 intptr_t PA
= WorkList
.back().second
;
616 if (isa
<UndefValue
>(PC
)) {
618 } else if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(PC
)) {
619 unsigned ElementSize
=
620 TD
->getTypeAllocSize(CP
->getType()->getElementType());
621 for (unsigned i
= 0, e
= CP
->getNumOperands(); i
!= e
; ++i
)
622 WorkList
.push_back(CPair(CP
->getOperand(i
), PA
+i
*ElementSize
));
623 } else if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(PC
)) {
625 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
627 switch (CE
->getOpcode()) {
628 case Instruction::GetElementPtr
: {
629 SmallVector
<Value
*, 8> Indices(CE
->op_begin()+1, CE
->op_end());
630 ScatteredOffset
= TD
->getIndexedOffset(CE
->getOperand(0)->getType(),
631 &Indices
[0], Indices
.size());
632 WorkList
.push_back(CPair(CE
->getOperand(0), PA
));
635 case Instruction::Add
:
637 errs() << "ConstantExpr not handled as global var init: " << *CE
<<"\n";
640 } else if (PC
->getType()->isSingleValueType()) {
641 unsigned char *ptr
= (unsigned char *)PA
;
642 switch (PC
->getType()->getTypeID()) {
643 case Type::IntegerTyID
: {
644 unsigned NumBits
= cast
<IntegerType
>(PC
->getType())->getBitWidth();
645 uint64_t val
= cast
<ConstantInt
>(PC
)->getZExtValue();
648 else if (NumBits
<= 16) {
649 if (TD
->isBigEndian())
650 val
= ByteSwap_16(val
);
653 } else if (NumBits
<= 32) {
654 if (TD
->isBigEndian())
655 val
= ByteSwap_32(val
);
660 } else if (NumBits
<= 64) {
661 if (TD
->isBigEndian())
662 val
= ByteSwap_64(val
);
672 llvm_unreachable("Not implemented: bit widths > 64");
676 case Type::FloatTyID
: {
677 uint32_t val
= cast
<ConstantFP
>(PC
)->getValueAPF().bitcastToAPInt().
679 if (TD
->isBigEndian())
680 val
= ByteSwap_32(val
);
687 case Type::DoubleTyID
: {
688 uint64_t val
= cast
<ConstantFP
>(PC
)->getValueAPF().bitcastToAPInt().
690 if (TD
->isBigEndian())
691 val
= ByteSwap_64(val
);
702 case Type::PointerTyID
:
703 if (isa
<ConstantPointerNull
>(PC
))
704 memset(ptr
, 0, TD
->getPointerSize());
705 else if (const GlobalValue
* GV
= dyn_cast
<GlobalValue
>(PC
)) {
706 // FIXME: what about function stubs?
707 mos
->addRelocation(MachineRelocation::getGV(PA
-(intptr_t)Addr
,
708 MachineRelocation::VANILLA
,
709 const_cast<GlobalValue
*>(GV
),
713 llvm_unreachable("Unknown constant pointer type!");
717 raw_string_ostream
Msg(msg
);
718 Msg
<< "ERROR: Constant unimp for type: " << *PC
->getType();
719 llvm_report_error(Msg
.str());
721 } else if (isa
<ConstantAggregateZero
>(PC
)) {
722 memset((void*)PA
, 0, (size_t)TD
->getTypeAllocSize(PC
->getType()));
723 } else if (const ConstantArray
*CPA
= dyn_cast
<ConstantArray
>(PC
)) {
724 unsigned ElementSize
=
725 TD
->getTypeAllocSize(CPA
->getType()->getElementType());
726 for (unsigned i
= 0, e
= CPA
->getNumOperands(); i
!= e
; ++i
)
727 WorkList
.push_back(CPair(CPA
->getOperand(i
), PA
+i
*ElementSize
));
728 } else if (const ConstantStruct
*CPS
= dyn_cast
<ConstantStruct
>(PC
)) {
729 const StructLayout
*SL
=
730 TD
->getStructLayout(cast
<StructType
>(CPS
->getType()));
731 for (unsigned i
= 0, e
= CPS
->getNumOperands(); i
!= e
; ++i
)
732 WorkList
.push_back(CPair(CPS
->getOperand(i
),
733 PA
+SL
->getElementOffset(i
)));
735 errs() << "Bad Type: " << *PC
->getType() << "\n";
736 llvm_unreachable("Unknown constant type to initialize memory with!");
741 //===----------------------------------------------------------------------===//
742 // MachOSym Implementation
743 //===----------------------------------------------------------------------===//
745 MachOSym::MachOSym(const GlobalValue
*gv
, std::string name
, uint8_t sect
,
746 const MCAsmInfo
*MAI
) :
747 GV(gv
), n_strx(0), n_type(sect
== NO_SECT
? N_UNDF
: N_SECT
), n_sect(sect
),
748 n_desc(0), n_value(0) {
750 // FIXME: This is completely broken, it should use the mangler interface.
751 switch (GV
->getLinkage()) {
753 llvm_unreachable("Unexpected linkage type!");
755 case GlobalValue::WeakAnyLinkage
:
756 case GlobalValue::WeakODRLinkage
:
757 case GlobalValue::LinkOnceAnyLinkage
:
758 case GlobalValue::LinkOnceODRLinkage
:
759 case GlobalValue::CommonLinkage
:
760 assert(!isa
<Function
>(gv
) && "Unexpected linkage type for Function!");
761 case GlobalValue::ExternalLinkage
:
762 GVName
= MAI
->getGlobalPrefix() + name
;
763 n_type
|= GV
->hasHiddenVisibility() ? N_PEXT
: N_EXT
;
765 case GlobalValue::PrivateLinkage
:
766 GVName
= MAI
->getPrivateGlobalPrefix() + name
;
768 case GlobalValue::LinkerPrivateLinkage
:
769 GVName
= MAI
->getLinkerPrivateGlobalPrefix() + name
;
771 case GlobalValue::InternalLinkage
:
772 GVName
= MAI
->getGlobalPrefix() + name
;
777 } // end namespace llvm