96c86655d9665d29cf76b177c23a01f5bb0a7f91
[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
650   // Emit initial debug information.
651   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
652   assert(MMI);
653   DW = getAnalysisIfAvailable<DwarfWriter>();
654   assert(DW && "DwarfWriter is not available");
655   DW->BeginModule(&M, MMI, O, this, TAI);
656
657   // GNU as handles section names wrapped in quotes
658   Mang->setUseQuotes(true);
659
660   SwitchToSection(TAI->getTextSection());
661
662   return Result;
663 }
664
665 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
666 /// Don't print things like \\n or \\0.
667 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
668   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
669        Name != E; ++Name)
670     if (isprint(*Name))
671       OS << *Name;
672 }
673
674 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
675   const TargetData *TD = TM.getTargetData();
676
677   if (!GVar->hasInitializer())
678     return;   // External global require no code
679
680   // Check to see if this is a special global used by LLVM, if so, emit it.
681   if (EmitSpecialLLVMGlobal(GVar))
682     return;
683
684   std::string name = Mang->getValueName(GVar);
685
686   printVisibility(name, GVar->getVisibility());
687
688   Constant *C = GVar->getInitializer();
689   const Type *Type = C->getType();
690   unsigned Size = TD->getTypePaddedSize(Type);
691   unsigned Align = TD->getPreferredAlignmentLog(GVar);
692
693   SwitchToSection(TAI->SectionForGlobal(GVar));
694
695   if (C->isNullValue() && /* FIXME: Verify correct */
696       !GVar->hasSection() &&
697       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
698        GVar->isWeakForLinker())) {
699       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
700
701       if (GVar->hasExternalLinkage()) {
702         O << "\t.global " << name << '\n';
703         O << "\t.type " << name << ", @object\n";
704         O << name << ":\n";
705         O << "\t.zero " << Size << '\n';
706       } else if (GVar->hasLocalLinkage()) {
707         O << TAI->getLCOMMDirective() << name << ',' << Size;
708       } else {
709         O << ".comm " << name << ',' << Size;
710       }
711       if (VerboseAsm) {
712         O << "\t\t" << TAI->getCommentString() << " '";
713         PrintUnmangledNameSafely(GVar, O);
714         O << "'";
715       }
716       O << '\n';
717       return;
718   }
719
720   switch (GVar->getLinkage()) {
721    case GlobalValue::LinkOnceAnyLinkage:
722    case GlobalValue::LinkOnceODRLinkage:
723    case GlobalValue::WeakAnyLinkage:
724    case GlobalValue::WeakODRLinkage:
725    case GlobalValue::CommonLinkage:
726     O << "\t.global " << name << '\n'
727       << "\t.type " << name << ", @object\n"
728       << "\t.weak " << name << '\n';
729     break;
730    case GlobalValue::AppendingLinkage:
731     // FIXME: appending linkage variables should go into a section of
732     // their name or something.  For now, just emit them as external.
733    case GlobalValue::ExternalLinkage:
734     // If external or appending, declare as a global symbol
735     O << "\t.global " << name << '\n'
736       << "\t.type " << name << ", @object\n";
737     // FALL THROUGH
738    case GlobalValue::InternalLinkage:
739    case GlobalValue::PrivateLinkage:
740     break;
741    default:
742     cerr << "Unknown linkage type!";
743     abort();
744   }
745
746   EmitAlignment(Align, GVar);
747   O << name << ":";
748   if (VerboseAsm) {
749     O << "\t\t\t\t" << TAI->getCommentString() << " '";
750     PrintUnmangledNameSafely(GVar, O);
751     O << "'";
752   }
753   O << '\n';
754
755   // If the initializer is a extern weak symbol, remember to emit the weak
756   // reference!
757   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
758     if (GV->hasExternalWeakLinkage())
759       ExtWeakSymbols.insert(GV);
760
761   EmitGlobalConstant(C);
762   O << '\n';
763 }
764
765 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
766   // Print out module-level global variables here.
767   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
768        I != E; ++I)
769     printModuleLevelGV(I);
770
771   // TODO
772
773   // Emit initial debug information.
774   DW->EndModule();
775
776   return AsmPrinter::doFinalization(M);
777 }
778
779 /// runOnMachineFunction - This uses the printMachineInstruction()
780 /// method to print assembly for each instruction.
781 ///
782 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
783   this->MF = &MF;
784
785   SetupMachineFunction(MF);
786   O << "\n\n";
787
788   // Print out constants referenced by the function
789   EmitConstantPool(MF.getConstantPool());
790
791   // Print out labels for the function.
792   const Function *F = MF.getFunction();
793   SwitchToSection(TAI->SectionForGlobal(F));
794
795   switch (F->getLinkage()) {
796   default: assert(0 && "Unknown linkage type!");
797   case Function::PrivateLinkage:
798   case Function::InternalLinkage:  // Symbols default to internal.
799     break;
800   case Function::ExternalLinkage:
801     O << "\t.globl\t" << CurrentFnName << '\n';
802     break;
803   case Function::WeakAnyLinkage:
804   case Function::WeakODRLinkage:
805   case Function::LinkOnceAnyLinkage:
806   case Function::LinkOnceODRLinkage:
807     O << "\t.globl\t" << CurrentFnName << '\n';
808     O << "\t.weak_definition\t" << CurrentFnName << '\n';
809     break;
810   }
811
812   printVisibility(CurrentFnName, F->getVisibility());
813
814   EmitAlignment(F->hasFnAttr(Attribute::OptimizeForSize) ? 2 : 4, F);
815   O << CurrentFnName << ":\n";
816
817   // Emit pre-function debug information.
818   DW->BeginFunction(&MF);
819
820   // If the function is empty, then we need to emit *something*. Otherwise, the
821   // function's label might be associated with something that it wasn't meant to
822   // be associated with. We emit a noop in this situation.
823   MachineFunction::iterator I = MF.begin();
824
825   if (++I == MF.end() && MF.front().empty())
826     O << "\tnop\n";
827
828   // Print out code for the function.
829   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
830        I != E; ++I) {
831     // Print a label for the basic block.
832     if (I != MF.begin()) {
833       printBasicBlockLabel(I, true, true, VerboseAsm);
834       O << '\n';
835     }
836     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
837          II != IE; ++II) {
838       // Print the assembly for the instruction.
839       printMachineInstruction(II);
840     }
841   }
842
843   // Print out jump tables referenced by the function.
844   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
845
846   // Emit post-function debug information.
847   DW->EndFunction(&MF);
848
849   // We didn't modify anything.
850   return false;
851 }
852
853
854 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
855   static const char *const CPUDirectives[] = {
856     "",
857     "ppc",
858     "ppc601",
859     "ppc602",
860     "ppc603",
861     "ppc7400",
862     "ppc750",
863     "ppc970",
864     "ppc64"
865   };
866
867   unsigned Directive = Subtarget.getDarwinDirective();
868   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
869     Directive = PPC::DIR_970;
870   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
871     Directive = PPC::DIR_7400;
872   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
873     Directive = PPC::DIR_64;
874   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
875   O << "\t.machine " << CPUDirectives[Directive] << '\n';
876
877   bool Result = AsmPrinter::doInitialization(M);
878
879   // Emit initial debug information.
880   // We need this for Personality functions.
881   // AsmPrinter::doInitialization should have done this analysis.
882   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
883   assert(MMI);
884   DW = getAnalysisIfAvailable<DwarfWriter>();
885   assert(DW && "DwarfWriter is not available");
886   DW->BeginModule(&M, MMI, O, this, TAI);
887
888   // Darwin wants symbols to be quoted if they have complex names.
889   Mang->setUseQuotes(true);
890
891   // Prime text sections so they are adjacent.  This reduces the likelihood a
892   // large data or debug section causes a branch to exceed 16M limit.
893   SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
894                       "pure_instructions");
895   if (TM.getRelocationModel() == Reloc::PIC_) {
896     SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
897                           "pure_instructions,32");
898   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
899     SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
900                         "pure_instructions,16");
901   }
902   SwitchToSection(TAI->getTextSection());
903
904   return Result;
905 }
906
907 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
908   const TargetData *TD = TM.getTargetData();
909
910   if (!GVar->hasInitializer())
911     return;   // External global require no code
912
913   // Check to see if this is a special global used by LLVM, if so, emit it.
914   if (EmitSpecialLLVMGlobal(GVar)) {
915     if (TM.getRelocationModel() == Reloc::Static) {
916       if (GVar->getName() == "llvm.global_ctors")
917         O << ".reference .constructors_used\n";
918       else if (GVar->getName() == "llvm.global_dtors")
919         O << ".reference .destructors_used\n";
920     }
921     return;
922   }
923
924   std::string name = Mang->getValueName(GVar);
925
926   printVisibility(name, GVar->getVisibility());
927
928   Constant *C = GVar->getInitializer();
929   const Type *Type = C->getType();
930   unsigned Size = TD->getTypePaddedSize(Type);
931   unsigned Align = TD->getPreferredAlignmentLog(GVar);
932
933   SwitchToSection(TAI->SectionForGlobal(GVar));
934
935   if (C->isNullValue() && /* FIXME: Verify correct */
936       !GVar->hasSection() &&
937       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
938        GVar->isWeakForLinker()) &&
939       TAI->SectionKindForGlobal(GVar) != SectionKind::RODataMergeStr) {
940     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
941
942     if (GVar->hasExternalLinkage()) {
943       O << "\t.globl " << name << '\n';
944       O << "\t.zerofill __DATA, __common, " << name << ", "
945         << Size << ", " << Align;
946     } else if (GVar->hasLocalLinkage()) {
947       O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
948     } else if (!GVar->hasCommonLinkage()) {
949       O << "\t.globl " << name << '\n'
950         << TAI->getWeakDefDirective() << name << '\n';
951       EmitAlignment(Align, GVar);
952       O << name << ":";
953       if (VerboseAsm) {
954         O << "\t\t\t\t" << TAI->getCommentString() << " ";
955         PrintUnmangledNameSafely(GVar, O);
956       }
957       O << '\n';
958       EmitGlobalConstant(C);
959       return;
960     } else {
961       O << ".comm " << name << ',' << Size;
962       // Darwin 9 and above support aligned common data.
963       if (Subtarget.isDarwin9())
964         O << ',' << Align;
965     }
966     if (VerboseAsm) {
967       O << "\t\t" << TAI->getCommentString() << " '";
968       PrintUnmangledNameSafely(GVar, O);
969       O << "'";
970     }
971     O << '\n';
972     return;
973   }
974
975   switch (GVar->getLinkage()) {
976    case GlobalValue::LinkOnceAnyLinkage:
977    case GlobalValue::LinkOnceODRLinkage:
978    case GlobalValue::WeakAnyLinkage:
979    case GlobalValue::WeakODRLinkage:
980    case GlobalValue::CommonLinkage:
981     O << "\t.globl " << name << '\n'
982       << "\t.weak_definition " << name << '\n';
983     break;
984    case GlobalValue::AppendingLinkage:
985     // FIXME: appending linkage variables should go into a section of
986     // their name or something.  For now, just emit them as external.
987    case GlobalValue::ExternalLinkage:
988     // If external or appending, declare as a global symbol
989     O << "\t.globl " << name << '\n';
990     // FALL THROUGH
991    case GlobalValue::InternalLinkage:
992    case GlobalValue::PrivateLinkage:
993     break;
994    default:
995     cerr << "Unknown linkage type!";
996     abort();
997   }
998
999   EmitAlignment(Align, GVar);
1000   O << name << ":";
1001   if (VerboseAsm) {
1002     O << "\t\t\t\t" << TAI->getCommentString() << " '";
1003     PrintUnmangledNameSafely(GVar, O);
1004     O << "'";
1005   }
1006   O << '\n';
1007
1008   // If the initializer is a extern weak symbol, remember to emit the weak
1009   // reference!
1010   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1011     if (GV->hasExternalWeakLinkage())
1012       ExtWeakSymbols.insert(GV);
1013
1014   EmitGlobalConstant(C);
1015   O << '\n';
1016 }
1017
1018 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1019   const TargetData *TD = TM.getTargetData();
1020
1021   // Print out module-level global variables here.
1022   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1023        I != E; ++I)
1024     printModuleLevelGV(I);
1025
1026   bool isPPC64 = TD->getPointerSizeInBits() == 64;
1027
1028   // Output stubs for dynamically-linked functions
1029   if (TM.getRelocationModel() == Reloc::PIC_) {
1030     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1031          i != e; ++i) {
1032       SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
1033                           "pure_instructions,32");
1034       EmitAlignment(4);
1035       const char *p = i->getKeyData();
1036       bool hasQuote = p[0]=='\"';
1037       printSuffixedName(p, "$stub");
1038       O << ":\n";
1039       O << "\t.indirect_symbol " << p << '\n';
1040       O << "\tmflr r0\n";
1041       O << "\tbcl 20,31,";
1042       if (hasQuote)
1043         O << "\"L0$" << &p[1];
1044       else
1045         O << "L0$" << p;
1046       O << '\n';
1047       if (hasQuote)
1048         O << "\"L0$" << &p[1];
1049       else
1050         O << "L0$" << p;
1051       O << ":\n";
1052       O << "\tmflr r11\n";
1053       O << "\taddis r11,r11,ha16(";
1054       printSuffixedName(p, "$lazy_ptr");
1055       O << "-";
1056       if (hasQuote)
1057         O << "\"L0$" << &p[1];
1058       else
1059         O << "L0$" << p;
1060       O << ")\n";
1061       O << "\tmtlr r0\n";
1062       if (isPPC64)
1063         O << "\tldu r12,lo16(";
1064       else
1065         O << "\tlwzu r12,lo16(";
1066       printSuffixedName(p, "$lazy_ptr");
1067       O << "-";
1068       if (hasQuote)
1069         O << "\"L0$" << &p[1];
1070       else
1071         O << "L0$" << p;
1072       O << ")(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 " << p << '\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 (StringSet<>::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       const char *p = i->getKeyData();
1091       printSuffixedName(p, "$stub");
1092       O << ":\n";
1093       O << "\t.indirect_symbol " << p << '\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 " << p << '\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 (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1132          i != e; ++i) {
1133       std::string p = i->getKeyData();
1134       printSuffixedName(p, "$non_lazy_ptr");
1135       O << ":\n";
1136       O << "\t.indirect_symbol " << p << '\n';
1137       if (isPPC64)
1138         O << "\t.quad\t0\n";
1139       else
1140         O << "\t.long\t0\n";
1141     }
1142   }
1143
1144   if (!HiddenGVStubs.empty()) {
1145     SwitchToSection(TAI->getDataSection());
1146     for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1147          i != e; ++i) {
1148       std::string p = i->getKeyData();
1149       EmitAlignment(isPPC64 ? 3 : 2);
1150       printSuffixedName(p, "$non_lazy_ptr");
1151       O << ":\n";
1152       if (isPPC64)
1153         O << "\t.quad\t";
1154       else
1155         O << "\t.long\t";
1156       O << p << '\n';
1157     }
1158   }
1159
1160
1161   // Emit initial debug information.
1162   DW->EndModule();
1163
1164   // Funny Darwin hack: This flag tells the linker that no global symbols
1165   // contain code that falls through to other global symbols (e.g. the obvious
1166   // implementation of multiple entry points).  If this doesn't occur, the
1167   // linker can safely perform dead code stripping.  Since LLVM never generates
1168   // code that does this, it is always safe to set.
1169   O << "\t.subsections_via_symbols\n";
1170
1171   return AsmPrinter::doFinalization(M);
1172 }
1173
1174
1175
1176 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1177 /// for a MachineFunction to the given output stream, in a format that the
1178 /// Darwin assembler can deal with.
1179 ///
1180 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1181                                             PPCTargetMachine &tm,
1182                                             CodeGenOpt::Level OptLevel,
1183                                             bool verbose) {
1184   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1185
1186   if (Subtarget->isDarwin()) {
1187     return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1188                                    OptLevel, verbose);
1189   } else {
1190     return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(),
1191                                   OptLevel, verbose);
1192   }
1193 }
1194
1195 namespace {
1196   static struct Register {
1197     Register() {
1198       PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);
1199     }
1200   } Registrator;
1201 }
1202
1203 extern "C" int PowerPCAsmPrinterForceLink;
1204 int PowerPCAsmPrinterForceLink = 0;