Handle quoted names when constructing $stub's,
[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() || GV->hasCommonLinkage()))) {
189             // Dynamically-resolved functions need a stub for the function.
190             std::string Name = Mang->getValueName(GV);
191             FnStubs.insert(Name);
192             printSuffixedName(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           printSuffixedName(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       printSuffixedName(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() || GV->hasCommonLinkage()))) {
394         GVStubs.insert(Name);
395         printSuffixedName(Name, "$non_lazy_ptr");
396         if (GV->hasExternalWeakLinkage())
397           ExtWeakSymbols.insert(GV);
398         return;
399       }
400     }
401     O << Name;
402     
403     if (MO.getOffset() > 0)
404       O << "+" << MO.getOffset();
405     else if (MO.getOffset() < 0)
406       O << MO.getOffset();
407     
408     if (GV->hasExternalWeakLinkage())
409       ExtWeakSymbols.insert(GV);
410     return;
411   }
412
413   default:
414     O << "<unknown operand type: " << MO.getType() << ">";
415     return;
416   }
417 }
418
419 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
420 ///
421 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
422   std::string Name = getGlobalLinkName(GV);
423   if (TM.getRelocationModel() != Reloc::Static) {
424     GVStubs.insert(Name);
425     printSuffixedName(Name, "$non_lazy_ptr");
426     return;
427   }
428   O << Name;
429 }
430
431 /// PrintAsmOperand - Print out an operand for an inline asm expression.
432 ///
433 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
434                                     unsigned AsmVariant, 
435                                     const char *ExtraCode) {
436   // Does this asm operand have a single letter operand modifier?
437   if (ExtraCode && ExtraCode[0]) {
438     if (ExtraCode[1] != 0) return true; // Unknown modifier.
439     
440     switch (ExtraCode[0]) {
441     default: return true;  // Unknown modifier.
442     case 'c': // Don't print "$" before a global var name or constant.
443       // PPC never has a prefix.
444       printOperand(MI, OpNo);
445       return false;
446     case 'L': // Write second word of DImode reference.  
447       // Verify that this operand has two consecutive registers.
448       if (!MI->getOperand(OpNo).isRegister() ||
449           OpNo+1 == MI->getNumOperands() ||
450           !MI->getOperand(OpNo+1).isRegister())
451         return true;
452       ++OpNo;   // Return the high-part.
453       break;
454     case 'I':
455       // Write 'i' if an integer constant, otherwise nothing.  Used to print
456       // addi vs add, etc.
457       if (MI->getOperand(OpNo).isImmediate())
458         O << "i";
459       return false;
460     }
461   }
462   
463   printOperand(MI, OpNo);
464   return false;
465 }
466
467 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
468                                           unsigned AsmVariant, 
469                                           const char *ExtraCode) {
470   if (ExtraCode && ExtraCode[0])
471     return true; // Unknown modifier.
472   if (MI->getOperand(OpNo).isRegister())
473     printMemRegReg(MI, OpNo);
474   else
475     printMemRegImm(MI, OpNo);
476   return false;
477 }
478
479 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
480                                           const char *Modifier) {
481   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
482   unsigned Code = MI->getOperand(OpNo).getImm();
483   if (!strcmp(Modifier, "cc")) {
484     switch ((PPC::Predicate)Code) {
485     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
486     case PPC::PRED_LT: O << "lt"; return;
487     case PPC::PRED_LE: O << "le"; return;
488     case PPC::PRED_EQ: O << "eq"; return;
489     case PPC::PRED_GE: O << "ge"; return;
490     case PPC::PRED_GT: O << "gt"; return;
491     case PPC::PRED_NE: O << "ne"; return;
492     case PPC::PRED_UN: O << "un"; return;
493     case PPC::PRED_NU: O << "nu"; return;
494     }
495       
496   } else {
497     assert(!strcmp(Modifier, "reg") &&
498            "Need to specify 'cc' or 'reg' as predicate op modifier!");
499     // Don't print the register for 'always'.
500     if (Code == PPC::PRED_ALWAYS) return;
501     printOperand(MI, OpNo+1);
502   }
503 }
504
505
506 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
507 /// the current output stream.
508 ///
509 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
510   ++EmittedInsts;
511
512   // Check for slwi/srwi mnemonics.
513   if (MI->getOpcode() == PPC::RLWINM) {
514     bool FoundMnemonic = false;
515     unsigned char SH = MI->getOperand(2).getImm();
516     unsigned char MB = MI->getOperand(3).getImm();
517     unsigned char ME = MI->getOperand(4).getImm();
518     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
519       O << "\tslwi "; FoundMnemonic = true;
520     }
521     if (SH <= 31 && MB == (32-SH) && ME == 31) {
522       O << "\tsrwi "; FoundMnemonic = true;
523       SH = 32-SH;
524     }
525     if (FoundMnemonic) {
526       printOperand(MI, 0);
527       O << ", ";
528       printOperand(MI, 1);
529       O << ", " << (unsigned int)SH << "\n";
530       return;
531     }
532   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
533     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
534       O << "\tmr ";
535       printOperand(MI, 0);
536       O << ", ";
537       printOperand(MI, 1);
538       O << "\n";
539       return;
540     }
541   } else if (MI->getOpcode() == PPC::RLDICR) {
542     unsigned char SH = MI->getOperand(2).getImm();
543     unsigned char ME = MI->getOperand(3).getImm();
544     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
545     if (63-SH == ME) {
546       O << "\tsldi ";
547       printOperand(MI, 0);
548       O << ", ";
549       printOperand(MI, 1);
550       O << ", " << (unsigned int)SH << "\n";
551       return;
552     }
553   }
554
555   if (printInstruction(MI))
556     return; // Printer was automatically generated
557
558   assert(0 && "Unhandled instruction in asm writer!");
559   abort();
560   return;
561 }
562
563 /// runOnMachineFunction - This uses the printMachineInstruction()
564 /// method to print assembly for each instruction.
565 ///
566 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
567   DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
568
569   SetupMachineFunction(MF);
570   O << "\n\n";
571   
572   // Print out constants referenced by the function
573   EmitConstantPool(MF.getConstantPool());
574
575   // Print out labels for the function.
576   const Function *F = MF.getFunction();
577   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
578   
579   switch (F->getLinkage()) {
580   default: assert(0 && "Unknown linkage type!");
581   case Function::InternalLinkage:  // Symbols default to internal.
582     break;
583   case Function::ExternalLinkage:
584     O << "\t.global\t" << CurrentFnName << '\n'
585       << "\t.type\t" << CurrentFnName << ", @function\n";
586     break;
587   case Function::WeakLinkage:
588   case Function::LinkOnceLinkage:
589     O << "\t.global\t" << CurrentFnName << '\n';
590     O << "\t.weak\t" << CurrentFnName << '\n';
591     break;
592   }
593   
594   if (F->hasHiddenVisibility())
595     if (const char *Directive = TAI->getHiddenDirective())
596       O << Directive << CurrentFnName << "\n";
597   
598   EmitAlignment(2, F);
599   O << CurrentFnName << ":\n";
600
601   // Emit pre-function debug information.
602   DW.BeginFunction(&MF);
603
604   // Print out code for the function.
605   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
606        I != E; ++I) {
607     // Print a label for the basic block.
608     if (I != MF.begin()) {
609       printBasicBlockLabel(I, true, true);
610       O << '\n';
611     }
612     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
613          II != E; ++II) {
614       // Print the assembly for the instruction.
615       printMachineInstruction(II);
616     }
617   }
618
619   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
620
621   // Print out jump tables referenced by the function.
622   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
623   
624   // Emit post-function debug information.
625   DW.EndFunction();
626   
627   // We didn't modify anything.
628   return false;
629 }
630
631 bool LinuxAsmPrinter::doInitialization(Module &M) {
632   bool Result = AsmPrinter::doInitialization(M);
633   
634   // GNU as handles section names wrapped in quotes
635   Mang->setUseQuotes(true);
636
637   SwitchToTextSection(TAI->getTextSection());
638   
639   // Emit initial debug information.
640   DW.BeginModule(&M);
641   return Result;
642 }
643
644 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
645 /// Don't print things like \n or \0.
646 static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) {
647   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
648        Name != E; ++Name)
649     if (isprint(*Name))
650       OS << *Name;
651 }
652
653 bool LinuxAsmPrinter::doFinalization(Module &M) {
654   const TargetData *TD = TM.getTargetData();
655
656   // Print out module-level global variables here.
657   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
658        I != E; ++I) {
659     if (!I->hasInitializer()) continue;   // External global require no code
660     
661     // Check to see if this is a special global used by LLVM, if so, emit it.
662     if (EmitSpecialLLVMGlobal(I))
663       continue;
664
665     std::string name = Mang->getValueName(I);
666
667     if (I->hasHiddenVisibility())
668       if (const char *Directive = TAI->getHiddenDirective())
669         O << Directive << name << "\n";
670     
671     Constant *C = I->getInitializer();
672     unsigned Size = TD->getABITypeSize(C->getType());
673     unsigned Align = TD->getPreferredAlignmentLog(I);
674
675     if (C->isNullValue() && /* FIXME: Verify correct */
676         !I->hasSection() && (I->hasCommonLinkage() ||
677          I->hasInternalLinkage() || I->hasWeakLinkage() ||
678          I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
679       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
680       if (I->hasExternalLinkage()) {
681         O << "\t.global " << name << '\n';
682         O << "\t.type " << name << ", @object\n";
683         if (TAI->getBSSSection())
684           SwitchToDataSection(TAI->getBSSSection(), I);
685         O << name << ":\n";
686         O << "\t.zero " << Size << "\n";
687       } else if (I->hasInternalLinkage()) {
688         SwitchToDataSection("\t.data", I);
689         O << TAI->getLCOMMDirective() << name << "," << Size;
690       } else {
691         SwitchToDataSection("\t.data", I);
692         O << ".comm " << name << "," << Size;
693       }
694       O << "\t\t" << TAI->getCommentString() << " '";
695       PrintUnmangledNameSafely(I, O);
696       O << "'\n";
697     } else {
698       switch (I->getLinkage()) {
699       case GlobalValue::LinkOnceLinkage:
700       case GlobalValue::WeakLinkage:
701       case GlobalValue::CommonLinkage:
702         O << "\t.global " << name << '\n'
703           << "\t.type " << name << ", @object\n"
704           << "\t.weak " << name << '\n';
705         SwitchToDataSection("\t.data", I);
706         break;
707       case GlobalValue::AppendingLinkage:
708         // FIXME: appending linkage variables should go into a section of
709         // their name or something.  For now, just emit them as external.
710       case GlobalValue::ExternalLinkage:
711         // If external or appending, declare as a global symbol
712         O << "\t.global " << name << "\n"
713           << "\t.type " << name << ", @object\n";
714         // FALL THROUGH
715       case GlobalValue::InternalLinkage:
716         if (I->isConstant()) {
717           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
718           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
719             SwitchToDataSection(TAI->getCStringSection(), I);
720             break;
721           }
722         }
723
724         // FIXME: special handling for ".ctors" & ".dtors" sections
725         if (I->hasSection() &&
726             (I->getSection() == ".ctors" ||
727              I->getSection() == ".dtors")) {
728           std::string SectionName = ".section " + I->getSection()
729                                                 + ",\"aw\",@progbits";
730           SwitchToDataSection(SectionName.c_str());
731         } else {
732           if (I->isConstant() && TAI->getReadOnlySection())
733             SwitchToDataSection(TAI->getReadOnlySection(), I);
734           else
735             SwitchToDataSection(TAI->getDataSection(), I);
736         }
737         break;
738       default:
739         cerr << "Unknown linkage type!";
740         abort();
741       }
742
743       EmitAlignment(Align, I);
744       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
745       PrintUnmangledNameSafely(I, O);
746       O << "'\n";
747
748       // If the initializer is a extern weak symbol, remember to emit the weak
749       // reference!
750       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
751         if (GV->hasExternalWeakLinkage())
752           ExtWeakSymbols.insert(GV);
753
754       EmitGlobalConstant(C);
755       O << '\n';
756     }
757   }
758
759   // TODO
760
761   // Emit initial debug information.
762   DW.EndModule();
763
764   return AsmPrinter::doFinalization(M);
765 }
766
767 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
768   switch (F.getLinkage()) {
769   default: assert(0 && "Unknown linkage type!");
770   case Function::ExternalLinkage:
771   case Function::InternalLinkage: return TAI->getTextSection();
772   case Function::WeakLinkage:
773   case Function::LinkOnceLinkage:
774     return ".text";
775   }
776 }
777
778 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
779   switch (F.getLinkage()) {
780   default: assert(0 && "Unknown linkage type!");
781   case Function::ExternalLinkage:
782   case Function::InternalLinkage: return TAI->getTextSection();
783   case Function::WeakLinkage:
784   case Function::LinkOnceLinkage:
785     return "\t.section __TEXT,__textcoal_nt,coalesced,pure_instructions";
786   }
787 }
788
789 /// runOnMachineFunction - This uses the printMachineInstruction()
790 /// method to print assembly for each instruction.
791 ///
792 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
793   // We need this for Personality functions.
794   MMI = &getAnalysis<MachineModuleInfo>();
795   DW.SetModuleInfo(MMI);
796
797   SetupMachineFunction(MF);
798   O << "\n\n";
799
800   // Print out constants referenced by the function
801   EmitConstantPool(MF.getConstantPool());
802
803   // Print out labels for the function.
804   const Function *F = MF.getFunction();
805   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
806   
807   switch (F->getLinkage()) {
808   default: assert(0 && "Unknown linkage type!");
809   case Function::InternalLinkage:  // Symbols default to internal.
810     break;
811   case Function::ExternalLinkage:
812     O << "\t.globl\t" << CurrentFnName << "\n";
813     break;
814   case Function::WeakLinkage:
815   case Function::LinkOnceLinkage:
816     O << "\t.globl\t" << CurrentFnName << "\n";
817     O << "\t.weak_definition\t" << CurrentFnName << "\n";
818     break;
819   }
820   
821   if (F->hasHiddenVisibility())
822     if (const char *Directive = TAI->getHiddenDirective())
823       O << Directive << CurrentFnName << "\n";
824   
825   EmitAlignment(OptimizeForSize ? 2 : 4, F);
826   O << CurrentFnName << ":\n";
827
828   // Emit pre-function debug information.
829   DW.BeginFunction(&MF);
830
831   // If the function is empty, then we need to emit *something*. Otherwise, the
832   // function's label might be associated with something that it wasn't meant to
833   // be associated with. We emit a noop in this situation.
834   MachineFunction::iterator I = MF.begin();
835
836   if (++I == MF.end() && MF.front().empty())
837     O << "\tnop\n";
838
839   // Print out code for the function.
840   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
841        I != E; ++I) {
842     // Print a label for the basic block.
843     if (I != MF.begin()) {
844       printBasicBlockLabel(I, true, true);
845       O << '\n';
846     }
847     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
848          II != IE; ++II) {
849       // Print the assembly for the instruction.
850       printMachineInstruction(II);
851     }
852   }
853
854   // Print out jump tables referenced by the function.
855   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
856   
857   // Emit post-function debug information.
858   DW.EndFunction();
859   
860   // We didn't modify anything.
861   return false;
862 }
863
864
865 bool DarwinAsmPrinter::doInitialization(Module &M) {
866   static const char *const CPUDirectives[] = {
867     "",
868     "ppc",
869     "ppc601",
870     "ppc602",
871     "ppc603",
872     "ppc7400",
873     "ppc750",
874     "ppc970",
875     "ppc64"
876   };
877
878   unsigned Directive = Subtarget.getDarwinDirective();
879   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
880     Directive = PPC::DIR_970;
881   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
882     Directive = PPC::DIR_7400;
883   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
884     Directive = PPC::DIR_64;
885   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
886   O << "\t.machine " << CPUDirectives[Directive] << "\n";
887      
888   bool Result = AsmPrinter::doInitialization(M);
889   
890   // Darwin wants symbols to be quoted if they have complex names.
891   Mang->setUseQuotes(true);
892   
893   // Prime text sections so they are adjacent.  This reduces the likelihood a
894   // large data or debug section causes a branch to exceed 16M limit.
895   SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
896                       "pure_instructions");
897   if (TM.getRelocationModel() == Reloc::PIC_) {
898     SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
899                           "pure_instructions,32");
900   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
901     SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
902                         "pure_instructions,16");
903   }
904   SwitchToTextSection(TAI->getTextSection());
905   
906   // Emit initial debug information.
907   DW.BeginModule(&M);
908   return Result;
909 }
910
911 bool DarwinAsmPrinter::doFinalization(Module &M) {
912   const TargetData *TD = TM.getTargetData();
913
914   // Print out module-level global variables here.
915   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
916        I != E; ++I) {
917     if (!I->hasInitializer()) continue;   // External global require no code
918     
919     // Check to see if this is a special global used by LLVM, if so, emit it.
920     if (EmitSpecialLLVMGlobal(I)) {
921       if (TM.getRelocationModel() == Reloc::Static) {
922         if (I->getName() == "llvm.global_ctors")
923           O << ".reference .constructors_used\n";
924         else if (I->getName() == "llvm.global_dtors")
925           O << ".reference .destructors_used\n";
926       }
927       continue;
928     }
929     
930     std::string name = Mang->getValueName(I);
931     
932     if (I->hasHiddenVisibility())
933       if (const char *Directive = TAI->getHiddenDirective())
934         O << Directive << name << "\n";
935     
936     Constant *C = I->getInitializer();
937     const Type *Type = C->getType();
938     unsigned Size = TD->getABITypeSize(Type);
939     unsigned Align = TD->getPreferredAlignmentLog(I);
940
941     if (C->isNullValue() && /* FIXME: Verify correct */
942         !I->hasSection() && (I->hasCommonLinkage() ||
943          I->hasInternalLinkage() || I->hasWeakLinkage() ||
944          I->hasLinkOnceLinkage() || I->hasExternalLinkage())) {
945       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
946       if (I->hasExternalLinkage()) {
947         O << "\t.globl " << name << '\n';
948         O << "\t.zerofill __DATA, __common, " << name << ", "
949           << Size << ", " << Align;
950       } else if (I->hasInternalLinkage()) {
951         SwitchToDataSection("\t.data", I);
952         O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
953       } else if (!I->hasCommonLinkage()) {
954         O << "\t.globl " << name << "\n"
955           << TAI->getWeakDefDirective() << name << "\n";
956         SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
957         EmitAlignment(Align, I);
958         O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
959         PrintUnmangledNameSafely(I, O);
960         O << "\n";
961         EmitGlobalConstant(C);
962         continue;
963       } else {
964         SwitchToDataSection("\t.data", I);
965         O << ".comm " << name << "," << Size;
966         // Darwin 9 and above support aligned common data.
967         if (Subtarget.isDarwin9())
968           O << "," << Align;
969       }
970       O << "\t\t" << TAI->getCommentString() << " '";
971       PrintUnmangledNameSafely(I, O);
972       O << "'\n";
973     } else {
974       switch (I->getLinkage()) {
975       case GlobalValue::LinkOnceLinkage:
976       case GlobalValue::WeakLinkage:
977       case GlobalValue::CommonLinkage:
978         O << "\t.globl " << name << '\n'
979           << "\t.weak_definition " << name << '\n';
980         SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
981         break;
982       case GlobalValue::AppendingLinkage:
983         // FIXME: appending linkage variables should go into a section of
984         // their name or something.  For now, just emit them as external.
985       case GlobalValue::ExternalLinkage:
986         // If external or appending, declare as a global symbol
987         O << "\t.globl " << name << "\n";
988         // FALL THROUGH
989       case GlobalValue::InternalLinkage:
990         if (I->isConstant()) {
991           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
992           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
993             SwitchToDataSection(TAI->getCStringSection(), I);
994             break;
995           }
996         }
997         if (I->hasSection()) {
998           // Honor all section names on Darwin; ObjC uses this
999           std::string SectionName = ".section " + I->getSection();
1000           SwitchToDataSection(SectionName.c_str());
1001         } else if (!I->isConstant())
1002           SwitchToDataSection(TAI->getDataSection(), I);
1003         else {
1004           // Read-only data.
1005           bool HasReloc = C->ContainsRelocations();
1006           if (HasReloc &&
1007               TM.getRelocationModel() != Reloc::Static)
1008             SwitchToDataSection("\t.const_data\n");
1009           else if (!HasReloc && Size == 4 &&
1010                    TAI->getFourByteConstantSection())
1011             SwitchToDataSection(TAI->getFourByteConstantSection(), I);
1012           else if (!HasReloc && Size == 8 &&
1013                    TAI->getEightByteConstantSection())
1014             SwitchToDataSection(TAI->getEightByteConstantSection(), I);
1015           else if (!HasReloc && Size == 16 &&
1016                    TAI->getSixteenByteConstantSection())
1017             SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
1018           else if (TAI->getReadOnlySection())
1019             SwitchToDataSection(TAI->getReadOnlySection(), I);
1020           else
1021             SwitchToDataSection(TAI->getDataSection(), I);
1022         }
1023         break;
1024       default:
1025         cerr << "Unknown linkage type!";
1026         abort();
1027       }
1028
1029       EmitAlignment(Align, I);
1030       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
1031       PrintUnmangledNameSafely(I, O);
1032       O << "'\n";
1033
1034       // If the initializer is a extern weak symbol, remember to emit the weak
1035       // reference!
1036       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1037         if (GV->hasExternalWeakLinkage())
1038           ExtWeakSymbols.insert(GV);
1039
1040       EmitGlobalConstant(C);
1041       O << '\n';
1042     }
1043   }
1044
1045   bool isPPC64 = TD->getPointerSizeInBits() == 64;
1046
1047   // Output stubs for dynamically-linked functions
1048   if (TM.getRelocationModel() == Reloc::PIC_) {
1049     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1050          i != e; ++i) {
1051       SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
1052                           "pure_instructions,32");
1053       EmitAlignment(4);
1054       std::string p = *i;
1055       std::string L0p = (p[0]=='\"') ? "\"L0$" + p.substr(1) : "L0$" + p ;
1056       printSuffixedName(p, "$stub");
1057       O << ":\n";
1058       O << "\t.indirect_symbol " << *i << "\n";
1059       O << "\tmflr r0\n";
1060       O << "\tbcl 20,31," << L0p << "\n";
1061       O << L0p << ":\n";
1062       O << "\tmflr r11\n";
1063       O << "\taddis r11,r11,ha16(";
1064       printSuffixedName(p, "$lazy_ptr");
1065       O << "-" << L0p << ")\n";
1066       O << "\tmtlr r0\n";
1067       if (isPPC64)
1068         O << "\tldu r12,lo16(";
1069       else
1070         O << "\tlwzu r12,lo16(";
1071       printSuffixedName(p, "$lazy_ptr");
1072       O << "-" << L0p << ")(r11)\n";
1073       O << "\tmtctr r12\n";
1074       O << "\tbctr\n";
1075       SwitchToDataSection(".lazy_symbol_pointer");
1076       printSuffixedName(p, "$lazy_ptr");
1077       O << ":\n";
1078       O << "\t.indirect_symbol " << *i << "\n";
1079       if (isPPC64)
1080         O << "\t.quad dyld_stub_binding_helper\n";
1081       else
1082         O << "\t.long dyld_stub_binding_helper\n";
1083     }
1084   } else {
1085     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1086          i != e; ++i) {
1087       SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1088                           "pure_instructions,16");
1089       EmitAlignment(4);
1090       std::string p = *i;
1091       printSuffixedName(p, "$stub");
1092       O << ":\n";
1093       O << "\t.indirect_symbol " << *i << "\n";
1094       O << "\tlis r11,ha16(";
1095       printSuffixedName(p, "$lazy_ptr");
1096       O << ")\n";
1097       if (isPPC64)
1098         O << "\tldu r12,lo16(";
1099       else
1100         O << "\tlwzu r12,lo16(";
1101       printSuffixedName(p, "$lazy_ptr");
1102       O << ")(r11)\n";
1103       O << "\tmtctr r12\n";
1104       O << "\tbctr\n";
1105       SwitchToDataSection(".lazy_symbol_pointer");
1106       printSuffixedName(p, "$lazy_ptr");
1107       O << ":\n";
1108       O << "\t.indirect_symbol " << *i << "\n";
1109       if (isPPC64)
1110         O << "\t.quad dyld_stub_binding_helper\n";
1111       else
1112         O << "\t.long dyld_stub_binding_helper\n";
1113     }
1114   }
1115
1116   O << "\n";
1117
1118   if (TAI->doesSupportExceptionHandling() && MMI) {
1119     // Add the (possibly multiple) personalities to the set of global values.
1120     // Only referenced functions get into the Personalities list.
1121     const std::vector<Function *>& Personalities = MMI->getPersonalities();
1122
1123     for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1124            E = Personalities.end(); I != E; ++I)
1125       if (*I) GVStubs.insert("_" + (*I)->getName());
1126   }
1127
1128   // Output stubs for external and common global variables.
1129   if (!GVStubs.empty()) {
1130     SwitchToDataSection(".non_lazy_symbol_pointer");
1131     for (std::set<std::string>::iterator I = GVStubs.begin(),
1132          E = GVStubs.end(); I != E; ++I) {
1133       std::string p = *I;
1134       printSuffixedName(p, "$non_lazy_ptr");
1135       O << ":\n";
1136       O << "\t.indirect_symbol " << *I << "\n";
1137       if (isPPC64)
1138         O << "\t.quad\t0\n";
1139       else
1140         O << "\t.long\t0\n";
1141         
1142     }
1143   }
1144
1145   // Emit initial debug information.
1146   DW.EndModule();
1147
1148   // Funny Darwin hack: This flag tells the linker that no global symbols
1149   // contain code that falls through to other global symbols (e.g. the obvious
1150   // implementation of multiple entry points).  If this doesn't occur, the
1151   // linker can safely perform dead code stripping.  Since LLVM never generates
1152   // code that does this, it is always safe to set.
1153   O << "\t.subsections_via_symbols\n";
1154
1155   return AsmPrinter::doFinalization(M);
1156 }
1157
1158
1159
1160 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1161 /// for a MachineFunction to the given output stream, in a format that the
1162 /// Darwin assembler can deal with.
1163 ///
1164 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1165                                             PPCTargetMachine &tm) {
1166   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1167
1168   if (Subtarget->isDarwin()) {
1169     return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1170   } else {
1171     return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1172   }
1173 }
1174