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