Zimm16 is now dead. Its entry is not removed from the enum, to avoid having
[oota-llvm.git] / lib / Target / PowerPC / PPCAsmPrinter.cpp
1 //===-- PPC32AsmPrinter.cpp - Print machine instrs to PowerPC assembly ----===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
13 //
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "asmprinter"
20 #include "PowerPC.h"
21 #include "PowerPCInstrInfo.h"
22 #include "PowerPCTargetMachine.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Support/Mangler.h"
33 #include "Support/CommandLine.h"
34 #include "Support/Debug.h"
35 #include "Support/Statistic.h"
36 #include "Support/StringExtras.h"
37 #include <set>
38
39 namespace llvm {
40
41 namespace {
42   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
43
44   struct PowerPCAsmPrinter : public MachineFunctionPass {
45     /// Output stream on which we're printing assembly code.
46     ///
47     std::ostream &O;
48
49     /// Target machine description which we query for reg. names, data
50     /// layout, etc.
51     ///
52     PowerPCTargetMachine &TM;
53
54     /// Name-mangler for global names.
55     ///
56     Mangler *Mang;
57     std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
58     std::set<std::string> Strings;
59
60     PowerPCAsmPrinter(std::ostream &o, TargetMachine &tm) : O(o),
61       TM(reinterpret_cast<PowerPCTargetMachine&>(tm)), LabelNumber(0) {}
62
63     /// Cache of mangled name for current function. This is
64     /// recalculated at the beginning of each call to
65     /// runOnMachineFunction().
66     ///
67     std::string CurrentFnName;
68
69     /// Unique incrementer for label values for referencing Global values.
70     ///
71     unsigned LabelNumber;
72   
73     virtual const char *getPassName() const {
74       return "PowerPC Assembly Printer";
75     }
76
77     /// printInstruction - This method is automatically generated by tablegen
78     /// from the instruction set description.  This method returns true if the
79     /// machine instruction was sufficiently described to print it, otherwise it
80     /// returns false.
81     bool printInstruction(const MachineInstr *MI);
82
83     void printMachineInstruction(const MachineInstr *MI);
84     void printOp(const MachineOperand &MO, bool LoadAddrOp = false);
85     void printImmOp(const MachineOperand &MO, unsigned ArgType);
86
87     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
88       const MachineOperand &MO = MI->getOperand(OpNo);
89       if (MO.getType() == MachineOperand::MO_MachineRegister) {
90         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
91         O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
92       } else if (MO.isImmediate()) {
93         O << MO.getImmedValue();
94       } else {
95         printOp(MO);
96       }
97     }
98
99     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
100                             MVT::ValueType VT) {
101       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
102     }
103
104     void printConstantPool(MachineConstantPool *MCP);
105     bool runOnMachineFunction(MachineFunction &F);    
106     bool doInitialization(Module &M);
107     bool doFinalization(Module &M);
108     void emitGlobalConstant(const Constant* CV);
109     void emitConstantValueOnly(const Constant *CV);
110   };
111 } // end of anonymous namespace
112
113 /// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
114 /// assembly code for a MachineFunction to the given output stream,
115 /// using the given target machine description.  This should work
116 /// regardless of whether the function is in SSA form or not.
117 ///
118 FunctionPass *createPPCAsmPrinter(std::ostream &o,TargetMachine &tm) {
119   return new PowerPCAsmPrinter(o, tm);
120 }
121
122 // Include the auto-generated portion of the assembly writer
123 #include "PowerPCGenAsmWriter.inc"
124
125 /// isStringCompatible - Can we treat the specified array as a string?
126 /// Only if it is an array of ubytes or non-negative sbytes.
127 ///
128 static bool isStringCompatible(const ConstantArray *CVA) {
129   const Type *ETy = cast<ArrayType>(CVA->getType())->getElementType();
130   if (ETy == Type::UByteTy) return true;
131   if (ETy != Type::SByteTy) return false;
132
133   for (unsigned i = 0; i < CVA->getNumOperands(); ++i)
134     if (cast<ConstantSInt>(CVA->getOperand(i))->getValue() < 0)
135       return false;
136
137   return true;
138 }
139
140 /// toOctal - Convert the low order bits of X into an octal digit.
141 ///
142 static inline char toOctal(int X) {
143   return (X&7)+'0';
144 }
145
146 /// getAsCString - Return the specified array as a C compatible
147 /// string, only if the predicate isStringCompatible is true.
148 ///
149 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
150   assert(isStringCompatible(CVA) && "Array is not string compatible!");
151
152   O << "\"";
153   for (unsigned i = 0; i < CVA->getNumOperands(); ++i) {
154     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
155
156     if (C == '"') {
157       O << "\\\"";
158     } else if (C == '\\') {
159       O << "\\\\";
160     } else if (isprint(C)) {
161       O << C;
162     } else {
163       switch (C) {
164       case '\b': O << "\\b"; break;
165       case '\f': O << "\\f"; break;
166       case '\n': O << "\\n"; break;
167       case '\r': O << "\\r"; break;
168       case '\t': O << "\\t"; break;
169       default:
170         O << '\\';
171         O << toOctal(C >> 6);
172         O << toOctal(C >> 3);
173         O << toOctal(C >> 0);
174         break;
175       }
176     }
177   }
178   O << "\"";
179 }
180
181 // Print out the specified constant, without a storage class.  Only the
182 // constants valid in constant expressions can occur here.
183 void PowerPCAsmPrinter::emitConstantValueOnly(const Constant *CV) {
184   if (CV->isNullValue())
185     O << "0";
186   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
187     assert(CB == ConstantBool::True);
188     O << "1";
189   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
190     O << CI->getValue();
191   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
192     O << CI->getValue();
193   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
194     // This is a constant address for a global variable or function.  Use the
195     // name of the variable or function as the address value.
196     O << Mang->getValueName(GV);
197   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
198     const TargetData &TD = TM.getTargetData();
199     switch (CE->getOpcode()) {
200     case Instruction::GetElementPtr: {
201       // generate a symbolic expression for the byte address
202       const Constant *ptrVal = CE->getOperand(0);
203       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
204       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
205         O << "(";
206         emitConstantValueOnly(ptrVal);
207         O << ") + " << Offset;
208       } else {
209         emitConstantValueOnly(ptrVal);
210       }
211       break;
212     }
213     case Instruction::Cast: {
214       // Support only non-converting or widening casts for now, that is, ones
215       // that do not involve a change in value.  This assertion is really gross,
216       // and may not even be a complete check.
217       Constant *Op = CE->getOperand(0);
218       const Type *OpTy = Op->getType(), *Ty = CE->getType();
219
220       // Remember, kids, pointers on x86 can be losslessly converted back and
221       // forth into 32-bit or wider integers, regardless of signedness. :-P
222       assert(((isa<PointerType>(OpTy)
223                && (Ty == Type::LongTy || Ty == Type::ULongTy
224                    || Ty == Type::IntTy || Ty == Type::UIntTy))
225               || (isa<PointerType>(Ty)
226                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
227                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
228               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
229                    && OpTy->isLosslesslyConvertibleTo(Ty))))
230              && "FIXME: Don't yet support this kind of constant cast expr");
231       O << "(";
232       emitConstantValueOnly(Op);
233       O << ")";
234       break;
235     }
236     case Instruction::Add:
237       O << "(";
238       emitConstantValueOnly(CE->getOperand(0));
239       O << ") + (";
240       emitConstantValueOnly(CE->getOperand(1));
241       O << ")";
242       break;
243     default:
244       assert(0 && "Unsupported operator!");
245     }
246   } else {
247     assert(0 && "Unknown constant value!");
248   }
249 }
250
251 // Print a constant value or values, with the appropriate storage class as a
252 // prefix.
253 void PowerPCAsmPrinter::emitGlobalConstant(const Constant *CV) {  
254   const TargetData &TD = TM.getTargetData();
255
256   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
257     if (isStringCompatible(CVA)) {
258       O << "\t.ascii ";
259       printAsCString(O, CVA);
260       O << "\n";
261     } else { // Not a string.  Print the values in successive locations
262       for (unsigned i=0, e = CVA->getNumOperands(); i != e; i++)
263         emitGlobalConstant(CVA->getOperand(i));
264     }
265     return;
266   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
267     // Print the fields in successive locations. Pad to align if needed!
268     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
269     unsigned sizeSoFar = 0;
270     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; i++) {
271       const Constant* field = CVS->getOperand(i);
272
273       // Check if padding is needed and insert one or more 0s.
274       unsigned fieldSize = TD.getTypeSize(field->getType());
275       unsigned padSize = ((i == e-1? cvsLayout->StructSize
276                            : cvsLayout->MemberOffsets[i+1])
277                           - cvsLayout->MemberOffsets[i]) - fieldSize;
278       sizeSoFar += fieldSize + padSize;
279
280       // Now print the actual field value
281       emitGlobalConstant(field);
282
283       // Insert the field padding unless it's zero bytes...
284       if (padSize)
285         O << "\t.space\t " << padSize << "\n";      
286     }
287     assert(sizeSoFar == cvsLayout->StructSize &&
288            "Layout of constant struct may be incorrect!");
289     return;
290   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
291     // FP Constants are printed as integer constants to avoid losing
292     // precision...
293     double Val = CFP->getValue();
294     union DU {                            // Abide by C TBAA rules
295       double FVal;
296       uint64_t UVal;
297       struct {
298         uint32_t MSWord;
299         uint32_t LSWord;
300       } T;
301     } U;
302     U.FVal = Val;
303     
304     O << ".long\t" << U.T.MSWord << "\t; double most significant word " 
305       << Val << "\n";
306     O << ".long\t" << U.T.LSWord << "\t; double least significant word " 
307       << Val << "\n";
308     return;
309   } else if (CV->getType() == Type::ULongTy || CV->getType() == Type::LongTy) {
310     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
311       union DU {                            // Abide by C TBAA rules
312         int64_t UVal;
313         struct {
314           uint32_t MSWord;
315           uint32_t LSWord;
316         } T;
317       } U;
318       U.UVal = CI->getRawValue();
319         
320       O << ".long\t" << U.T.MSWord << "\t; Double-word most significant word " 
321         << U.UVal << "\n";
322       O << ".long\t" << U.T.LSWord << "\t; Double-word least significant word " 
323         << U.UVal << "\n";
324       return;
325     }
326   }
327
328   const Type *type = CV->getType();
329   O << "\t";
330   switch (type->getTypeID()) {
331   case Type::UByteTyID: case Type::SByteTyID:
332     O << ".byte";
333     break;
334   case Type::UShortTyID: case Type::ShortTyID:
335     O << ".short";
336     break;
337   case Type::BoolTyID: 
338   case Type::PointerTyID:
339   case Type::UIntTyID: case Type::IntTyID:
340     O << ".long";
341     break;
342   case Type::ULongTyID: case Type::LongTyID:    
343     assert (0 && "Should have already output double-word constant.");
344   case Type::FloatTyID: case Type::DoubleTyID:
345     assert (0 && "Should have already output floating point constant.");
346   default:
347     if (CV == Constant::getNullValue(type)) {  // Zero initializer?
348       O << ".space\t" << TD.getTypeSize(type) << "\n";      
349       return;
350     }
351     std::cerr << "Can't handle printing: " << *CV;
352     abort();
353     break;
354   }
355   O << "\t";
356   emitConstantValueOnly(CV);
357   O << "\n";
358 }
359
360 /// printConstantPool - Print to the current output stream assembly
361 /// representations of the constants in the constant pool MCP. This is
362 /// used to print out constants which have been "spilled to memory" by
363 /// the code generator.
364 ///
365 void PowerPCAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
366   const std::vector<Constant*> &CP = MCP->getConstants();
367   const TargetData &TD = TM.getTargetData();
368  
369   if (CP.empty()) return;
370
371   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
372     O << "\t.const\n";
373     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
374       << "\n";
375     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
376       << *CP[i] << "\n";
377     emitGlobalConstant(CP[i]);
378   }
379 }
380
381 /// runOnMachineFunction - This uses the printMachineInstruction()
382 /// method to print assembly for each instruction.
383 ///
384 bool PowerPCAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
385   O << "\n\n";
386   // What's my mangled name?
387   CurrentFnName = Mang->getValueName(MF.getFunction());
388
389   // Print out constants referenced by the function
390   printConstantPool(MF.getConstantPool());
391
392   // Print out labels for the function.
393   O << "\t.text\n"; 
394   O << "\t.globl\t" << CurrentFnName << "\n";
395   O << "\t.align 2\n";
396   O << CurrentFnName << ":\n";
397
398   // Print out code for the function.
399   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
400        I != E; ++I) {
401     // Print a label for the basic block.
402     O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
403       << I->getBasicBlock()->getName() << "\n";
404     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
405       II != E; ++II) {
406       // Print the assembly for the instruction.
407       O << "\t";
408       printMachineInstruction(II);
409     }
410   }
411   ++LabelNumber;
412
413   // We didn't modify anything.
414   return false;
415 }
416
417 void PowerPCAsmPrinter::printOp(const MachineOperand &MO,
418                       bool LoadAddrOp /* = false */) {
419   const MRegisterInfo &RI = *TM.getRegisterInfo();
420   int new_symbol;
421   
422   switch (MO.getType()) {
423   case MachineOperand::MO_VirtualRegister:
424     if (Value *V = MO.getVRegValueOrNull()) {
425       O << "<" << V->getName() << ">";
426       return;
427     }
428     // FALLTHROUGH
429   case MachineOperand::MO_MachineRegister:
430   case MachineOperand::MO_CCRegister:
431     O << LowercaseString(RI.get(MO.getReg()).Name);
432     return;
433
434   case MachineOperand::MO_SignExtendedImmed:
435   case MachineOperand::MO_UnextendedImmed:
436     std::cerr << "printOp() does not handle immediate values\n";
437     abort();
438     return;
439
440   case MachineOperand::MO_PCRelativeDisp:
441     std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
442     abort();
443     return;
444     
445   case MachineOperand::MO_MachineBasicBlock: {
446     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
447     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
448       << "_" << MBBOp->getNumber() << "\t; "
449       << MBBOp->getBasicBlock()->getName();
450     return;
451   }
452
453   case MachineOperand::MO_ConstantPoolIndex:
454     O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
455     return;
456
457   case MachineOperand::MO_ExternalSymbol:
458     O << MO.getSymbolName();
459     return;
460
461   case MachineOperand::MO_GlobalAddress: {
462     GlobalValue *GV = MO.getGlobal();
463     std::string Name = Mang->getValueName(GV);
464
465     // Dynamically-resolved functions need a stub for the function.  Be
466     // wary however not to output $stub for external functions whose addresses
467     // are taken.  Those should be emitted as $non_lazy_ptr below.
468     Function *F = dyn_cast<Function>(GV);
469     if (F && F->isExternal() && !LoadAddrOp &&
470         TM.CalledFunctions.find(F) != TM.CalledFunctions.end()) {
471       FnStubs.insert(Name);
472       O << "L" << Name << "$stub";
473       return;
474     }
475     
476     // External global variables need a non-lazily-resolved stub
477     if (GV->isExternal() && TM.AddressTaken.find(GV) != TM.AddressTaken.end()) {
478       GVStubs.insert(Name);
479       O << "L" << Name << "$non_lazy_ptr";
480       return;
481     }
482     
483     if (F && LoadAddrOp && TM.AddressTaken.find(GV) != TM.AddressTaken.end()) {
484       LinkOnceStubs.insert(Name);
485       O << "L" << Name << "$non_lazy_ptr";
486       return;
487     }
488             
489     O << Mang->getValueName(GV);
490     return;
491   }
492     
493   default:
494     O << "<unknown operand type: " << MO.getType() << ">";
495     return;
496   }
497 }
498
499 void PowerPCAsmPrinter::printImmOp(const MachineOperand &MO, unsigned ArgType) {
500   int Imm = MO.getImmedValue();
501   if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
502     O << (short)Imm;
503   } else {
504     O << Imm;
505   }
506 }
507
508 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
509 /// the current output stream.
510 ///
511 void PowerPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
512   ++EmittedInsts;
513   if (printInstruction(MI))
514     return; // Printer was automatically generated
515     
516   unsigned Opcode = MI->getOpcode();
517   const TargetInstrInfo &TII = *TM.getInstrInfo();
518   const TargetInstrDescriptor &Desc = TII.get(Opcode);
519   unsigned i;
520
521   unsigned ArgCount = MI->getNumOperands();
522   unsigned ArgType[] = {
523     (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
524     (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
525     (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
526     (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
527     (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
528   };
529   assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
530          "Instruction requires VMX support");
531   assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
532          "Instruction requires 64 bit support");
533
534   // CALLpcrel and CALLindirect are handled specially here to print only the
535   // appropriate number of args that the assembler expects.  This is because
536   // may have many arguments appended to record the uses of registers that are
537   // holding arguments to the called function.
538   if (Opcode == PPC::COND_BRANCH) {
539     std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
540     abort();
541   } else if (Opcode == PPC::IMPLICIT_DEF) {
542     O << "; IMPLICIT DEF ";
543     printOp(MI->getOperand(0));
544     O << "\n";
545     return;
546   } else if (Opcode == PPC::CALLpcrel) {
547     O << TII.getName(Opcode) << " ";
548     printOp(MI->getOperand(0));
549     O << "\n";
550     return;
551   } else if (Opcode == PPC::CALLindirect) {
552     O << TII.getName(Opcode) << " ";
553     printImmOp(MI->getOperand(0), ArgType[0]);
554     O << ", ";
555     printImmOp(MI->getOperand(1), ArgType[0]);
556     O << "\n";
557     return;
558   } else if (Opcode == PPC::MovePCtoLR) {
559     // FIXME: should probably be converted to cout.width and cout.fill
560     O << "bl \"L0000" << LabelNumber << "$pb\"\n";
561     O << "\"L0000" << LabelNumber << "$pb\":\n";
562     O << "\tmflr ";
563     printOp(MI->getOperand(0));
564     O << "\n";
565     return;
566   }
567
568   O << TII.getName(Opcode) << " ";
569   if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
570     printOp(MI->getOperand(0));
571     O << ", lo16(";
572     printOp(MI->getOperand(2), true /* LoadAddrOp */);
573     O << "-\"L0000" << LabelNumber << "$pb\")";
574     O << "(";
575     if (MI->getOperand(1).getReg() == PPC::R0)
576       O << "0";
577     else
578       printOp(MI->getOperand(1));
579     O << ")\n";
580   } else if (Opcode == PPC::LOADHiAddr) {
581     printOp(MI->getOperand(0));
582     O << ", ";
583     if (MI->getOperand(1).getReg() == PPC::R0)
584       O << "0";
585     else
586       printOp(MI->getOperand(1));
587     O << ", ha16(" ;
588     printOp(MI->getOperand(2), true /* LoadAddrOp */);
589      O << "-\"L0000" << LabelNumber << "$pb\")\n";
590   } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
591     printOp(MI->getOperand(0));
592     O << ", ";
593     printImmOp(MI->getOperand(1), ArgType[1]);
594     O << "(";
595     if (MI->getOperand(2).hasAllocatedReg() &&
596         MI->getOperand(2).getReg() == PPC::R0)
597       O << "0";
598     else
599       printOp(MI->getOperand(2));
600     O << ")\n";
601   } else {
602     for (i = 0; i < ArgCount; ++i) {
603       // addi and friends
604       if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
605           MI->getOperand(1).hasAllocatedReg() && 
606           MI->getOperand(1).getReg() == PPC::R0) {
607         O << "0";
608       // for long branch support, bc $+8
609       } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
610                  TII.isBranch(MI->getOpcode())) {
611         O << "$+8";
612         assert(8 == MI->getOperand(i).getImmedValue()
613           && "branch off PC not to pc+8?");
614         //printOp(MI->getOperand(i));
615       } else if (MI->getOperand(i).isImmediate()) {
616         printImmOp(MI->getOperand(i), ArgType[i]);
617       } else {
618         printOp(MI->getOperand(i));
619       }
620       if (ArgCount - 1 == i)
621         O << "\n";
622       else
623         O << ", ";
624     }
625   }
626   return;
627 }
628
629 bool PowerPCAsmPrinter::doInitialization(Module &M) {
630   Mang = new Mangler(M, true);
631   return false; // success
632 }
633
634 // SwitchSection - Switch to the specified section of the executable if we are
635 // not already in it!
636 //
637 static void SwitchSection(std::ostream &OS, std::string &CurSection,
638                           const char *NewSection) {
639   if (CurSection != NewSection) {
640     CurSection = NewSection;
641     if (!CurSection.empty())
642       OS << "\t" << NewSection << "\n";
643   }
644 }
645
646 bool PowerPCAsmPrinter::doFinalization(Module &M) {
647   const TargetData &TD = TM.getTargetData();
648   std::string CurSection;
649
650   // Print out module-level global variables here.
651   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
652     if (I->hasInitializer()) {   // External global require no code
653       O << "\n\n";
654       std::string name = Mang->getValueName(I);
655       Constant *C = I->getInitializer();
656       unsigned Size = TD.getTypeSize(C->getType());
657       unsigned Align = TD.getTypeAlignment(C->getType());
658
659       if (C->isNullValue() && /* FIXME: Verify correct */
660           (I->hasInternalLinkage() || I->hasWeakLinkage())) {
661         SwitchSection(O, CurSection, ".data");
662         if (I->hasInternalLinkage())
663           O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
664             << "," << (unsigned)TD.getTypeAlignment(C->getType());
665         else 
666           O << ".comm " << name << "," << TD.getTypeSize(C->getType());
667         O << "\t\t; ";
668         WriteAsOperand(O, I, true, true, &M);
669         O << "\n";
670       } else {
671         switch (I->getLinkage()) {
672         case GlobalValue::LinkOnceLinkage:
673           O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
674             << ".weak_definition " << name << '\n'
675             << ".private_extern " << name << '\n'
676             << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
677           LinkOnceStubs.insert(name);
678           break;  
679         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
680           // Nonnull linkonce -> weak
681           O << "\t.weak " << name << "\n";
682           SwitchSection(O, CurSection, "");
683           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
684           break;
685         case GlobalValue::AppendingLinkage:
686           // FIXME: appending linkage variables should go into a section of
687           // their name or something.  For now, just emit them as external.
688         case GlobalValue::ExternalLinkage:
689           // If external or appending, declare as a global symbol
690           O << "\t.globl " << name << "\n";
691           // FALL THROUGH
692         case GlobalValue::InternalLinkage:
693           SwitchSection(O, CurSection, ".data");
694           break;
695         }
696
697         O << "\t.align " << Align << "\n";
698         O << name << ":\t\t\t\t; ";
699         WriteAsOperand(O, I, true, true, &M);
700         O << " = ";
701         WriteAsOperand(O, C, false, false, &M);
702         O << "\n";
703         emitGlobalConstant(C);
704       }
705     }
706
707   // Output stubs for dynamically-linked functions
708   for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); 
709        i != e; ++i)
710   {
711     O << ".data\n";
712     O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
713     O << "\t.align 2\n";
714     O << "L" << *i << "$stub:\n";
715     O << "\t.indirect_symbol " << *i << "\n";
716     O << "\tmflr r0\n";
717     O << "\tbcl 20,31,L0$" << *i << "\n";
718     O << "L0$" << *i << ":\n";
719     O << "\tmflr r11\n";
720     O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
721     O << "\tmtlr r0\n";
722     O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
723     O << "\tmtctr r12\n";
724     O << "\tbctr\n";
725     O << ".data\n";
726     O << ".lazy_symbol_pointer\n";
727     O << "L" << *i << "$lazy_ptr:\n";
728     O << "\t.indirect_symbol " << *i << "\n";
729     O << "\t.long dyld_stub_binding_helper\n";
730   }
731
732   O << "\n";
733
734   // Output stubs for external global variables
735   if (GVStubs.begin() != GVStubs.end())
736     O << ".data\n.non_lazy_symbol_pointer\n";
737   for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end(); 
738        i != e; ++i) {
739     O << "L" << *i << "$non_lazy_ptr:\n";
740     O << "\t.indirect_symbol " << *i << "\n";
741     O << "\t.long\t0\n";
742   }
743   
744   // Output stubs for link-once variables
745   if (LinkOnceStubs.begin() != LinkOnceStubs.end())
746     O << ".data\n.align 2\n";
747   for (std::set<std::string>::iterator i = LinkOnceStubs.begin(), 
748          e = LinkOnceStubs.end(); i != e; ++i) {
749     O << "L" << *i << "$non_lazy_ptr:\n"
750       << "\t.long\t" << *i << '\n';
751   }
752   
753   delete Mang;
754   return false; // success
755 }
756
757 } // End llvm namespace