Revert 49006 for the moment.
[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 is distributed under the University of Illinois Open Source
6 // 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 "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Target/TargetAsmInfo.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include <set>
46 using namespace llvm;
47
48 STATISTIC(EmittedInsts, "Number of machine instrs printed");
49
50 namespace {
51   struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
52     std::set<std::string> FnStubs, GVStubs;
53     const PPCSubtarget &Subtarget;
54
55     PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
56       : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
57     }
58
59     virtual const char *getPassName() const {
60       return "PowerPC Assembly Printer";
61     }
62
63     PPCTargetMachine &getTM() {
64       return static_cast<PPCTargetMachine&>(TM);
65     }
66
67     unsigned enumRegToMachineReg(unsigned enumReg) {
68       switch (enumReg) {
69       default: assert(0 && "Unhandled register!"); break;
70       case PPC::CR0:  return  0;
71       case PPC::CR1:  return  1;
72       case PPC::CR2:  return  2;
73       case PPC::CR3:  return  3;
74       case PPC::CR4:  return  4;
75       case PPC::CR5:  return  5;
76       case PPC::CR6:  return  6;
77       case PPC::CR7:  return  7;
78       }
79       abort();
80     }
81
82     /// printInstruction - This method is automatically generated by tablegen
83     /// from the instruction set description.  This method returns true if the
84     /// machine instruction was sufficiently described to print it, otherwise it
85     /// returns false.
86     bool printInstruction(const MachineInstr *MI);
87
88     void printMachineInstruction(const MachineInstr *MI);
89     void printOp(const MachineOperand &MO);
90     
91     /// stripRegisterPrefix - This method strips the character prefix from a
92     /// register name so that only the number is left.  Used by for linux asm.
93     const char *stripRegisterPrefix(const char *RegName) {
94       switch (RegName[0]) {
95       case 'r':
96       case 'f':
97       case 'v': return RegName + 1;
98       case 'c': if (RegName[1] == 'r') return RegName + 2;
99       }
100        
101       return RegName;
102     }
103     
104     /// printRegister - Print register according to target requirements.
105     ///
106     void printRegister(const MachineOperand &MO, bool R0AsZero) {
107       unsigned RegNo = MO.getReg();
108       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
109       
110       // If we should use 0 for R0.
111       if (R0AsZero && RegNo == PPC::R0) {
112         O << "0";
113         return;
114       }
115       
116       const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
117       // Linux assembler (Others?) does not take register mnemonics.
118       // FIXME - What about special registers used in mfspr/mtspr?
119       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
120       O << RegName;
121     }
122
123     void printOperand(const MachineInstr *MI, unsigned OpNo) {
124       const MachineOperand &MO = MI->getOperand(OpNo);
125       if (MO.isRegister()) {
126         printRegister(MO, false);
127       } else if (MO.isImmediate()) {
128         O << MO.getImm();
129       } else {
130         printOp(MO);
131       }
132     }
133     
134     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
135                          unsigned AsmVariant, const char *ExtraCode);
136     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
137                                unsigned AsmVariant, const char *ExtraCode);
138     
139     
140     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
141       char value = MI->getOperand(OpNo).getImm();
142       value = (value << (32-5)) >> (32-5);
143       O << (int)value;
144     }
145     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
146       unsigned char value = MI->getOperand(OpNo).getImm();
147       assert(value <= 31 && "Invalid u5imm argument!");
148       O << (unsigned int)value;
149     }
150     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
151       unsigned char value = MI->getOperand(OpNo).getImm();
152       assert(value <= 63 && "Invalid u6imm argument!");
153       O << (unsigned int)value;
154     }
155     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
156       O << (short)MI->getOperand(OpNo).getImm();
157     }
158     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
159       O << (unsigned short)MI->getOperand(OpNo).getImm();
160     }
161     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
162       if (MI->getOperand(OpNo).isImmediate()) {
163         O << (short)(MI->getOperand(OpNo).getImm()*4);
164       } else {
165         O << "lo16(";
166         printOp(MI->getOperand(OpNo));
167         if (TM.getRelocationModel() == Reloc::PIC_)
168           O << "-\"L" << getFunctionNumber() << "$pb\")";
169         else
170           O << ')';
171       }
172     }
173     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
174       // Branches can take an immediate operand.  This is used by the branch
175       // selection pass to print $+8, an eight byte displacement from the PC.
176       if (MI->getOperand(OpNo).isImmediate()) {
177         O << "$+" << MI->getOperand(OpNo).getImm()*4;
178       } else {
179         printOp(MI->getOperand(OpNo));
180       }
181     }
182     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
183       const MachineOperand &MO = MI->getOperand(OpNo);
184       if (TM.getRelocationModel() != Reloc::Static) {
185         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
186           GlobalValue *GV = MO.getGlobal();
187           if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
188                 GV->hasLinkOnceLinkage()))) {
189             // Dynamically-resolved functions need a stub for the function.
190             std::string Name = Mang->getValueName(GV);
191             FnStubs.insert(Name);
192             O << "L" << Name << "$stub";
193             if (GV->hasExternalWeakLinkage())
194               ExtWeakSymbols.insert(GV);
195             return;
196           }
197         }
198         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
199           std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
200           FnStubs.insert(Name);
201           O << "L" << Name << "$stub";
202           return;
203         }
204       }
205       
206       printOp(MI->getOperand(OpNo));
207     }
208     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
209      O << (int)MI->getOperand(OpNo).getImm()*4;
210     }
211     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
212       O << "\"L" << getFunctionNumber() << "$pb\"\n";
213       O << "\"L" << getFunctionNumber() << "$pb\":";
214     }
215     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
216       if (MI->getOperand(OpNo).isImmediate()) {
217         printS16ImmOperand(MI, OpNo);
218       } else {
219         if (Subtarget.isDarwin()) O << "ha16(";
220         printOp(MI->getOperand(OpNo));
221         if (TM.getRelocationModel() == Reloc::PIC_)
222           O << "-\"L" << getFunctionNumber() << "$pb\"";
223         if (Subtarget.isDarwin())
224           O << ')';
225         else
226           O << "@ha";
227       }
228     }
229     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
230       if (MI->getOperand(OpNo).isImmediate()) {
231         printS16ImmOperand(MI, OpNo);
232       } else {
233         if (Subtarget.isDarwin()) O << "lo16(";
234         printOp(MI->getOperand(OpNo));
235         if (TM.getRelocationModel() == Reloc::PIC_)
236           O << "-\"L" << getFunctionNumber() << "$pb\"";
237         if (Subtarget.isDarwin())
238           O << ')';
239         else
240           O << "@l";
241       }
242     }
243     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
244       unsigned CCReg = MI->getOperand(OpNo).getReg();
245       unsigned RegNo = enumRegToMachineReg(CCReg);
246       O << (0x80 >> RegNo);
247     }
248     // The new addressing mode printers.
249     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
250       printSymbolLo(MI, OpNo);
251       O << '(';
252       if (MI->getOperand(OpNo+1).isRegister() && 
253           MI->getOperand(OpNo+1).getReg() == PPC::R0)
254         O << "0";
255       else
256         printOperand(MI, OpNo+1);
257       O << ')';
258     }
259     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
260       if (MI->getOperand(OpNo).isImmediate())
261         printS16X4ImmOperand(MI, OpNo);
262       else 
263         printSymbolLo(MI, OpNo);
264       O << '(';
265       if (MI->getOperand(OpNo+1).isRegister() && 
266           MI->getOperand(OpNo+1).getReg() == PPC::R0)
267         O << "0";
268       else
269         printOperand(MI, OpNo+1);
270       O << ')';
271     }
272     
273     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
274       // When used as the base register, r0 reads constant zero rather than
275       // the value contained in the register.  For this reason, the darwin
276       // assembler requires that we print r0 as 0 (no r) when used as the base.
277       const MachineOperand &MO = MI->getOperand(OpNo);
278       printRegister(MO, true);
279       O << ", ";
280       printOperand(MI, OpNo+1);
281     }
282     
283     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
284                                const char *Modifier);
285     
286     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
287     virtual bool doFinalization(Module &M) = 0;
288
289     virtual void EmitExternalGlobal(const GlobalVariable *GV);
290   };
291
292   /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
293   struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
294
295     DwarfWriter DW;
296
297     LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
298                     const TargetAsmInfo *T)
299       : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
300     }
301
302     virtual const char *getPassName() const {
303       return "Linux PPC Assembly Printer";
304     }
305
306     bool runOnMachineFunction(MachineFunction &F);
307     bool doInitialization(Module &M);
308     bool doFinalization(Module &M);
309     
310     void getAnalysisUsage(AnalysisUsage &AU) const {
311       AU.setPreservesAll();
312       AU.addRequired<MachineModuleInfo>();
313       PPCAsmPrinter::getAnalysisUsage(AU);
314     }
315
316     /// getSectionForFunction - Return the section that we should emit the
317     /// specified function body into.
318     virtual std::string getSectionForFunction(const Function &F) const;
319   };
320
321   /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
322   /// X
323   struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
324   
325     DwarfWriter DW;
326     MachineModuleInfo *MMI;
327
328     DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
329                      const TargetAsmInfo *T)
330       : PPCAsmPrinter(O, TM, T), DW(O, this, T), MMI(0) {
331     }
332
333     virtual const char *getPassName() const {
334       return "Darwin PPC Assembly Printer";
335     }
336     
337     bool runOnMachineFunction(MachineFunction &F);
338     bool doInitialization(Module &M);
339     bool doFinalization(Module &M);
340     
341     void getAnalysisUsage(AnalysisUsage &AU) const {
342       AU.setPreservesAll();
343       AU.addRequired<MachineModuleInfo>();
344       PPCAsmPrinter::getAnalysisUsage(AU);
345     }
346
347     /// getSectionForFunction - Return the section that we should emit the
348     /// specified function body into.
349     virtual std::string getSectionForFunction(const Function &F) const;
350   };
351 } // end of anonymous namespace
352
353 // Include the auto-generated portion of the assembly writer
354 #include "PPCGenAsmWriter.inc"
355
356 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
357   switch (MO.getType()) {
358   case MachineOperand::MO_Immediate:
359     cerr << "printOp() does not handle immediate values\n";
360     abort();
361     return;
362
363   case MachineOperand::MO_MachineBasicBlock:
364     printBasicBlockLabel(MO.getMBB());
365     return;
366   case MachineOperand::MO_JumpTableIndex:
367     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
368       << '_' << MO.getIndex();
369     // FIXME: PIC relocation model
370     return;
371   case MachineOperand::MO_ConstantPoolIndex:
372     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
373       << '_' << MO.getIndex();
374     return;
375   case MachineOperand::MO_ExternalSymbol:
376     // Computing the address of an external symbol, not calling it.
377     if (TM.getRelocationModel() != Reloc::Static) {
378       std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
379       GVStubs.insert(Name);
380       O << "L" << Name << "$non_lazy_ptr";
381       return;
382     }
383     O << TAI->getGlobalPrefix() << MO.getSymbolName();
384     return;
385   case MachineOperand::MO_GlobalAddress: {
386     // Computing the address of a global symbol, not calling it.
387     GlobalValue *GV = MO.getGlobal();
388     std::string Name = Mang->getValueName(GV);
389
390     // External or weakly linked global variables need non-lazily-resolved stubs
391     if (TM.getRelocationModel() != Reloc::Static) {
392       if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
393             GV->hasLinkOnceLinkage()))) {
394         GVStubs.insert(Name);
395         O << "L" << Name << "$non_lazy_ptr";
396         return;
397       }
398     }
399     O << Name;
400     
401     if (MO.getOffset() > 0)
402       O << "+" << MO.getOffset();
403     else if (MO.getOffset() < 0)
404       O << MO.getOffset();
405     
406     if (GV->hasExternalWeakLinkage())
407       ExtWeakSymbols.insert(GV);
408     return;
409   }
410
411   default:
412     O << "<unknown operand type: " << MO.getType() << ">";
413     return;
414   }
415 }
416
417 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
418 ///
419 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
420   std::string Name = getGlobalLinkName(GV);
421   if (TM.getRelocationModel() != Reloc::Static) {
422     GVStubs.insert(Name);
423     O << "L" << Name << "$non_lazy_ptr";
424     return;
425   }
426   O << Name;
427 }
428
429 /// PrintAsmOperand - Print out an operand for an inline asm expression.
430 ///
431 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
432                                     unsigned AsmVariant, 
433                                     const char *ExtraCode) {
434   // Does this asm operand have a single letter operand modifier?
435   if (ExtraCode && ExtraCode[0]) {
436     if (ExtraCode[1] != 0) return true; // Unknown modifier.
437     
438     switch (ExtraCode[0]) {
439     default: return true;  // Unknown modifier.
440     case 'c': // Don't print "$" before a global var name or constant.
441       // PPC never has a prefix.
442       printOperand(MI, OpNo);
443       return false;
444     case 'L': // Write second word of DImode reference.  
445       // Verify that this operand has two consecutive registers.
446       if (!MI->getOperand(OpNo).isRegister() ||
447           OpNo+1 == MI->getNumOperands() ||
448           !MI->getOperand(OpNo+1).isRegister())
449         return true;
450       ++OpNo;   // Return the high-part.
451       break;
452     case 'I':
453       // Write 'i' if an integer constant, otherwise nothing.  Used to print
454       // addi vs add, etc.
455       if (MI->getOperand(OpNo).isImmediate())
456         O << "i";
457       return false;
458     }
459   }
460   
461   printOperand(MI, OpNo);
462   return false;
463 }
464
465 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
466                                           unsigned AsmVariant, 
467                                           const char *ExtraCode) {
468   if (ExtraCode && ExtraCode[0])
469     return true; // Unknown modifier.
470   if (MI->getOperand(OpNo).isRegister())
471     printMemRegReg(MI, OpNo);
472   else
473     printMemRegImm(MI, OpNo);
474   return false;
475 }
476
477 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
478                                           const char *Modifier) {
479   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
480   unsigned Code = MI->getOperand(OpNo).getImm();
481   if (!strcmp(Modifier, "cc")) {
482     switch ((PPC::Predicate)Code) {
483     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
484     case PPC::PRED_LT: O << "lt"; return;
485     case PPC::PRED_LE: O << "le"; return;
486     case PPC::PRED_EQ: O << "eq"; return;
487     case PPC::PRED_GE: O << "ge"; return;
488     case PPC::PRED_GT: O << "gt"; return;
489     case PPC::PRED_NE: O << "ne"; return;
490     case PPC::PRED_UN: O << "un"; return;
491     case PPC::PRED_NU: O << "nu"; return;
492     }
493       
494   } else {
495     assert(!strcmp(Modifier, "reg") &&
496            "Need to specify 'cc' or 'reg' as predicate op modifier!");
497     // Don't print the register for 'always'.
498     if (Code == PPC::PRED_ALWAYS) return;
499     printOperand(MI, OpNo+1);
500   }
501 }
502
503
504 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
505 /// the current output stream.
506 ///
507 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
508   ++EmittedInsts;
509
510   // Check for slwi/srwi mnemonics.
511   if (MI->getOpcode() == PPC::RLWINM) {
512     bool FoundMnemonic = false;
513     unsigned char SH = MI->getOperand(2).getImm();
514     unsigned char MB = MI->getOperand(3).getImm();
515     unsigned char ME = MI->getOperand(4).getImm();
516     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
517       O << "\tslwi "; FoundMnemonic = true;
518     }
519     if (SH <= 31 && MB == (32-SH) && ME == 31) {
520       O << "\tsrwi "; FoundMnemonic = true;
521       SH = 32-SH;
522     }
523     if (FoundMnemonic) {
524       printOperand(MI, 0);
525       O << ", ";
526       printOperand(MI, 1);
527       O << ", " << (unsigned int)SH << "\n";
528       return;
529     }
530   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
531     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
532       O << "\tmr ";
533       printOperand(MI, 0);
534       O << ", ";
535       printOperand(MI, 1);
536       O << "\n";
537       return;
538     }
539   } else if (MI->getOpcode() == PPC::RLDICR) {
540     unsigned char SH = MI->getOperand(2).getImm();
541     unsigned char ME = MI->getOperand(3).getImm();
542     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
543     if (63-SH == ME) {
544       O << "\tsldi ";
545       printOperand(MI, 0);
546       O << ", ";
547       printOperand(MI, 1);
548       O << ", " << (unsigned int)SH << "\n";
549       return;
550     }
551   }
552
553   if (printInstruction(MI))
554     return; // Printer was automatically generated
555
556   assert(0 && "Unhandled instruction in asm writer!");
557   abort();
558   return;
559 }
560
561 /// runOnMachineFunction - This uses the printMachineInstruction()
562 /// method to print assembly for each instruction.
563 ///
564 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
565   DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
566
567   SetupMachineFunction(MF);
568   O << "\n\n";
569   
570   // Print out constants referenced by the function
571   EmitConstantPool(MF.getConstantPool());
572
573   // Print out labels for the function.
574   const Function *F = MF.getFunction();
575   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
576   
577   switch (F->getLinkage()) {
578   default: assert(0 && "Unknown linkage type!");
579   case Function::InternalLinkage:  // Symbols default to internal.
580     break;
581   case Function::ExternalLinkage:
582     O << "\t.global\t" << CurrentFnName << '\n'
583       << "\t.type\t" << CurrentFnName << ", @function\n";
584     break;
585   case Function::WeakLinkage:
586   case Function::LinkOnceLinkage:
587     O << "\t.global\t" << CurrentFnName << '\n';
588     O << "\t.weak\t" << CurrentFnName << '\n';
589     break;
590   }
591   
592   if (F->hasHiddenVisibility())
593     if (const char *Directive = TAI->getHiddenDirective())
594       O << Directive << CurrentFnName << "\n";
595   
596   EmitAlignment(2, F);
597   O << CurrentFnName << ":\n";
598
599   // Emit pre-function debug information.
600   DW.BeginFunction(&MF);
601
602   // Print out code for the function.
603   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
604        I != E; ++I) {
605     // Print a label for the basic block.
606     if (I != MF.begin()) {
607       printBasicBlockLabel(I, true, true);
608       O << '\n';
609     }
610     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
611          II != E; ++II) {
612       // Print the assembly for the instruction.
613       printMachineInstruction(II);
614     }
615   }
616
617   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
618
619   // Print out jump tables referenced by the function.
620   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
621   
622   // Emit post-function debug information.
623   DW.EndFunction();
624   
625   // We didn't modify anything.
626   return false;
627 }
628
629 bool LinuxAsmPrinter::doInitialization(Module &M) {
630   bool Result = AsmPrinter::doInitialization(M);
631   
632   // GNU as handles section names wrapped in quotes
633   Mang->setUseQuotes(true);
634
635   SwitchToTextSection(TAI->getTextSection());
636   
637   // Emit initial debug information.
638   DW.BeginModule(&M);
639   return Result;
640 }
641
642 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
643 /// Don't print things like \n or \0.
644 static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) {
645   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
646        Name != E; ++Name)
647     if (isprint(*Name))
648       OS << *Name;
649 }
650
651 bool LinuxAsmPrinter::doFinalization(Module &M) {
652   const TargetData *TD = TM.getTargetData();
653
654   // Print out module-level global variables here.
655   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
656        I != E; ++I) {
657     if (!I->hasInitializer()) continue;   // External global require no code
658     
659     // Check to see if this is a special global used by LLVM, if so, emit it.
660     if (EmitSpecialLLVMGlobal(I))
661       continue;
662
663     std::string name = Mang->getValueName(I);
664
665     if (I->hasHiddenVisibility())
666       if (const char *Directive = TAI->getHiddenDirective())
667         O << Directive << name << "\n";
668     
669     Constant *C = I->getInitializer();
670     unsigned Size = TD->getABITypeSize(C->getType());
671     unsigned Align = TD->getPreferredAlignmentLog(I);
672
673     if (C->isNullValue() && /* FIXME: Verify correct */
674         !I->hasSection() &&
675         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
676          I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
677       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
678       if (I->hasExternalLinkage()) {
679         O << "\t.global " << name << '\n';
680         O << "\t.type " << name << ", @object\n";
681         if (TAI->getBSSSection())
682           SwitchToDataSection(TAI->getBSSSection(), I);
683         O << name << ":\n";
684         O << "\t.zero " << Size << "\n";
685       } else if (I->hasInternalLinkage()) {
686         SwitchToDataSection("\t.data", I);
687         O << TAI->getLCOMMDirective() << name << "," << Size;
688       } else {
689         SwitchToDataSection("\t.data", I);
690         O << ".comm " << name << "," << Size;
691       }
692       O << "\t\t" << TAI->getCommentString() << " '";
693       PrintUnmangledNameSafely(I, O);
694       O << "'\n";
695     } else {
696       switch (I->getLinkage()) {
697       case GlobalValue::LinkOnceLinkage:
698       case GlobalValue::WeakLinkage:
699         O << "\t.global " << name << '\n'
700           << "\t.type " << name << ", @object\n"
701           << "\t.weak " << name << '\n';
702         SwitchToDataSection("\t.data", I);
703         break;
704       case GlobalValue::AppendingLinkage:
705         // FIXME: appending linkage variables should go into a section of
706         // their name or something.  For now, just emit them as external.
707       case GlobalValue::ExternalLinkage:
708         // If external or appending, declare as a global symbol
709         O << "\t.global " << name << "\n"
710           << "\t.type " << name << ", @object\n";
711         // FALL THROUGH
712       case GlobalValue::InternalLinkage:
713         if (I->isConstant()) {
714           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
715           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
716             SwitchToDataSection(TAI->getCStringSection(), I);
717             break;
718           }
719         }
720
721         // FIXME: special handling for ".ctors" & ".dtors" sections
722         if (I->hasSection() &&
723             (I->getSection() == ".ctors" ||
724              I->getSection() == ".dtors")) {
725           std::string SectionName = ".section " + I->getSection()
726                                                 + ",\"aw\",@progbits";
727           SwitchToDataSection(SectionName.c_str());
728         } else {
729           if (I->isConstant() && TAI->getReadOnlySection())
730             SwitchToDataSection(TAI->getReadOnlySection(), I);
731           else
732             SwitchToDataSection(TAI->getDataSection(), I);
733         }
734         break;
735       default:
736         cerr << "Unknown linkage type!";
737         abort();
738       }
739
740       EmitAlignment(Align, I);
741       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
742       PrintUnmangledNameSafely(I, O);
743       O << "'\n";
744
745       // If the initializer is a extern weak symbol, remember to emit the weak
746       // reference!
747       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
748         if (GV->hasExternalWeakLinkage())
749           ExtWeakSymbols.insert(GV);
750
751       EmitGlobalConstant(C);
752       O << '\n';
753     }
754   }
755
756   // TODO
757
758   // Emit initial debug information.
759   DW.EndModule();
760
761   return AsmPrinter::doFinalization(M);
762 }
763
764 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
765   switch (F.getLinkage()) {
766   default: assert(0 && "Unknown linkage type!");
767   case Function::ExternalLinkage:
768   case Function::InternalLinkage: return TAI->getTextSection();
769   case Function::WeakLinkage:
770   case Function::LinkOnceLinkage:
771     return ".text";
772   }
773 }
774
775 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
776   switch (F.getLinkage()) {
777   default: assert(0 && "Unknown linkage type!");
778   case Function::ExternalLinkage:
779   case Function::InternalLinkage: return TAI->getTextSection();
780   case Function::WeakLinkage:
781   case Function::LinkOnceLinkage:
782     return "\t.section __TEXT,__textcoal_nt,coalesced,pure_instructions";
783   }
784 }
785
786 /// runOnMachineFunction - This uses the printMachineInstruction()
787 /// method to print assembly for each instruction.
788 ///
789 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
790   // We need this for Personality functions.
791   MMI = &getAnalysis<MachineModuleInfo>();
792   DW.SetModuleInfo(MMI);
793
794   SetupMachineFunction(MF);
795   O << "\n\n";
796
797   // Print out constants referenced by the function
798   EmitConstantPool(MF.getConstantPool());
799
800   // Print out labels for the function.
801   const Function *F = MF.getFunction();
802   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
803   
804   switch (F->getLinkage()) {
805   default: assert(0 && "Unknown linkage type!");
806   case Function::InternalLinkage:  // Symbols default to internal.
807     break;
808   case Function::ExternalLinkage:
809     O << "\t.globl\t" << CurrentFnName << "\n";
810     break;
811   case Function::WeakLinkage:
812   case Function::LinkOnceLinkage:
813     O << "\t.globl\t" << CurrentFnName << "\n";
814     O << "\t.weak_definition\t" << CurrentFnName << "\n";
815     break;
816   }
817   
818   if (F->hasHiddenVisibility())
819     if (const char *Directive = TAI->getHiddenDirective())
820       O << Directive << CurrentFnName << "\n";
821   
822   EmitAlignment(OptimizeForSize ? 2 : 4, F);
823   O << CurrentFnName << ":\n";
824
825   // Emit pre-function debug information.
826   DW.BeginFunction(&MF);
827
828   // If the function is empty, then we need to emit *something*. Otherwise, the
829   // function's label might be associated with something that it wasn't meant to
830   // be associated with. We emit a noop in this situation.
831   MachineFunction::iterator I = MF.begin();
832
833   if (++I == MF.end() && MF.front().empty())
834     O << "\tnop\n";
835
836   // Print out code for the function.
837   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
838        I != E; ++I) {
839     // Print a label for the basic block.
840     if (I != MF.begin()) {
841       printBasicBlockLabel(I, true, true);
842       O << '\n';
843     }
844     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
845          II != IE; ++II) {
846       // Print the assembly for the instruction.
847       printMachineInstruction(II);
848     }
849   }
850
851   // Print out jump tables referenced by the function.
852   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
853   
854   // Emit post-function debug information.
855   DW.EndFunction();
856   
857   // We didn't modify anything.
858   return false;
859 }
860
861
862 bool DarwinAsmPrinter::doInitialization(Module &M) {
863   static const char *const CPUDirectives[] = {
864     "",
865     "ppc",
866     "ppc601",
867     "ppc602",
868     "ppc603",
869     "ppc7400",
870     "ppc750",
871     "ppc970",
872     "ppc64"
873   };
874
875   unsigned Directive = Subtarget.getDarwinDirective();
876   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
877     Directive = PPC::DIR_970;
878   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
879     Directive = PPC::DIR_7400;
880   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
881     Directive = PPC::DIR_64;
882   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
883   O << "\t.machine " << CPUDirectives[Directive] << "\n";
884      
885   bool Result = AsmPrinter::doInitialization(M);
886   
887   // Darwin wants symbols to be quoted if they have complex names.
888   Mang->setUseQuotes(true);
889   
890   // Prime text sections so they are adjacent.  This reduces the likelihood a
891   // large data or debug section causes a branch to exceed 16M limit.
892   SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
893                       "pure_instructions");
894   if (TM.getRelocationModel() == Reloc::PIC_) {
895     SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
896                           "pure_instructions,32");
897   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
898     SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
899                         "pure_instructions,16");
900   }
901   SwitchToTextSection(TAI->getTextSection());
902   
903   // Emit initial debug information.
904   DW.BeginModule(&M);
905   return Result;
906 }
907
908 bool DarwinAsmPrinter::doFinalization(Module &M) {
909   const TargetData *TD = TM.getTargetData();
910
911   // Print out module-level global variables here.
912   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
913        I != E; ++I) {
914     if (!I->hasInitializer()) continue;   // External global require no code
915     
916     // Check to see if this is a special global used by LLVM, if so, emit it.
917     if (EmitSpecialLLVMGlobal(I)) {
918       if (TM.getRelocationModel() == Reloc::Static) {
919         if (I->getName() == "llvm.global_ctors")
920           O << ".reference .constructors_used\n";
921         else if (I->getName() == "llvm.global_dtors")
922           O << ".reference .destructors_used\n";
923       }
924       continue;
925     }
926     
927     std::string name = Mang->getValueName(I);
928     
929     if (I->hasHiddenVisibility())
930       if (const char *Directive = TAI->getHiddenDirective())
931         O << Directive << name << "\n";
932     
933     Constant *C = I->getInitializer();
934     const Type *Type = C->getType();
935     unsigned Size = TD->getABITypeSize(Type);
936     unsigned Align = TD->getPreferredAlignmentLog(I);
937
938     if (C->isNullValue() && /* FIXME: Verify correct */
939         !I->hasSection() &&
940         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
941          I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
942       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
943       if (I->hasExternalLinkage()) {
944         O << "\t.globl " << name << '\n';
945         O << "\t.zerofill __DATA, __common, " << name << ", "
946           << Size << ", " << Align;
947       } else if (I->hasInternalLinkage()) {
948         SwitchToDataSection("\t.data", I);
949         O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
950       } else {
951         SwitchToDataSection("\t.data", I);
952         O << ".comm " << name << "," << Size;
953         // Darwin 9 and above support aligned common data.
954         if (Subtarget.isDarwin9())
955           O << "," << Align;
956       }
957       O << "\t\t" << TAI->getCommentString() << " '";
958       PrintUnmangledNameSafely(I, O);
959       O << "'\n";
960     } else {
961       switch (I->getLinkage()) {
962       case GlobalValue::LinkOnceLinkage:
963       case GlobalValue::WeakLinkage:
964         O << "\t.globl " << name << '\n'
965           << "\t.weak_definition " << name << '\n';
966         SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
967         break;
968       case GlobalValue::AppendingLinkage:
969         // FIXME: appending linkage variables should go into a section of
970         // their name or something.  For now, just emit them as external.
971       case GlobalValue::ExternalLinkage:
972         // If external or appending, declare as a global symbol
973         O << "\t.globl " << name << "\n";
974         // FALL THROUGH
975       case GlobalValue::InternalLinkage:
976         if (I->isConstant()) {
977           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
978           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
979             SwitchToDataSection(TAI->getCStringSection(), I);
980             break;
981           }
982         }
983         if (I->hasSection()) {
984           // Honor all section names on Darwin; ObjC uses this
985           std::string SectionName = ".section " + I->getSection();
986           SwitchToDataSection(SectionName.c_str());
987         } else if (!I->isConstant())
988           SwitchToDataSection(TAI->getDataSection(), I);
989         else {
990           // Read-only data.
991           bool HasReloc = C->ContainsRelocations();
992           if (HasReloc &&
993               TM.getRelocationModel() != Reloc::Static)
994             SwitchToDataSection("\t.const_data\n");
995           else if (!HasReloc && Size == 4 &&
996                    TAI->getFourByteConstantSection())
997             SwitchToDataSection(TAI->getFourByteConstantSection(), I);
998           else if (!HasReloc && Size == 8 &&
999                    TAI->getEightByteConstantSection())
1000             SwitchToDataSection(TAI->getEightByteConstantSection(), I);
1001           else if (!HasReloc && Size == 16 &&
1002                    TAI->getSixteenByteConstantSection())
1003             SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
1004           else if (TAI->getReadOnlySection())
1005             SwitchToDataSection(TAI->getReadOnlySection(), I);
1006           else
1007             SwitchToDataSection(TAI->getDataSection(), I);
1008         }
1009         break;
1010       default:
1011         cerr << "Unknown linkage type!";
1012         abort();
1013       }
1014
1015       EmitAlignment(Align, I);
1016       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
1017       PrintUnmangledNameSafely(I, O);
1018       O << "'\n";
1019
1020       // If the initializer is a extern weak symbol, remember to emit the weak
1021       // reference!
1022       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1023         if (GV->hasExternalWeakLinkage())
1024           ExtWeakSymbols.insert(GV);
1025
1026       EmitGlobalConstant(C);
1027       O << '\n';
1028     }
1029   }
1030
1031   bool isPPC64 = TD->getPointerSizeInBits() == 64;
1032
1033   // Output stubs for dynamically-linked functions
1034   if (TM.getRelocationModel() == Reloc::PIC_) {
1035     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1036          i != e; ++i) {
1037       SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
1038                           "pure_instructions,32");
1039       EmitAlignment(4);
1040       O << "L" << *i << "$stub:\n";
1041       O << "\t.indirect_symbol " << *i << "\n";
1042       O << "\tmflr r0\n";
1043       O << "\tbcl 20,31,L0$" << *i << "\n";
1044       O << "L0$" << *i << ":\n";
1045       O << "\tmflr r11\n";
1046       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
1047       O << "\tmtlr r0\n";
1048       if (isPPC64)
1049         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1050       else
1051         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1052       O << "\tmtctr r12\n";
1053       O << "\tbctr\n";
1054       SwitchToDataSection(".lazy_symbol_pointer");
1055       O << "L" << *i << "$lazy_ptr:\n";
1056       O << "\t.indirect_symbol " << *i << "\n";
1057       if (isPPC64)
1058         O << "\t.quad dyld_stub_binding_helper\n";
1059       else
1060         O << "\t.long dyld_stub_binding_helper\n";
1061     }
1062   } else {
1063     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1064          i != e; ++i) {
1065       SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1066                           "pure_instructions,16");
1067       EmitAlignment(4);
1068       O << "L" << *i << "$stub:\n";
1069       O << "\t.indirect_symbol " << *i << "\n";
1070       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
1071       if (isPPC64)
1072         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1073       else
1074         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1075       O << "\tmtctr r12\n";
1076       O << "\tbctr\n";
1077       SwitchToDataSection(".lazy_symbol_pointer");
1078       O << "L" << *i << "$lazy_ptr:\n";
1079       O << "\t.indirect_symbol " << *i << "\n";
1080       if (isPPC64)
1081         O << "\t.quad dyld_stub_binding_helper\n";
1082       else
1083         O << "\t.long dyld_stub_binding_helper\n";
1084     }
1085   }
1086
1087   O << "\n";
1088
1089   if (ExceptionHandling && TAI->doesSupportExceptionHandling() && MMI) {
1090     // Add the (possibly multiple) personalities to the set of global values.
1091     const std::vector<Function *>& Personalities = MMI->getPersonalities();
1092
1093     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1094            E = Personalities.end(); I != E; ++I)
1095       if (*I) GVStubs.insert("_" + (*I)->getName());
1096   }
1097
1098   // Output stubs for external and common global variables.
1099   if (!GVStubs.empty()) {
1100     SwitchToDataSection(".non_lazy_symbol_pointer");
1101     for (std::set<std::string>::iterator I = GVStubs.begin(),
1102          E = GVStubs.end(); I != E; ++I) {
1103       O << "L" << *I << "$non_lazy_ptr:\n";
1104       O << "\t.indirect_symbol " << *I << "\n";
1105       if (isPPC64)
1106         O << "\t.quad\t0\n";
1107       else
1108         O << "\t.long\t0\n";
1109         
1110     }
1111   }
1112
1113   // Emit initial debug information.
1114   DW.EndModule();
1115
1116   // Funny Darwin hack: This flag tells the linker that no global symbols
1117   // contain code that falls through to other global symbols (e.g. the obvious
1118   // implementation of multiple entry points).  If this doesn't occur, the
1119   // linker can safely perform dead code stripping.  Since LLVM never generates
1120   // code that does this, it is always safe to set.
1121   O << "\t.subsections_via_symbols\n";
1122
1123   return AsmPrinter::doFinalization(M);
1124 }
1125
1126
1127
1128 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1129 /// for a MachineFunction to the given output stream, in a format that the
1130 /// Darwin assembler can deal with.
1131 ///
1132 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1133                                             PPCTargetMachine &tm) {
1134   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1135
1136   if (Subtarget->isDarwin()) {
1137     return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1138   } else {
1139     return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1140   }
1141 }
1142