163df6994aa625d02bd81671df6771345bbb4ad7
[oota-llvm.git] / lib / CodeGen / MachOWriter.cpp
1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the target-independent Mach-O writer.  This file writes
11 // out the Mach-O file in the following order:
12 //
13 //  #1 FatHeader (universal-only)
14 //  #2 FatArch (universal-only, 1 per universal arch)
15 //  Per arch:
16 //    #3 Header
17 //    #4 Load Commands
18 //    #5 Sections
19 //    #6 Relocations
20 //    #7 Symbols
21 //    #8 Strings
22 //
23 //===----------------------------------------------------------------------===//
24
25 #include "MachOWriter.h"
26 #include "MachOCodeEmitter.h"
27 #include "llvm/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Module.h"
30 #include "llvm/PassManager.h"
31 #include "llvm/CodeGen/FileWriters.h"
32 #include "llvm/CodeGen/MachineCodeEmitter.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetJITInfo.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/OutputBuffer.h"
40 #include "llvm/Support/Streams.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <algorithm>
43 #include <cstring>
44
45 namespace llvm {
46
47 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
48 /// pass manager.
49 MachineCodeEmitter *AddMachOWriter(PassManagerBase &PM,
50                                          raw_ostream &O,
51                                          TargetMachine &TM) {
52   MachOWriter *MOW = new MachOWriter(O, TM);
53   PM.add(MOW);
54   return &MOW->getMachineCodeEmitter();
55 }
56
57 //===----------------------------------------------------------------------===//
58 //                          MachOWriter Implementation
59 //===----------------------------------------------------------------------===//
60
61 char MachOWriter::ID = 0;
62
63 MachOWriter::MachOWriter(raw_ostream &o, TargetMachine &tm)
64   : MachineFunctionPass(&ID), O(o), TM(tm) {
65   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
66   isLittleEndian = TM.getTargetData()->isLittleEndian();
67
68   TAI = TM.getTargetAsmInfo();
69
70   // Create the machine code emitter object for this target.
71
72   MCE = new MachOCodeEmitter(*this);
73 }
74
75 MachOWriter::~MachOWriter() {
76   delete MCE;
77 }
78
79 bool MachOWriter::doInitialization(Module &M) {
80   // Set the magic value, now that we know the pointer size and endianness
81   Header.setMagic(isLittleEndian, is64Bit);
82
83   // Set the file type
84   // FIXME: this only works for object files, we do not support the creation
85   //        of dynamic libraries or executables at this time.
86   Header.filetype = MachOHeader::MH_OBJECT;
87
88   Mang = new Mangler(M);
89   return false;
90 }
91
92 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
93   return false;
94 }
95
96 /// doFinalization - Now that the module has been completely processed, emit
97 /// the Mach-O file to 'O'.
98 bool MachOWriter::doFinalization(Module &M) {
99   // FIXME: we don't handle debug info yet, we should probably do that.
100
101   // Okay, the.text section has been completed, build the .data, .bss, and
102   // "common" sections next.
103   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
104        I != E; ++I)
105     EmitGlobal(I);
106
107   // Emit the header and load commands.
108   EmitHeaderAndLoadCommands();
109
110   // Emit the various sections and their relocation info.
111   EmitSections();
112   EmitRelocations();
113
114   // Write the symbol table and the string table to the end of the file.
115   O.write((char*)&SymT[0], SymT.size());
116   O.write((char*)&StrT[0], StrT.size());
117
118   // We are done with the abstract symbols.
119   SectionList.clear();
120   SymbolTable.clear();
121   DynamicSymbolTable.clear();
122
123   // Release the name mangler object.
124   delete Mang; Mang = 0;
125   return false;
126 }
127
128 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
129   const Type *Ty = GV->getType()->getElementType();
130   unsigned Size = TM.getTargetData()->getTypeAllocSize(Ty);
131   unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
132
133   // Reserve space in the .bss section for this symbol while maintaining the
134   // desired section alignment, which must be at least as much as required by
135   // this symbol.
136   OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
137
138   if (Align) {
139     uint64_t OrigSize = Sec->size;
140     Align = Log2_32(Align);
141     Sec->align = std::max(unsigned(Sec->align), Align);
142     Sec->size = (Sec->size + Align - 1) & ~(Align-1);
143
144     // Add alignment padding to buffer as well.
145     // FIXME: remove when we have unified size + output buffer
146     unsigned AlignedSize = Sec->size - OrigSize;
147     for (unsigned i = 0; i < AlignedSize; ++i)
148       SecDataOut.outbyte(0);
149   }
150   // Globals without external linkage apparently do not go in the symbol table.
151   if (!GV->hasLocalLinkage()) {
152     MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TAI);
153     Sym.n_value = Sec->size;
154     SymbolTable.push_back(Sym);
155   }
156
157   // Record the offset of the symbol, and then allocate space for it.
158   // FIXME: remove when we have unified size + output buffer
159   Sec->size += Size;
160
161   // Now that we know what section the GlovalVariable is going to be emitted
162   // into, update our mappings.
163   // FIXME: We may also need to update this when outputting non-GlobalVariable
164   // GlobalValues such as functions.
165   GVSection[GV] = Sec;
166   GVOffset[GV] = Sec->SectionData.size();
167
168   // Allocate space in the section for the global.
169   for (unsigned i = 0; i < Size; ++i)
170     SecDataOut.outbyte(0);
171 }
172
173 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
174   const Type *Ty = GV->getType()->getElementType();
175   unsigned Size = TM.getTargetData()->getTypeAllocSize(Ty);
176   bool NoInit = !GV->hasInitializer();
177
178   // If this global has a zero initializer, it is part of the .bss or common
179   // section.
180   if (NoInit || GV->getInitializer()->isNullValue()) {
181     // If this global is part of the common block, add it now.  Variables are
182     // part of the common block if they are zero initialized and allowed to be
183     // merged with other symbols.
184     if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
185         GV->hasCommonLinkage()) {
186       MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), 
187                               MachOSym::NO_SECT, TAI);
188       // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
189       // bytes of the symbol.
190       ExtOrCommonSym.n_value = Size;
191       SymbolTable.push_back(ExtOrCommonSym);
192       // Remember that we've seen this symbol
193       GVOffset[GV] = Size;
194       return;
195     }
196     // Otherwise, this symbol is part of the .bss section.
197     MachOSection *BSS = getBSSSection();
198     AddSymbolToSection(BSS, GV);
199     return;
200   }
201
202   // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
203   // 16 bytes, or a cstring.  Other read only data goes into a regular const
204   // section.  Read-write data goes in the data section.
205   MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
206                                          getDataSection();
207   AddSymbolToSection(Sec, GV);
208   InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
209           TM.getTargetData(), Sec->Relocations);
210 }
211
212
213
214 void MachOWriter::EmitHeaderAndLoadCommands() {
215   // Step #0: Fill in the segment load command size, since we need it to figure
216   //          out the rest of the header fields
217   MachOSegment SEG("", is64Bit);
218   SEG.nsects  = SectionList.size();
219   SEG.cmdsize = SEG.cmdSize(is64Bit) +
220                 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
221
222   // Step #1: calculate the number of load commands.  We always have at least
223   //          one, for the LC_SEGMENT load command, plus two for the normal
224   //          and dynamic symbol tables, if there are any symbols.
225   Header.ncmds = SymbolTable.empty() ? 1 : 3;
226
227   // Step #2: calculate the size of the load commands
228   Header.sizeofcmds = SEG.cmdsize;
229   if (!SymbolTable.empty())
230     Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
231
232   // Step #3: write the header to the file
233   // Local alias to shortenify coming code.
234   DataBuffer &FH = Header.HeaderData;
235   OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
236
237   FHOut.outword(Header.magic);
238   FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
239   FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
240   FHOut.outword(Header.filetype);
241   FHOut.outword(Header.ncmds);
242   FHOut.outword(Header.sizeofcmds);
243   FHOut.outword(Header.flags);
244   if (is64Bit)
245     FHOut.outword(Header.reserved);
246
247   // Step #4: Finish filling in the segment load command and write it out
248   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
249          E = SectionList.end(); I != E; ++I)
250     SEG.filesize += (*I)->size;
251
252   SEG.vmsize = SEG.filesize;
253   SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
254
255   FHOut.outword(SEG.cmd);
256   FHOut.outword(SEG.cmdsize);
257   FHOut.outstring(SEG.segname, 16);
258   FHOut.outaddr(SEG.vmaddr);
259   FHOut.outaddr(SEG.vmsize);
260   FHOut.outaddr(SEG.fileoff);
261   FHOut.outaddr(SEG.filesize);
262   FHOut.outword(SEG.maxprot);
263   FHOut.outword(SEG.initprot);
264   FHOut.outword(SEG.nsects);
265   FHOut.outword(SEG.flags);
266
267   // Step #5: Finish filling in the fields of the MachOSections
268   uint64_t currentAddr = 0;
269   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
270          E = SectionList.end(); I != E; ++I) {
271     MachOSection *MOS = *I;
272     MOS->addr = currentAddr;
273     MOS->offset = currentAddr + SEG.fileoff;
274
275     // FIXME: do we need to do something with alignment here?
276     currentAddr += MOS->size;
277   }
278
279   // Step #6: Emit the symbol table to temporary buffers, so that we know the
280   // size of the string table when we write the next load command.  This also
281   // sorts and assigns indices to each of the symbols, which is necessary for
282   // emitting relocations to externally-defined objects.
283   BufferSymbolAndStringTable();
284
285   // Step #7: Calculate the number of relocations for each section and write out
286   // the section commands for each section
287   currentAddr += SEG.fileoff;
288   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
289          E = SectionList.end(); I != E; ++I) {
290     MachOSection *MOS = *I;
291     // Convert the relocations to target-specific relocations, and fill in the
292     // relocation offset for this section.
293     CalculateRelocations(*MOS);
294     MOS->reloff = MOS->nreloc ? currentAddr : 0;
295     currentAddr += MOS->nreloc * 8;
296
297     // write the finalized section command to the output buffer
298     FHOut.outstring(MOS->sectname, 16);
299     FHOut.outstring(MOS->segname, 16);
300     FHOut.outaddr(MOS->addr);
301     FHOut.outaddr(MOS->size);
302     FHOut.outword(MOS->offset);
303     FHOut.outword(MOS->align);
304     FHOut.outword(MOS->reloff);
305     FHOut.outword(MOS->nreloc);
306     FHOut.outword(MOS->flags);
307     FHOut.outword(MOS->reserved1);
308     FHOut.outword(MOS->reserved2);
309     if (is64Bit)
310       FHOut.outword(MOS->reserved3);
311   }
312
313   // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
314   SymTab.symoff  = currentAddr;
315   SymTab.nsyms   = SymbolTable.size();
316   SymTab.stroff  = SymTab.symoff + SymT.size();
317   SymTab.strsize = StrT.size();
318   FHOut.outword(SymTab.cmd);
319   FHOut.outword(SymTab.cmdsize);
320   FHOut.outword(SymTab.symoff);
321   FHOut.outword(SymTab.nsyms);
322   FHOut.outword(SymTab.stroff);
323   FHOut.outword(SymTab.strsize);
324
325   // FIXME: set DySymTab fields appropriately
326   // We should probably just update these in BufferSymbolAndStringTable since
327   // thats where we're partitioning up the different kinds of symbols.
328   FHOut.outword(DySymTab.cmd);
329   FHOut.outword(DySymTab.cmdsize);
330   FHOut.outword(DySymTab.ilocalsym);
331   FHOut.outword(DySymTab.nlocalsym);
332   FHOut.outword(DySymTab.iextdefsym);
333   FHOut.outword(DySymTab.nextdefsym);
334   FHOut.outword(DySymTab.iundefsym);
335   FHOut.outword(DySymTab.nundefsym);
336   FHOut.outword(DySymTab.tocoff);
337   FHOut.outword(DySymTab.ntoc);
338   FHOut.outword(DySymTab.modtaboff);
339   FHOut.outword(DySymTab.nmodtab);
340   FHOut.outword(DySymTab.extrefsymoff);
341   FHOut.outword(DySymTab.nextrefsyms);
342   FHOut.outword(DySymTab.indirectsymoff);
343   FHOut.outword(DySymTab.nindirectsyms);
344   FHOut.outword(DySymTab.extreloff);
345   FHOut.outword(DySymTab.nextrel);
346   FHOut.outword(DySymTab.locreloff);
347   FHOut.outword(DySymTab.nlocrel);
348
349   O.write((char*)&FH[0], FH.size());
350 }
351
352 /// EmitSections - Now that we have constructed the file header and load
353 /// commands, emit the data for each section to the file.
354
355 void MachOWriter::EmitSections() {
356   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
357          E = SectionList.end(); I != E; ++I)
358     // Emit the contents of each section
359     O.write((char*)&(*I)->SectionData[0], (*I)->size);
360 }
361 void MachOWriter::EmitRelocations() {
362   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
363          E = SectionList.end(); I != E; ++I)
364     // Emit the relocation entry data for each section.
365     O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
366 }
367
368 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
369 /// each a string table index so that they appear in the correct order in the
370 /// output file.
371
372 void MachOWriter::BufferSymbolAndStringTable() {
373   // The order of the symbol table is:
374   // 1. local symbols
375   // 2. defined external symbols (sorted by name)
376   // 3. undefined external symbols (sorted by name)
377
378   // Before sorting the symbols, check the PendingGlobals for any undefined
379   // globals that need to be put in the symbol table.
380
381   for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
382          E = PendingGlobals.end(); I != E; ++I) {
383     if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
384       MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TAI);
385       SymbolTable.push_back(UndfSym);
386       GVOffset[*I] = -1;
387     }
388   }
389
390   // Sort the symbols by name, so that when we partition the symbols by scope
391   // of definition, we won't have to sort by name within each partition.
392
393   std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSym::SymCmp());
394
395   // Parition the symbol table entries so that all local symbols come before
396   // all symbols with external linkage. { 1 | 2 3 }
397
398   std::partition(SymbolTable.begin(), SymbolTable.end(),
399                  MachOSym::PartitionByLocal);
400
401   // Advance iterator to beginning of external symbols and partition so that
402   // all external symbols defined in this module come before all external
403   // symbols defined elsewhere. { 1 | 2 | 3 }
404
405   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
406          E = SymbolTable.end(); I != E; ++I) {
407     if (!MachOSym::PartitionByLocal(*I)) {
408       std::partition(I, E, MachOSym::PartitionByDefined);
409       break;
410     }
411   }
412
413   // Calculate the starting index for each of the local, extern defined, and
414   // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
415   // load command.
416
417   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
418          E = SymbolTable.end(); I != E; ++I) {
419     if (MachOSym::PartitionByLocal(*I)) {
420       ++DySymTab.nlocalsym;
421       ++DySymTab.iextdefsym;
422       ++DySymTab.iundefsym;
423     } else if (MachOSym::PartitionByDefined(*I)) {
424       ++DySymTab.nextdefsym;
425       ++DySymTab.iundefsym;
426     } else {
427       ++DySymTab.nundefsym;
428     }
429   }
430
431   // Write out a leading zero byte when emitting string table, for n_strx == 0
432   // which means an empty string.
433
434   OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
435   StrTOut.outbyte(0);
436
437   // The order of the string table is:
438   // 1. strings for external symbols
439   // 2. strings for local symbols
440   // Since this is the opposite order from the symbol table, which we have just
441   // sorted, we can walk the symbol table backwards to output the string table.
442
443   for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
444         E = SymbolTable.rend(); I != E; ++I) {
445     if (I->GVName == "") {
446       I->n_strx = 0;
447     } else {
448       I->n_strx = StrT.size();
449       StrTOut.outstring(I->GVName, I->GVName.length()+1);
450     }
451   }
452
453   OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
454
455   unsigned index = 0;
456   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
457          E = SymbolTable.end(); I != E; ++I, ++index) {
458     // Add the section base address to the section offset in the n_value field
459     // to calculate the full address.
460     // FIXME: handle symbols where the n_value field is not the address
461     GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
462     if (GV && GVSection[GV])
463       I->n_value += GVSection[GV]->addr;
464     if (GV && (GVOffset[GV] == -1))
465       GVOffset[GV] = index;
466
467     // Emit nlist to buffer
468     SymTOut.outword(I->n_strx);
469     SymTOut.outbyte(I->n_type);
470     SymTOut.outbyte(I->n_sect);
471     SymTOut.outhalf(I->n_desc);
472     SymTOut.outaddr(I->n_value);
473   }
474 }
475
476 /// CalculateRelocations - For each MachineRelocation in the current section,
477 /// calculate the index of the section containing the object to be relocated,
478 /// and the offset into that section.  From this information, create the
479 /// appropriate target-specific MachORelocation type and add buffer it to be
480 /// written out after we are finished writing out sections.
481
482 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
483   for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
484     MachineRelocation &MR = MOS.Relocations[i];
485     unsigned TargetSection = MR.getConstantVal();
486     unsigned TargetAddr = 0;
487     unsigned TargetIndex = 0;
488
489     // This is a scattered relocation entry if it points to a global value with
490     // a non-zero offset.
491
492     bool Scattered = false;
493     bool Extern = false;
494
495     // Since we may not have seen the GlobalValue we were interested in yet at
496     // the time we emitted the relocation for it, fix it up now so that it
497     // points to the offset into the correct section.
498
499     if (MR.isGlobalValue()) {
500       GlobalValue *GV = MR.getGlobalValue();
501       MachOSection *MOSPtr = GVSection[GV];
502       intptr_t Offset = GVOffset[GV];
503
504       // If we have never seen the global before, it must be to a symbol
505       // defined in another module (N_UNDF).
506
507       if (!MOSPtr) {
508         // FIXME: need to append stub suffix
509         Extern = true;
510         TargetAddr = 0;
511         TargetIndex = GVOffset[GV];
512       } else {
513         Scattered = TargetSection != 0;
514         TargetSection = MOSPtr->Index;
515       }
516       MR.setResultPointer((void*)Offset);
517     }
518
519     // If the symbol is locally defined, pass in the address of the section and
520     // the section index to the code which will generate the target relocation.
521
522     if (!Extern) {
523         MachOSection &To = *SectionList[TargetSection - 1];
524         TargetAddr = To.addr;
525         TargetIndex = To.Index;
526     }
527
528     OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
529     OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
530
531     MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
532                                       RelocOut, SecOut, Scattered, Extern);
533   }
534 }
535
536 // InitMem - Write the value of a Constant to the specified memory location,
537 // converting it into bytes and relocations.
538
539 void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
540                           const TargetData *TD,
541                           std::vector<MachineRelocation> &MRs) {
542   typedef std::pair<const Constant*, intptr_t> CPair;
543   std::vector<CPair> WorkList;
544
545   WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
546
547   intptr_t ScatteredOffset = 0;
548
549   while (!WorkList.empty()) {
550     const Constant *PC = WorkList.back().first;
551     intptr_t PA = WorkList.back().second;
552     WorkList.pop_back();
553
554     if (isa<UndefValue>(PC)) {
555       continue;
556     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
557       unsigned ElementSize =
558         TD->getTypeAllocSize(CP->getType()->getElementType());
559       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
560         WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
561     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
562       //
563       // FIXME: Handle ConstantExpression.  See EE::getConstantValue()
564       //
565       switch (CE->getOpcode()) {
566       case Instruction::GetElementPtr: {
567         SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
568         ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
569                                                &Indices[0], Indices.size());
570         WorkList.push_back(CPair(CE->getOperand(0), PA));
571         break;
572       }
573       case Instruction::Add:
574       default:
575         cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
576         abort();
577         break;
578       }
579     } else if (PC->getType()->isSingleValueType()) {
580       unsigned char *ptr = (unsigned char *)PA;
581       switch (PC->getType()->getTypeID()) {
582       case Type::IntegerTyID: {
583         unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
584         uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
585         if (NumBits <= 8)
586           ptr[0] = val;
587         else if (NumBits <= 16) {
588           if (TD->isBigEndian())
589             val = ByteSwap_16(val);
590           ptr[0] = val;
591           ptr[1] = val >> 8;
592         } else if (NumBits <= 32) {
593           if (TD->isBigEndian())
594             val = ByteSwap_32(val);
595           ptr[0] = val;
596           ptr[1] = val >> 8;
597           ptr[2] = val >> 16;
598           ptr[3] = val >> 24;
599         } else if (NumBits <= 64) {
600           if (TD->isBigEndian())
601             val = ByteSwap_64(val);
602           ptr[0] = val;
603           ptr[1] = val >> 8;
604           ptr[2] = val >> 16;
605           ptr[3] = val >> 24;
606           ptr[4] = val >> 32;
607           ptr[5] = val >> 40;
608           ptr[6] = val >> 48;
609           ptr[7] = val >> 56;
610         } else {
611           assert(0 && "Not implemented: bit widths > 64");
612         }
613         break;
614       }
615       case Type::FloatTyID: {
616         uint32_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
617                         getZExtValue();
618         if (TD->isBigEndian())
619           val = ByteSwap_32(val);
620         ptr[0] = val;
621         ptr[1] = val >> 8;
622         ptr[2] = val >> 16;
623         ptr[3] = val >> 24;
624         break;
625       }
626       case Type::DoubleTyID: {
627         uint64_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
628                          getZExtValue();
629         if (TD->isBigEndian())
630           val = ByteSwap_64(val);
631         ptr[0] = val;
632         ptr[1] = val >> 8;
633         ptr[2] = val >> 16;
634         ptr[3] = val >> 24;
635         ptr[4] = val >> 32;
636         ptr[5] = val >> 40;
637         ptr[6] = val >> 48;
638         ptr[7] = val >> 56;
639         break;
640       }
641       case Type::PointerTyID:
642         if (isa<ConstantPointerNull>(PC))
643           memset(ptr, 0, TD->getPointerSize());
644         else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
645           // FIXME: what about function stubs?
646           MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr, 
647                                                  MachineRelocation::VANILLA,
648                                                  const_cast<GlobalValue*>(GV),
649                                                  ScatteredOffset));
650           ScatteredOffset = 0;
651         } else
652           assert(0 && "Unknown constant pointer type!");
653         break;
654       default:
655         cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
656         abort();
657       }
658     } else if (isa<ConstantAggregateZero>(PC)) {
659       memset((void*)PA, 0, (size_t)TD->getTypeAllocSize(PC->getType()));
660     } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
661       unsigned ElementSize =
662         TD->getTypeAllocSize(CPA->getType()->getElementType());
663       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
664         WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
665     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
666       const StructLayout *SL =
667         TD->getStructLayout(cast<StructType>(CPS->getType()));
668       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
669         WorkList.push_back(CPair(CPS->getOperand(i),
670                                  PA+SL->getElementOffset(i)));
671     } else {
672       cerr << "Bad Type: " << *PC->getType() << "\n";
673       assert(0 && "Unknown constant type to initialize memory with!");
674     }
675   }
676 }
677
678 //===----------------------------------------------------------------------===//
679 //                          MachOSym Implementation
680 //===----------------------------------------------------------------------===//
681
682 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
683                    const TargetAsmInfo *TAI) :
684   GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
685   n_desc(0), n_value(0) {
686
687   switch (GV->getLinkage()) {
688   default:
689     assert(0 && "Unexpected linkage type!");
690     break;
691   case GlobalValue::WeakAnyLinkage:
692   case GlobalValue::WeakODRLinkage:
693   case GlobalValue::LinkOnceAnyLinkage:
694   case GlobalValue::LinkOnceODRLinkage:
695   case GlobalValue::CommonLinkage:
696     assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
697   case GlobalValue::ExternalLinkage:
698     GVName = TAI->getGlobalPrefix() + name;
699     n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
700     break;
701   case GlobalValue::PrivateLinkage:
702     GVName = TAI->getPrivateGlobalPrefix() + name;
703     break;
704   case GlobalValue::InternalLinkage:
705     GVName = TAI->getGlobalPrefix() + name;
706     break;
707   }
708 }
709
710 } // end namespace llvm
711