Make LABEL a builtin opcode.
[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 'c': // Don't print "$" before a global var name or constant.
416       // PPC never has a prefix.
417       printOperand(MI, OpNo);
418       return false;
419     case 'L': // Write second word of DImode reference.  
420       // Verify that this operand has two consecutive registers.
421       if (!MI->getOperand(OpNo).isRegister() ||
422           OpNo+1 == MI->getNumOperands() ||
423           !MI->getOperand(OpNo+1).isRegister())
424         return true;
425       ++OpNo;   // Return the high-part.
426       break;
427     }
428   }
429   
430   printOperand(MI, OpNo);
431   return false;
432 }
433
434 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
435                                           unsigned AsmVariant, 
436                                           const char *ExtraCode) {
437   if (ExtraCode && ExtraCode[0])
438     return true; // Unknown modifier.
439   printMemRegReg(MI, OpNo);
440   return false;
441 }
442
443 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
444                                           const char *Modifier) {
445   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
446   unsigned Code = MI->getOperand(OpNo).getImm();
447   if (!strcmp(Modifier, "cc")) {
448     switch ((PPC::Predicate)Code) {
449     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
450     case PPC::PRED_LT: O << "lt"; return;
451     case PPC::PRED_LE: O << "le"; return;
452     case PPC::PRED_EQ: O << "eq"; return;
453     case PPC::PRED_GE: O << "ge"; return;
454     case PPC::PRED_GT: O << "gt"; return;
455     case PPC::PRED_NE: O << "ne"; return;
456     case PPC::PRED_UN: O << "un"; return;
457     case PPC::PRED_NU: O << "nu"; return;
458     }
459       
460   } else {
461     assert(!strcmp(Modifier, "reg") &&
462            "Need to specify 'cc' or 'reg' as predicate op modifier!");
463     // Don't print the register for 'always'.
464     if (Code == PPC::PRED_ALWAYS) return;
465     printOperand(MI, OpNo+1);
466   }
467 }
468
469
470 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
471 /// the current output stream.
472 ///
473 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
474   ++EmittedInsts;
475
476   // Check for slwi/srwi mnemonics.
477   if (MI->getOpcode() == PPC::RLWINM) {
478     bool FoundMnemonic = false;
479     unsigned char SH = MI->getOperand(2).getImmedValue();
480     unsigned char MB = MI->getOperand(3).getImmedValue();
481     unsigned char ME = MI->getOperand(4).getImmedValue();
482     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
483       O << "slwi "; FoundMnemonic = true;
484     }
485     if (SH <= 31 && MB == (32-SH) && ME == 31) {
486       O << "srwi "; FoundMnemonic = true;
487       SH = 32-SH;
488     }
489     if (FoundMnemonic) {
490       printOperand(MI, 0);
491       O << ", ";
492       printOperand(MI, 1);
493       O << ", " << (unsigned int)SH << "\n";
494       return;
495     }
496   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
497     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
498       O << "mr ";
499       printOperand(MI, 0);
500       O << ", ";
501       printOperand(MI, 1);
502       O << "\n";
503       return;
504     }
505   } else if (MI->getOpcode() == PPC::RLDICR) {
506     unsigned char SH = MI->getOperand(2).getImmedValue();
507     unsigned char ME = MI->getOperand(3).getImmedValue();
508     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
509     if (63-SH == ME) {
510       O << "sldi ";
511       printOperand(MI, 0);
512       O << ", ";
513       printOperand(MI, 1);
514       O << ", " << (unsigned int)SH << "\n";
515       return;
516     }
517   }
518
519   if (printInstruction(MI))
520     return; // Printer was automatically generated
521
522   assert(0 && "Unhandled instruction in asm writer!");
523   abort();
524   return;
525 }
526
527 /// runOnMachineFunction - This uses the printMachineInstruction()
528 /// method to print assembly for each instruction.
529 ///
530 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
531   DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
532
533   SetupMachineFunction(MF);
534   O << "\n\n";
535   
536   // Print out constants referenced by the function
537   EmitConstantPool(MF.getConstantPool());
538
539   // Print out labels for the function.
540   const Function *F = MF.getFunction();
541   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
542   
543   switch (F->getLinkage()) {
544   default: assert(0 && "Unknown linkage type!");
545   case Function::InternalLinkage:  // Symbols default to internal.
546     break;
547   case Function::ExternalLinkage:
548     O << "\t.global\t" << CurrentFnName << '\n'
549       << "\t.type\t" << CurrentFnName << ", @function\n";
550     break;
551   case Function::WeakLinkage:
552   case Function::LinkOnceLinkage:
553     O << "\t.global\t" << CurrentFnName << '\n';
554     O << "\t.weak\t" << CurrentFnName << '\n';
555     break;
556   }
557   
558   if (F->hasHiddenVisibility())
559     if (const char *Directive = TAI->getHiddenDirective())
560       O << Directive << CurrentFnName << "\n";
561   
562   EmitAlignment(2, F);
563   O << CurrentFnName << ":\n";
564
565   // Emit pre-function debug information.
566   DW.BeginFunction(&MF);
567
568   // Print out code for the function.
569   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
570        I != E; ++I) {
571     // Print a label for the basic block.
572     if (I != MF.begin()) {
573       printBasicBlockLabel(I, true);
574       O << '\n';
575     }
576     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
577          II != E; ++II) {
578       // Print the assembly for the instruction.
579       O << "\t";
580       printMachineInstruction(II);
581     }
582   }
583
584   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
585
586   // Print out jump tables referenced by the function.
587   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
588   
589   // Emit post-function debug information.
590   DW.EndFunction();
591   
592   // We didn't modify anything.
593   return false;
594 }
595
596 bool LinuxAsmPrinter::doInitialization(Module &M) {
597   AsmPrinter::doInitialization(M);
598   
599   // GNU as handles section names wrapped in quotes
600   Mang->setUseQuotes(true);
601
602   SwitchToTextSection(TAI->getTextSection());
603   
604   // Emit initial debug information.
605   DW.BeginModule(&M);
606   return false;
607 }
608
609 bool LinuxAsmPrinter::doFinalization(Module &M) {
610   const TargetData *TD = TM.getTargetData();
611
612   // Print out module-level global variables here.
613   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
614        I != E; ++I) {
615     if (!I->hasInitializer()) continue;   // External global require no code
616     
617     // Check to see if this is a special global used by LLVM, if so, emit it.
618     if (EmitSpecialLLVMGlobal(I))
619       continue;
620
621     std::string name = Mang->getValueName(I);
622
623     if (I->hasHiddenVisibility())
624       if (const char *Directive = TAI->getHiddenDirective())
625         O << Directive << name << "\n";
626     
627     Constant *C = I->getInitializer();
628     unsigned Size = TD->getTypeSize(C->getType());
629     unsigned Align = TD->getPreferredAlignmentLog(I);
630
631     if (C->isNullValue() && /* FIXME: Verify correct */
632         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
633          I->hasLinkOnceLinkage() ||
634          (I->hasExternalLinkage() && !I->hasSection()))) {
635       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
636       if (I->hasExternalLinkage()) {
637         O << "\t.global " << name << '\n';
638         O << "\t.type " << name << ", @object\n";
639         //O << "\t.zerofill __DATA, __common, " << name << ", "
640         //  << Size << ", " << Align;
641       } else if (I->hasInternalLinkage()) {
642         SwitchToDataSection("\t.data", I);
643         O << TAI->getLCOMMDirective() << name << "," << Size;
644       } else {
645         SwitchToDataSection("\t.data", I);
646         O << ".comm " << name << "," << Size;
647       }
648       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
649     } else {
650       switch (I->getLinkage()) {
651       case GlobalValue::LinkOnceLinkage:
652       case GlobalValue::WeakLinkage:
653         O << "\t.global " << name << '\n'
654           << "\t.type " << name << ", @object\n"
655           << "\t.weak " << name << '\n';
656         SwitchToDataSection("\t.data", I);
657         break;
658       case GlobalValue::AppendingLinkage:
659         // FIXME: appending linkage variables should go into a section of
660         // their name or something.  For now, just emit them as external.
661       case GlobalValue::ExternalLinkage:
662         // If external or appending, declare as a global symbol
663         O << "\t.global " << name << "\n"
664           << "\t.type " << name << ", @object\n";
665         // FALL THROUGH
666       case GlobalValue::InternalLinkage:
667         if (I->isConstant()) {
668           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
669           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
670             SwitchToDataSection(TAI->getCStringSection(), I);
671             break;
672           }
673         }
674
675         // FIXME: special handling for ".ctors" & ".dtors" sections
676         if (I->hasSection() &&
677             (I->getSection() == ".ctors" ||
678              I->getSection() == ".dtors")) {
679           std::string SectionName = ".section " + I->getSection()
680                                                 + ",\"aw\",@progbits";
681           SwitchToDataSection(SectionName.c_str());
682         } else {
683           SwitchToDataSection(TAI->getDataSection(), I);
684         }
685         break;
686       default:
687         cerr << "Unknown linkage type!";
688         abort();
689       }
690
691       EmitAlignment(Align, I);
692       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
693         << I->getName() << "'\n";
694
695       // If the initializer is a extern weak symbol, remember to emit the weak
696       // reference!
697       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
698         if (GV->hasExternalWeakLinkage())
699           ExtWeakSymbols.insert(GV);
700
701       EmitGlobalConstant(C);
702       O << '\n';
703     }
704   }
705
706   // TODO
707
708   // Emit initial debug information.
709   DW.EndModule();
710
711   AsmPrinter::doFinalization(M);
712   return false; // success
713 }
714
715 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
716   switch (F.getLinkage()) {
717   default: assert(0 && "Unknown linkage type!");
718   case Function::ExternalLinkage:
719   case Function::InternalLinkage: return TAI->getTextSection();
720   case Function::WeakLinkage:
721   case Function::LinkOnceLinkage:
722     return ".text";
723   }
724 }
725
726 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
727   switch (F.getLinkage()) {
728   default: assert(0 && "Unknown linkage type!");
729   case Function::ExternalLinkage:
730   case Function::InternalLinkage: return TAI->getTextSection();
731   case Function::WeakLinkage:
732   case Function::LinkOnceLinkage:
733     return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
734   }
735 }
736
737 /// runOnMachineFunction - This uses the printMachineInstruction()
738 /// method to print assembly for each instruction.
739 ///
740 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
741   DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
742
743   SetupMachineFunction(MF);
744   O << "\n\n";
745   
746   // Print out constants referenced by the function
747   EmitConstantPool(MF.getConstantPool());
748
749   // Print out labels for the function.
750   const Function *F = MF.getFunction();
751   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
752   
753   switch (F->getLinkage()) {
754   default: assert(0 && "Unknown linkage type!");
755   case Function::InternalLinkage:  // Symbols default to internal.
756     break;
757   case Function::ExternalLinkage:
758     O << "\t.globl\t" << CurrentFnName << "\n";
759     break;
760   case Function::WeakLinkage:
761   case Function::LinkOnceLinkage:
762     O << "\t.globl\t" << CurrentFnName << "\n";
763     O << "\t.weak_definition\t" << CurrentFnName << "\n";
764     break;
765   }
766   
767   if (F->hasHiddenVisibility())
768     if (const char *Directive = TAI->getHiddenDirective())
769       O << Directive << CurrentFnName << "\n";
770   
771   EmitAlignment(4, F);
772   O << CurrentFnName << ":\n";
773
774   // Emit pre-function debug information.
775   DW.BeginFunction(&MF);
776
777   // Print out code for the function.
778   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
779        I != E; ++I) {
780     // Print a label for the basic block.
781     if (I != MF.begin()) {
782       printBasicBlockLabel(I, true);
783       O << '\n';
784     }
785     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
786          II != E; ++II) {
787       // Print the assembly for the instruction.
788       O << "\t";
789       printMachineInstruction(II);
790     }
791   }
792
793   // Print out jump tables referenced by the function.
794   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
795   
796   // Emit post-function debug information.
797   DW.EndFunction();
798   
799   // We didn't modify anything.
800   return false;
801 }
802
803
804 bool DarwinAsmPrinter::doInitialization(Module &M) {
805   static const char *CPUDirectives[] = {
806     "ppc",
807     "ppc601",
808     "ppc602",
809     "ppc603",
810     "ppc7400",
811     "ppc750",
812     "ppc970",
813     "ppc64"
814   };
815
816   unsigned Directive = Subtarget.getDarwinDirective();
817   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
818     Directive = PPC::DIR_970;
819   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
820     Directive = PPC::DIR_7400;
821   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
822     Directive = PPC::DIR_64;
823   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
824   O << "\t.machine " << CPUDirectives[Directive] << "\n";
825      
826   AsmPrinter::doInitialization(M);
827   
828   // Darwin wants symbols to be quoted if they have complex names.
829   Mang->setUseQuotes(true);
830   
831   // Prime text sections so they are adjacent.  This reduces the likelihood a
832   // large data or debug section causes a branch to exceed 16M limit.
833   SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
834                       "pure_instructions");
835   if (TM.getRelocationModel() == Reloc::PIC_) {
836     SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
837                           "pure_instructions,32");
838   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
839     SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
840                         "pure_instructions,16");
841   }
842   SwitchToTextSection(TAI->getTextSection());
843   
844   // Emit initial debug information.
845   DW.BeginModule(&M);
846   return false;
847 }
848
849 bool DarwinAsmPrinter::doFinalization(Module &M) {
850   const TargetData *TD = TM.getTargetData();
851
852   // Print out module-level global variables here.
853   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
854        I != E; ++I) {
855     if (!I->hasInitializer()) continue;   // External global require no code
856     
857     // Check to see if this is a special global used by LLVM, if so, emit it.
858     if (EmitSpecialLLVMGlobal(I))
859       continue;
860     
861     std::string name = Mang->getValueName(I);
862     
863     if (I->hasHiddenVisibility())
864       if (const char *Directive = TAI->getHiddenDirective())
865         O << Directive << name << "\n";
866     
867     Constant *C = I->getInitializer();
868     unsigned Size = TD->getTypeSize(C->getType());
869     unsigned Align = TD->getPreferredAlignmentLog(I);
870
871     if (C->isNullValue() && /* FIXME: Verify correct */
872         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
873          I->hasLinkOnceLinkage() ||
874          (I->hasExternalLinkage() && !I->hasSection()))) {
875       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
876       if (I->hasExternalLinkage()) {
877         O << "\t.globl " << name << '\n';
878         O << "\t.zerofill __DATA, __common, " << name << ", "
879           << Size << ", " << Align;
880       } else if (I->hasInternalLinkage()) {
881         SwitchToDataSection("\t.data", I);
882         O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
883       } else {
884         SwitchToDataSection("\t.data", I);
885         O << ".comm " << name << "," << Size;
886       }
887       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
888     } else {
889       switch (I->getLinkage()) {
890       case GlobalValue::LinkOnceLinkage:
891       case GlobalValue::WeakLinkage:
892         O << "\t.globl " << name << '\n'
893           << "\t.weak_definition " << name << '\n';
894         SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
895         break;
896       case GlobalValue::AppendingLinkage:
897         // FIXME: appending linkage variables should go into a section of
898         // their name or something.  For now, just emit them as external.
899       case GlobalValue::ExternalLinkage:
900         // If external or appending, declare as a global symbol
901         O << "\t.globl " << name << "\n";
902         // FALL THROUGH
903       case GlobalValue::InternalLinkage:
904         if (I->isConstant()) {
905           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
906           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
907             SwitchToDataSection(TAI->getCStringSection(), I);
908             break;
909           }
910         }
911
912         SwitchToDataSection("\t.data", I);
913         break;
914       default:
915         cerr << "Unknown linkage type!";
916         abort();
917       }
918
919       EmitAlignment(Align, I);
920       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
921         << I->getName() << "'\n";
922
923       // If the initializer is a extern weak symbol, remember to emit the weak
924       // reference!
925       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
926         if (GV->hasExternalWeakLinkage())
927           ExtWeakSymbols.insert(GV);
928
929       EmitGlobalConstant(C);
930       O << '\n';
931     }
932   }
933
934   bool isPPC64 = TD->getPointerSizeInBits() == 64;
935
936   // Output stubs for dynamically-linked functions
937   if (TM.getRelocationModel() == Reloc::PIC_) {
938     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
939          i != e; ++i) {
940       SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
941                           "pure_instructions,32");
942       EmitAlignment(4);
943       O << "L" << *i << "$stub:\n";
944       O << "\t.indirect_symbol " << *i << "\n";
945       O << "\tmflr r0\n";
946       O << "\tbcl 20,31,L0$" << *i << "\n";
947       O << "L0$" << *i << ":\n";
948       O << "\tmflr r11\n";
949       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
950       O << "\tmtlr r0\n";
951       if (isPPC64)
952         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
953       else
954         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
955       O << "\tmtctr r12\n";
956       O << "\tbctr\n";
957       SwitchToDataSection(".lazy_symbol_pointer");
958       O << "L" << *i << "$lazy_ptr:\n";
959       O << "\t.indirect_symbol " << *i << "\n";
960       if (isPPC64)
961         O << "\t.quad dyld_stub_binding_helper\n";
962       else
963         O << "\t.long dyld_stub_binding_helper\n";
964     }
965   } else {
966     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
967          i != e; ++i) {
968       SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
969                           "pure_instructions,16");
970       EmitAlignment(4);
971       O << "L" << *i << "$stub:\n";
972       O << "\t.indirect_symbol " << *i << "\n";
973       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
974       if (isPPC64)
975         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
976       else
977         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
978       O << "\tmtctr r12\n";
979       O << "\tbctr\n";
980       SwitchToDataSection(".lazy_symbol_pointer");
981       O << "L" << *i << "$lazy_ptr:\n";
982       O << "\t.indirect_symbol " << *i << "\n";
983       if (isPPC64)
984         O << "\t.quad dyld_stub_binding_helper\n";
985       else
986         O << "\t.long dyld_stub_binding_helper\n";
987     }
988   }
989
990   O << "\n";
991
992   // Output stubs for external and common global variables.
993   if (GVStubs.begin() != GVStubs.end()) {
994     SwitchToDataSection(".non_lazy_symbol_pointer");
995     for (std::set<std::string>::iterator I = GVStubs.begin(),
996          E = GVStubs.end(); I != E; ++I) {
997       O << "L" << *I << "$non_lazy_ptr:\n";
998       O << "\t.indirect_symbol " << *I << "\n";
999       if (isPPC64)
1000         O << "\t.quad\t0\n";
1001       else
1002         O << "\t.long\t0\n";
1003         
1004     }
1005   }
1006
1007   // Emit initial debug information.
1008   DW.EndModule();
1009
1010   // Funny Darwin hack: This flag tells the linker that no global symbols
1011   // contain code that falls through to other global symbols (e.g. the obvious
1012   // implementation of multiple entry points).  If this doesn't occur, the
1013   // linker can safely perform dead code stripping.  Since LLVM never generates
1014   // code that does this, it is always safe to set.
1015   O << "\t.subsections_via_symbols\n";
1016
1017   AsmPrinter::doFinalization(M);
1018   return false; // success
1019 }
1020
1021
1022
1023 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1024 /// for a MachineFunction to the given output stream, in a format that the
1025 /// Darwin assembler can deal with.
1026 ///
1027 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1028                                             PPCTargetMachine &tm) {
1029   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1030
1031   if (Subtarget->isDarwin()) {
1032     return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1033   } else {
1034     return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1035   }
1036 }
1037