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