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