refactor call operand handling to eliminate special cases from printOp.
[oota-llvm.git] / lib / Target / PowerPC / PPCAsmPrinter.cpp
1 //===-- PPCAsmPrinter.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 "PPC.h"
21 #include "PPCTargetMachine.h"
22 #include "PPCSubtarget.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/AsmPrinter.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Target/MRegisterInfo.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include <set>
41 using namespace llvm;
42
43 namespace {
44   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
45
46   class PPCAsmPrinter : public AsmPrinter {
47     std::string CurSection;
48   public:
49     std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
50     
51     PPCAsmPrinter(std::ostream &O, TargetMachine &TM)
52       : AsmPrinter(O, TM), FunctionNumber(0) {}
53
54     /// Unique incrementer for label values for referencing Global values.
55     ///
56     unsigned FunctionNumber;
57
58     virtual const char *getPassName() const {
59       return "PowerPC Assembly Printer";
60     }
61
62     PPCTargetMachine &getTM() {
63       return static_cast<PPCTargetMachine&>(TM);
64     }
65
66     /// SwitchSection - Switch to the specified section of the executable if we
67     /// are not already in it!
68     ///
69     void SwitchSection(const char *NewSection, const GlobalValue *GV) {
70       std::string NS;
71       
72       if (GV && GV->hasSection())
73         NS = ".section " + GV->getSection();
74       else
75         NS = NewSection;
76       
77       if (CurSection != NS) {
78         CurSection = NS;
79         if (!CurSection.empty())
80           O << "\t" << CurSection << "\n";
81       }
82     }
83     
84     unsigned enumRegToMachineReg(unsigned enumReg) {
85       switch (enumReg) {
86       default: assert(0 && "Unhandled register!"); break;
87       case PPC::CR0:  return  0;
88       case PPC::CR1:  return  1;
89       case PPC::CR2:  return  2;
90       case PPC::CR3:  return  3;
91       case PPC::CR4:  return  4;
92       case PPC::CR5:  return  5;
93       case PPC::CR6:  return  6;
94       case PPC::CR7:  return  7;
95       }
96       abort();
97     }
98
99     /// printInstruction - This method is automatically generated by tablegen
100     /// from the instruction set description.  This method returns true if the
101     /// machine instruction was sufficiently described to print it, otherwise it
102     /// returns false.
103     bool printInstruction(const MachineInstr *MI);
104
105     void printMachineInstruction(const MachineInstr *MI);
106     void printOp(const MachineOperand &MO);
107
108     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
109       const MachineOperand &MO = MI->getOperand(OpNo);
110       if (MO.getType() == MachineOperand::MO_MachineRegister) {
111         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
112         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
113       } else if (MO.isImmediate()) {
114         O << MO.getImmedValue();
115       } else {
116         printOp(MO);
117       }
118     }
119
120     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo,
121                             MVT::ValueType VT) {
122       unsigned char value = MI->getOperand(OpNo).getImmedValue();
123       assert(value <= 31 && "Invalid u5imm argument!");
124       O << (unsigned int)value;
125     }
126     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo,
127                             MVT::ValueType VT) {
128       unsigned char value = MI->getOperand(OpNo).getImmedValue();
129       assert(value <= 63 && "Invalid u6imm argument!");
130       O << (unsigned int)value;
131     }
132     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
133                             MVT::ValueType VT) {
134       O << (short)MI->getOperand(OpNo).getImmedValue();
135     }
136     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
137                             MVT::ValueType VT) {
138       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
139     }
140     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo,
141                               MVT::ValueType VT) {
142       O << (short)MI->getOperand(OpNo).getImmedValue()*4;
143     }
144     void printBranchOperand(const MachineInstr *MI, unsigned OpNo,
145                             MVT::ValueType VT) {
146       // Branches can take an immediate operand.  This is used by the branch
147       // selection pass to print $+8, an eight byte displacement from the PC.
148       if (MI->getOperand(OpNo).isImmediate()) {
149         O << "$+" << MI->getOperand(OpNo).getImmedValue();
150       } else {
151         printOp(MI->getOperand(OpNo));
152       }
153     }
154     void printCallOperand(const MachineInstr *MI, unsigned OpNo,
155                           MVT::ValueType VT) {
156       const MachineOperand &MO = MI->getOperand(OpNo);
157       if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
158         std::string Name(GlobalPrefix); Name += MO.getSymbolName();
159         FnStubs.insert(Name);
160         O << "L" << Name << "$stub";
161       } else if (MO.getType() == MachineOperand::MO_GlobalAddress &&
162                  isa<Function>(MO.getGlobal()) && 
163                  cast<Function>(MO.getGlobal())->isExternal()) {
164         // Dynamically-resolved functions need a stub for the function.
165         std::string Name = Mang->getValueName(MO.getGlobal());
166         FnStubs.insert(Name);
167         O << "L" << Name << "$stub";
168       } else {
169         printOp(MI->getOperand(OpNo));
170       }
171     }
172     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo,
173                              MVT::ValueType VT) {
174      O << (int)MI->getOperand(OpNo).getImmedValue()*4;
175     }
176     void printPICLabel(const MachineInstr *MI, unsigned OpNo,
177                        MVT::ValueType VT) {
178       // FIXME: should probably be converted to cout.width and cout.fill
179       O << "\"L0000" << FunctionNumber << "$pb\"\n";
180       O << "\"L0000" << FunctionNumber << "$pb\":";
181     }
182     void printSymbolHi(const MachineInstr *MI, unsigned OpNo,
183                        MVT::ValueType VT) {
184       if (MI->getOperand(OpNo).isImmediate()) {
185         printS16ImmOperand(MI, OpNo, VT);
186       } else {
187         O << "ha16(";
188         printOp(MI->getOperand(OpNo));
189         if (PICEnabled)
190           O << "-\"L0000" << FunctionNumber << "$pb\")";
191         else
192           O << ')';
193       }
194     }
195     void printSymbolLo(const MachineInstr *MI, unsigned OpNo,
196                        MVT::ValueType VT) {
197       if (MI->getOperand(OpNo).isImmediate()) {
198         printS16ImmOperand(MI, OpNo, VT);
199       } else {
200         O << "lo16(";
201         printOp(MI->getOperand(OpNo));
202         if (PICEnabled)
203           O << "-\"L0000" << FunctionNumber << "$pb\")";
204         else
205           O << ')';
206       }
207     }
208     void printcrbitm(const MachineInstr *MI, unsigned OpNo,
209                        MVT::ValueType VT) {
210       unsigned CCReg = MI->getOperand(OpNo).getReg();
211       unsigned RegNo = enumRegToMachineReg(CCReg);
212       O << (0x80 >> RegNo);
213     }
214
215     virtual void printConstantPool(MachineConstantPool *MCP) = 0;
216     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
217     virtual bool doFinalization(Module &M) = 0;
218   };
219
220   /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
221   /// X
222   ///
223   struct DarwinAsmPrinter : public PPCAsmPrinter {
224
225     DarwinAsmPrinter(std::ostream &O, TargetMachine &TM)
226       : PPCAsmPrinter(O, TM) {
227       CommentString = ";";
228       GlobalPrefix = "_";
229       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
230       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
231       AlignmentIsInBytes = false;    // Alignment is by power of 2.
232     }
233
234     virtual const char *getPassName() const {
235       return "Darwin PPC Assembly Printer";
236     }
237
238     void printConstantPool(MachineConstantPool *MCP);
239     bool runOnMachineFunction(MachineFunction &F);
240     bool doInitialization(Module &M);
241     bool doFinalization(Module &M);
242   };
243
244   /// AIXAsmPrinter - PowerPC assembly printer, customized for AIX
245   ///
246   struct AIXAsmPrinter : public PPCAsmPrinter {
247     /// Map for labels corresponding to global variables
248     ///
249     std::map<const GlobalVariable*,std::string> GVToLabelMap;
250
251     AIXAsmPrinter(std::ostream &O, TargetMachine &TM)
252       : PPCAsmPrinter(O, TM) {
253       CommentString = "#";
254       GlobalPrefix = ".";
255       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
256       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
257       AlignmentIsInBytes = false;    // Alignment is by power of 2.
258     }
259
260     virtual const char *getPassName() const {
261       return "AIX PPC Assembly Printer";
262     }
263
264     void printConstantPool(MachineConstantPool *MCP);
265     bool runOnMachineFunction(MachineFunction &F);
266     bool doInitialization(Module &M);
267     bool doFinalization(Module &M);
268   };
269 } // end of anonymous namespace
270
271 /// createDarwinAsmPrinterPass - Returns a pass that prints the PPC assembly
272 /// code for a MachineFunction to the given output stream, in a format that the
273 /// Darwin assembler can deal with.
274 ///
275 FunctionPass *llvm::createDarwinAsmPrinter(std::ostream &o, TargetMachine &tm) {
276   return new DarwinAsmPrinter(o, tm);
277 }
278
279 /// createAIXAsmPrinterPass - Returns a pass that prints the PPC assembly code
280 /// for a MachineFunction to the given output stream, in a format that the
281 /// AIX 5L assembler can deal with.
282 ///
283 FunctionPass *llvm::createAIXAsmPrinter(std::ostream &o, TargetMachine &tm) {
284   return new AIXAsmPrinter(o, tm);
285 }
286
287 // Include the auto-generated portion of the assembly writer
288 #include "PPCGenAsmWriter.inc"
289
290 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
291   const MRegisterInfo &RI = *TM.getRegisterInfo();
292   int new_symbol;
293
294   switch (MO.getType()) {
295   case MachineOperand::MO_VirtualRegister:
296     if (Value *V = MO.getVRegValueOrNull()) {
297       O << "<" << V->getName() << ">";
298       return;
299     }
300     // FALLTHROUGH
301   case MachineOperand::MO_MachineRegister:
302   case MachineOperand::MO_CCRegister:
303     O << RI.get(MO.getReg()).Name;
304     return;
305
306   case MachineOperand::MO_SignExtendedImmed:
307   case MachineOperand::MO_UnextendedImmed:
308     std::cerr << "printOp() does not handle immediate values\n";
309     abort();
310     return;
311
312   case MachineOperand::MO_PCRelativeDisp:
313     std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
314     abort();
315     return;
316
317   case MachineOperand::MO_MachineBasicBlock: {
318     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
319     O << "LBB" << FunctionNumber << "_" << MBBOp->getNumber() << "\t; "
320       << MBBOp->getBasicBlock()->getName();
321     return;
322   }
323
324   case MachineOperand::MO_ConstantPoolIndex:
325     O << "LCPI" << FunctionNumber << '_' << MO.getConstantPoolIndex();
326     return;
327
328   case MachineOperand::MO_ExternalSymbol:
329     O << GlobalPrefix << MO.getSymbolName();
330     return;
331
332   case MachineOperand::MO_GlobalAddress: {
333     GlobalValue *GV = MO.getGlobal();
334     std::string Name = Mang->getValueName(GV);
335
336     // External or weakly linked global variables need non-lazily-resolved stubs
337     if ((GV->isExternal() || GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())){
338       if (GV->hasLinkOnceLinkage())
339         LinkOnceStubs.insert(Name);
340       else
341         GVStubs.insert(Name);
342       O << "L" << Name << "$non_lazy_ptr";
343       return;
344     }
345
346     O << Mang->getValueName(GV);
347     return;
348   }
349
350   default:
351     O << "<unknown operand type: " << MO.getType() << ">";
352     return;
353   }
354 }
355
356 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
357 /// the current output stream.
358 ///
359 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
360   ++EmittedInsts;
361
362   // Check for slwi/srwi mnemonics.
363   if (MI->getOpcode() == PPC::RLWINM) {
364     bool FoundMnemonic = false;
365     unsigned char SH = MI->getOperand(2).getImmedValue();
366     unsigned char MB = MI->getOperand(3).getImmedValue();
367     unsigned char ME = MI->getOperand(4).getImmedValue();
368     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
369       O << "slwi "; FoundMnemonic = true;
370     }
371     if (SH <= 31 && MB == (32-SH) && ME == 31) {
372       O << "srwi "; FoundMnemonic = true;
373       SH = 32-SH;
374     }
375     if (FoundMnemonic) {
376       printOperand(MI, 0, MVT::i64);
377       O << ", ";
378       printOperand(MI, 1, MVT::i64);
379       O << ", " << (unsigned int)SH << "\n";
380       return;
381     }
382   }
383
384   if (printInstruction(MI))
385     return; // Printer was automatically generated
386
387   assert(0 && "Unhandled instruction in asm writer!");
388   abort();
389   return;
390 }
391
392 /// runOnMachineFunction - This uses the printMachineInstruction()
393 /// method to print assembly for each instruction.
394 ///
395 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
396   setupMachineFunction(MF);
397   O << "\n\n";
398
399   // Print out constants referenced by the function
400   printConstantPool(MF.getConstantPool());
401
402   // Print out labels for the function.
403   const Function *F = MF.getFunction();
404   SwitchSection(".text", F);
405   emitAlignment(4, F);
406   if (!F->hasInternalLinkage())
407     O << "\t.globl\t" << CurrentFnName << "\n";
408   O << CurrentFnName << ":\n";
409
410   // Print out code for the function.
411   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
412        I != E; ++I) {
413     // Print a label for the basic block.
414     if (I != MF.begin()) {
415       O << "LBB" << FunctionNumber << '_' << I->getNumber() << ":\t";
416       if (!I->getBasicBlock()->getName().empty())
417         O << CommentString << " " << I->getBasicBlock()->getName();
418       O << "\n";
419     }
420     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
421          II != E; ++II) {
422       // Print the assembly for the instruction.
423       O << "\t";
424       printMachineInstruction(II);
425     }
426   }
427   ++FunctionNumber;
428
429   // We didn't modify anything.
430   return false;
431 }
432
433 /// printConstantPool - Print to the current output stream assembly
434 /// representations of the constants in the constant pool MCP. This is
435 /// used to print out constants which have been "spilled to memory" by
436 /// the code generator.
437 ///
438 void DarwinAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
439   const std::vector<Constant*> &CP = MCP->getConstants();
440   const TargetData &TD = TM.getTargetData();
441
442   if (CP.empty()) return;
443
444   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
445     SwitchSection(".const", 0);
446     // FIXME: force doubles to be naturally aligned.  We should handle this
447     // more correctly in the future.
448     if (Type::DoubleTy == CP[i]->getType())
449       emitAlignment(3);
450     else
451       emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
452     O << "LCPI" << FunctionNumber << '_' << i << ":\t\t\t\t\t" << CommentString
453       << *CP[i] << '\n';
454     emitGlobalConstant(CP[i]);
455   }
456 }
457
458 bool DarwinAsmPrinter::doInitialization(Module &M) {
459   if (TM.getSubtarget<PPCSubtarget>().isGigaProcessor())
460     O << "\t.machine ppc970\n";
461   SwitchSection("", 0);
462   AsmPrinter::doInitialization(M);
463   
464   // Darwin wants symbols to be quoted if they have complex names.
465   Mang->setUseQuotes(true);
466   return false;
467 }
468
469 bool DarwinAsmPrinter::doFinalization(Module &M) {
470   const TargetData &TD = TM.getTargetData();
471
472   // Print out module-level global variables here.
473   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
474        I != E; ++I)
475     if (I->hasInitializer()) {   // External global require no code
476       O << '\n';
477       std::string name = Mang->getValueName(I);
478       Constant *C = I->getInitializer();
479       unsigned Size = TD.getTypeSize(C->getType());
480       unsigned Align = TD.getTypeAlignmentShift(C->getType());
481
482       if (C->isNullValue() && /* FIXME: Verify correct */
483           (I->hasInternalLinkage() || I->hasWeakLinkage() ||
484            I->hasLinkOnceLinkage())) {
485         SwitchSection(".data", I);
486         if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
487         if (I->hasInternalLinkage())
488           O << ".lcomm " << name << "," << Size << "," << Align;
489         else
490           O << ".comm " << name << "," << Size;
491         O << "\t\t; '" << I->getName() << "'\n";
492       } else {
493         switch (I->getLinkage()) {
494         case GlobalValue::LinkOnceLinkage:
495           SwitchSection("", 0);
496           O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
497             << ".weak_definition " << name << '\n'
498             << ".private_extern " << name << '\n'
499             << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
500           LinkOnceStubs.insert(name);
501           break;
502         case GlobalValue::WeakLinkage:
503           O << ".weak_definition " << name << '\n'
504             << ".private_extern " << name << '\n';
505           break;
506         case GlobalValue::AppendingLinkage:
507           // FIXME: appending linkage variables should go into a section of
508           // their name or something.  For now, just emit them as external.
509         case GlobalValue::ExternalLinkage:
510           // If external or appending, declare as a global symbol
511           O << "\t.globl " << name << "\n";
512           // FALL THROUGH
513         case GlobalValue::InternalLinkage:
514           SwitchSection(".data", I);
515           break;
516         default:
517           std::cerr << "Unknown linkage type!";
518           abort();
519         }
520
521         emitAlignment(Align, I);
522         O << name << ":\t\t\t\t; '" << I->getName() << "'\n";
523         emitGlobalConstant(C);
524       }
525     }
526
527   // Output stubs for dynamically-linked functions
528   for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
529        i != e; ++i)
530   {
531     if (PICEnabled) {
532     O << ".data\n";
533     O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
534     emitAlignment(2);
535     O << "L" << *i << "$stub:\n";
536     O << "\t.indirect_symbol " << *i << "\n";
537     O << "\tmflr r0\n";
538     O << "\tbcl 20,31,L0$" << *i << "\n";
539     O << "L0$" << *i << ":\n";
540     O << "\tmflr r11\n";
541     O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
542     O << "\tmtlr r0\n";
543     O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
544     O << "\tmtctr r12\n";
545     O << "\tbctr\n";
546     O << ".data\n";
547     O << ".lazy_symbol_pointer\n";
548     O << "L" << *i << "$lazy_ptr:\n";
549     O << "\t.indirect_symbol " << *i << "\n";
550     O << "\t.long dyld_stub_binding_helper\n";
551     } else {
552     O << "\t.section __TEXT,__symbol_stub1,symbol_stubs,pure_instructions,16\n";
553     emitAlignment(4);
554     O << "L" << *i << "$stub:\n";
555     O << "\t.indirect_symbol " << *i << "\n";
556     O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
557     O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
558     O << "\tmtctr r12\n";
559     O << "\tbctr\n";
560     O << "\t.lazy_symbol_pointer\n";
561     O << "L" << *i << "$lazy_ptr:\n";
562     O << "\t.indirect_symbol " << *i << "\n";
563     O << "\t.long dyld_stub_binding_helper\n";
564     }
565   }
566
567   O << "\n";
568
569   // Output stubs for external global variables
570   if (GVStubs.begin() != GVStubs.end())
571     O << ".data\n.non_lazy_symbol_pointer\n";
572   for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
573        i != e; ++i) {
574     O << "L" << *i << "$non_lazy_ptr:\n";
575     O << "\t.indirect_symbol " << *i << "\n";
576     O << "\t.long\t0\n";
577   }
578
579   // Output stubs for link-once variables
580   if (LinkOnceStubs.begin() != LinkOnceStubs.end())
581     O << ".data\n.align 2\n";
582   for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
583          e = LinkOnceStubs.end(); i != e; ++i) {
584     O << "L" << *i << "$non_lazy_ptr:\n"
585       << "\t.long\t" << *i << '\n';
586   }
587
588   // Funny Darwin hack: This flag tells the linker that no global symbols
589   // contain code that falls through to other global symbols (e.g. the obvious
590   // implementation of multiple entry points).  If this doesn't occur, the
591   // linker can safely perform dead code stripping.  Since LLVM never generates
592   // code that does this, it is always safe to set.
593   O << "\t.subsections_via_symbols\n";
594
595   AsmPrinter::doFinalization(M);
596   return false; // success
597 }
598
599 /// runOnMachineFunction - This uses the printMachineInstruction()
600 /// method to print assembly for each instruction.
601 ///
602 bool AIXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
603   CurrentFnName = MF.getFunction()->getName();
604
605   // Print out constants referenced by the function
606   printConstantPool(MF.getConstantPool());
607
608   // Print out header for the function.
609   O << "\t.csect .text[PR]\n"
610     << "\t.align 2\n"
611     << "\t.globl "  << CurrentFnName << '\n'
612     << "\t.globl ." << CurrentFnName << '\n'
613     << "\t.csect "  << CurrentFnName << "[DS],3\n"
614     << CurrentFnName << ":\n"
615     << "\t.llong ." << CurrentFnName << ", TOC[tc0], 0\n"
616     << "\t.csect .text[PR]\n"
617     << '.' << CurrentFnName << ":\n";
618
619   // Print out code for the function.
620   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
621        I != E; ++I) {
622     // Print a label for the basic block.
623     O << "LBB" << CurrentFnName << '_' << I->getNumber() << ":\t# "
624       << I->getBasicBlock()->getName() << '\n';
625     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
626       II != E; ++II) {
627       // Print the assembly for the instruction.
628       O << "\t";
629       printMachineInstruction(II);
630     }
631   }
632   ++FunctionNumber;
633
634   O << "LT.." << CurrentFnName << ":\n"
635     << "\t.long 0\n"
636     << "\t.byte 0,0,32,65,128,0,0,0\n"
637     << "\t.long LT.." << CurrentFnName << "-." << CurrentFnName << '\n'
638     << "\t.short 3\n"
639     << "\t.byte \"" << CurrentFnName << "\"\n"
640     << "\t.align 2\n";
641
642   // We didn't modify anything.
643   return false;
644 }
645
646 /// printConstantPool - Print to the current output stream assembly
647 /// representations of the constants in the constant pool MCP. This is
648 /// used to print out constants which have been "spilled to memory" by
649 /// the code generator.
650 ///
651 void AIXAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
652   const std::vector<Constant*> &CP = MCP->getConstants();
653   const TargetData &TD = TM.getTargetData();
654
655   if (CP.empty()) return;
656
657   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
658     SwitchSection(".const", 0);
659     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
660       << "\n";
661     O << "LCPI" << FunctionNumber << '_' << i << ":\t\t\t\t\t;"
662       << *CP[i] << '\n';
663     emitGlobalConstant(CP[i]);
664   }
665 }
666
667 bool AIXAsmPrinter::doInitialization(Module &M) {
668   SwitchSection("", 0);
669   const TargetData &TD = TM.getTargetData();
670
671   O << "\t.machine \"ppc64\"\n"
672     << "\t.toc\n"
673     << "\t.csect .text[PR]\n";
674
675   // Print out module-level global variables
676   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
677        I != E; ++I) {
678     if (!I->hasInitializer())
679       continue;
680
681     std::string Name = I->getName();
682     Constant *C = I->getInitializer();
683     // N.B.: We are defaulting to writable strings
684     if (I->hasExternalLinkage()) {
685       O << "\t.globl " << Name << '\n'
686         << "\t.csect .data[RW],3\n";
687     } else {
688       O << "\t.csect _global.rw_c[RW],3\n";
689     }
690     O << Name << ":\n";
691     emitGlobalConstant(C);
692   }
693
694   // Output labels for globals
695   if (M.global_begin() != M.global_end()) O << "\t.toc\n";
696   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
697        I != E; ++I) {
698     const GlobalVariable *GV = I;
699     // Do not output labels for unused variables
700     if (GV->isExternal() && GV->use_begin() == GV->use_end())
701       continue;
702
703     std::string Name = GV->getName();
704     std::string Label = "LC.." + utostr(FunctionNumber++);
705     GVToLabelMap[GV] = Label;
706     O << Label << ":\n"
707       << "\t.tc " << Name << "[TC]," << Name;
708     if (GV->isExternal()) O << "[RW]";
709     O << '\n';
710   }
711
712   AsmPrinter::doInitialization(M);
713   return false; // success
714 }
715
716 bool AIXAsmPrinter::doFinalization(Module &M) {
717   const TargetData &TD = TM.getTargetData();
718   // Print out module-level global variables
719   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
720        I != E; ++I) {
721     if (I->hasInitializer() || I->hasExternalLinkage())
722       continue;
723
724     std::string Name = I->getName();
725     if (I->hasInternalLinkage()) {
726       O << "\t.lcomm " << Name << ",16,_global.bss_c";
727     } else {
728       O << "\t.comm " << Name << "," << TD.getTypeSize(I->getType())
729         << "," << Log2_32((unsigned)TD.getTypeAlignment(I->getType()));
730     }
731     O << "\t\t# ";
732     WriteAsOperand(O, I, false, true, &M);
733     O << "\n";
734   }
735
736   O << "_section_.text:\n"
737     << "\t.csect .data[RW],3\n"
738     << "\t.llong _section_.text\n";
739   AsmPrinter::doFinalization(M);
740   return false; // success
741 }