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