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