Fix PR1351 and CodeGen/PowerPC/2007-04-24-InlineAsm-I-Modifier.ll
[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/MachineModuleInfo.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->isDeclaration() || 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         if (Subtarget.isDarwin()) O << "ha16(";
219         printOp(MI->getOperand(OpNo));
220         if (TM.getRelocationModel() == Reloc::PIC_)
221           O << "-\"L" << getFunctionNumber() << "$pb\"";
222         if (Subtarget.isDarwin())
223           O << ')';
224         else
225           O << "@ha";
226       }
227     }
228     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
229       if (MI->getOperand(OpNo).isImmediate()) {
230         printS16ImmOperand(MI, OpNo);
231       } else {
232         if (Subtarget.isDarwin()) O << "lo16(";
233         printOp(MI->getOperand(OpNo));
234         if (TM.getRelocationModel() == Reloc::PIC_)
235           O << "-\"L" << getFunctionNumber() << "$pb\"";
236         if (Subtarget.isDarwin())
237           O << ')';
238         else
239           O << "@l";
240       }
241     }
242     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
243       unsigned CCReg = MI->getOperand(OpNo).getReg();
244       unsigned RegNo = enumRegToMachineReg(CCReg);
245       O << (0x80 >> RegNo);
246     }
247     // The new addressing mode printers.
248     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
249       printSymbolLo(MI, OpNo);
250       O << '(';
251       if (MI->getOperand(OpNo+1).isRegister() && 
252           MI->getOperand(OpNo+1).getReg() == PPC::R0)
253         O << "0";
254       else
255         printOperand(MI, OpNo+1);
256       O << ')';
257     }
258     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
259       if (MI->getOperand(OpNo).isImmediate())
260         printS16X4ImmOperand(MI, OpNo);
261       else 
262         printSymbolLo(MI, OpNo);
263       O << '(';
264       if (MI->getOperand(OpNo+1).isRegister() && 
265           MI->getOperand(OpNo+1).getReg() == PPC::R0)
266         O << "0";
267       else
268         printOperand(MI, OpNo+1);
269       O << ')';
270     }
271     
272     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
273       // When used as the base register, r0 reads constant zero rather than
274       // the value contained in the register.  For this reason, the darwin
275       // assembler requires that we print r0 as 0 (no r) when used as the base.
276       const MachineOperand &MO = MI->getOperand(OpNo);
277       printRegister(MO, true);
278       O << ", ";
279       printOperand(MI, OpNo+1);
280     }
281     
282     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
283                                const char *Modifier);
284     
285     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
286     virtual bool doFinalization(Module &M) = 0;
287
288     virtual void EmitExternalGlobal(const GlobalVariable *GV);
289   };
290
291   /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
292   struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
293
294     DwarfWriter DW;
295
296     LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
297                     const TargetAsmInfo *T)
298       : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
299     }
300
301     virtual const char *getPassName() const {
302       return "Linux PPC Assembly Printer";
303     }
304
305     bool runOnMachineFunction(MachineFunction &F);
306     bool doInitialization(Module &M);
307     bool doFinalization(Module &M);
308     
309     void getAnalysisUsage(AnalysisUsage &AU) const {
310       AU.setPreservesAll();
311       AU.addRequired<MachineModuleInfo>();
312       PPCAsmPrinter::getAnalysisUsage(AU);
313     }
314
315     /// getSectionForFunction - Return the section that we should emit the
316     /// specified function body into.
317     virtual std::string getSectionForFunction(const Function &F) const;
318   };
319
320   /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
321   /// X
322   struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
323   
324     DwarfWriter DW;
325
326     DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
327                      const TargetAsmInfo *T)
328       : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
329     }
330
331     virtual const char *getPassName() const {
332       return "Darwin PPC Assembly Printer";
333     }
334     
335     bool runOnMachineFunction(MachineFunction &F);
336     bool doInitialization(Module &M);
337     bool doFinalization(Module &M);
338     
339     void getAnalysisUsage(AnalysisUsage &AU) const {
340       AU.setPreservesAll();
341       AU.addRequired<MachineModuleInfo>();
342       PPCAsmPrinter::getAnalysisUsage(AU);
343     }
344
345     /// getSectionForFunction - Return the section that we should emit the
346     /// specified function body into.
347     virtual std::string getSectionForFunction(const Function &F) const;
348   };
349 } // end of anonymous namespace
350
351 // Include the auto-generated portion of the assembly writer
352 #include "PPCGenAsmWriter.inc"
353
354 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
355   switch (MO.getType()) {
356   case MachineOperand::MO_Immediate:
357     cerr << "printOp() does not handle immediate values\n";
358     abort();
359     return;
360
361   case MachineOperand::MO_MachineBasicBlock:
362     printBasicBlockLabel(MO.getMachineBasicBlock());
363     return;
364   case MachineOperand::MO_JumpTableIndex:
365     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
366       << '_' << MO.getJumpTableIndex();
367     // FIXME: PIC relocation model
368     return;
369   case MachineOperand::MO_ConstantPoolIndex:
370     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
371       << '_' << MO.getConstantPoolIndex();
372     return;
373   case MachineOperand::MO_ExternalSymbol:
374     // Computing the address of an external symbol, not calling it.
375     if (TM.getRelocationModel() != Reloc::Static) {
376       std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
377       GVStubs.insert(Name);
378       O << "L" << Name << "$non_lazy_ptr";
379       return;
380     }
381     O << TAI->getGlobalPrefix() << MO.getSymbolName();
382     return;
383   case MachineOperand::MO_GlobalAddress: {
384     // Computing the address of a global symbol, not calling it.
385     GlobalValue *GV = MO.getGlobal();
386     std::string Name = Mang->getValueName(GV);
387
388     // External or weakly linked global variables need non-lazily-resolved stubs
389     if (TM.getRelocationModel() != Reloc::Static) {
390       if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
391             GV->hasLinkOnceLinkage()))) {
392         GVStubs.insert(Name);
393         O << "L" << Name << "$non_lazy_ptr";
394         return;
395       }
396     }
397     O << Name;
398     
399     if (GV->hasExternalWeakLinkage())
400       ExtWeakSymbols.insert(GV);
401     return;
402   }
403
404   default:
405     O << "<unknown operand type: " << MO.getType() << ">";
406     return;
407   }
408 }
409
410 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
411 ///
412 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
413   std::string Name = getGlobalLinkName(GV);
414   if (TM.getRelocationModel() != Reloc::Static) {
415     GVStubs.insert(Name);
416     O << "L" << Name << "$non_lazy_ptr";
417     return;
418   }
419   O << Name;
420 }
421
422 /// PrintAsmOperand - Print out an operand for an inline asm expression.
423 ///
424 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
425                                     unsigned AsmVariant, 
426                                     const char *ExtraCode) {
427   // Does this asm operand have a single letter operand modifier?
428   if (ExtraCode && ExtraCode[0]) {
429     if (ExtraCode[1] != 0) return true; // Unknown modifier.
430     
431     switch (ExtraCode[0]) {
432     default: return true;  // Unknown modifier.
433     case 'c': // Don't print "$" before a global var name or constant.
434       // PPC never has a prefix.
435       printOperand(MI, OpNo);
436       return false;
437     case 'L': // Write second word of DImode reference.  
438       // Verify that this operand has two consecutive registers.
439       if (!MI->getOperand(OpNo).isRegister() ||
440           OpNo+1 == MI->getNumOperands() ||
441           !MI->getOperand(OpNo+1).isRegister())
442         return true;
443       ++OpNo;   // Return the high-part.
444       break;
445     case 'I':
446       // Write 'i' if an integer constant, otherwise nothing.  Used to print
447       // addi vs add, etc.
448       if (MI->getOperand(OpNo).isImm())
449         O << "i";
450       return false;
451     }
452   }
453   
454   printOperand(MI, OpNo);
455   return false;
456 }
457
458 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
459                                           unsigned AsmVariant, 
460                                           const char *ExtraCode) {
461   if (ExtraCode && ExtraCode[0])
462     return true; // Unknown modifier.
463   if (MI->getOperand(OpNo).isRegister())
464     printMemRegReg(MI, OpNo);
465   else
466     printMemRegImm(MI, OpNo);
467   return false;
468 }
469
470 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
471                                           const char *Modifier) {
472   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
473   unsigned Code = MI->getOperand(OpNo).getImm();
474   if (!strcmp(Modifier, "cc")) {
475     switch ((PPC::Predicate)Code) {
476     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
477     case PPC::PRED_LT: O << "lt"; return;
478     case PPC::PRED_LE: O << "le"; return;
479     case PPC::PRED_EQ: O << "eq"; return;
480     case PPC::PRED_GE: O << "ge"; return;
481     case PPC::PRED_GT: O << "gt"; return;
482     case PPC::PRED_NE: O << "ne"; return;
483     case PPC::PRED_UN: O << "un"; return;
484     case PPC::PRED_NU: O << "nu"; return;
485     }
486       
487   } else {
488     assert(!strcmp(Modifier, "reg") &&
489            "Need to specify 'cc' or 'reg' as predicate op modifier!");
490     // Don't print the register for 'always'.
491     if (Code == PPC::PRED_ALWAYS) return;
492     printOperand(MI, OpNo+1);
493   }
494 }
495
496
497 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
498 /// the current output stream.
499 ///
500 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
501   ++EmittedInsts;
502
503   // Check for slwi/srwi mnemonics.
504   if (MI->getOpcode() == PPC::RLWINM) {
505     bool FoundMnemonic = false;
506     unsigned char SH = MI->getOperand(2).getImmedValue();
507     unsigned char MB = MI->getOperand(3).getImmedValue();
508     unsigned char ME = MI->getOperand(4).getImmedValue();
509     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
510       O << "slwi "; FoundMnemonic = true;
511     }
512     if (SH <= 31 && MB == (32-SH) && ME == 31) {
513       O << "srwi "; FoundMnemonic = true;
514       SH = 32-SH;
515     }
516     if (FoundMnemonic) {
517       printOperand(MI, 0);
518       O << ", ";
519       printOperand(MI, 1);
520       O << ", " << (unsigned int)SH << "\n";
521       return;
522     }
523   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
524     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
525       O << "mr ";
526       printOperand(MI, 0);
527       O << ", ";
528       printOperand(MI, 1);
529       O << "\n";
530       return;
531     }
532   } else if (MI->getOpcode() == PPC::RLDICR) {
533     unsigned char SH = MI->getOperand(2).getImmedValue();
534     unsigned char ME = MI->getOperand(3).getImmedValue();
535     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
536     if (63-SH == ME) {
537       O << "sldi ";
538       printOperand(MI, 0);
539       O << ", ";
540       printOperand(MI, 1);
541       O << ", " << (unsigned int)SH << "\n";
542       return;
543     }
544   }
545
546   if (printInstruction(MI))
547     return; // Printer was automatically generated
548
549   assert(0 && "Unhandled instruction in asm writer!");
550   abort();
551   return;
552 }
553
554 /// runOnMachineFunction - This uses the printMachineInstruction()
555 /// method to print assembly for each instruction.
556 ///
557 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
558   DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
559
560   SetupMachineFunction(MF);
561   O << "\n\n";
562   
563   // Print out constants referenced by the function
564   EmitConstantPool(MF.getConstantPool());
565
566   // Print out labels for the function.
567   const Function *F = MF.getFunction();
568   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
569   
570   switch (F->getLinkage()) {
571   default: assert(0 && "Unknown linkage type!");
572   case Function::InternalLinkage:  // Symbols default to internal.
573     break;
574   case Function::ExternalLinkage:
575     O << "\t.global\t" << CurrentFnName << '\n'
576       << "\t.type\t" << CurrentFnName << ", @function\n";
577     break;
578   case Function::WeakLinkage:
579   case Function::LinkOnceLinkage:
580     O << "\t.global\t" << CurrentFnName << '\n';
581     O << "\t.weak\t" << CurrentFnName << '\n';
582     break;
583   }
584   
585   if (F->hasHiddenVisibility())
586     if (const char *Directive = TAI->getHiddenDirective())
587       O << Directive << CurrentFnName << "\n";
588   
589   EmitAlignment(2, F);
590   O << CurrentFnName << ":\n";
591
592   // Emit pre-function debug information.
593   DW.BeginFunction(&MF);
594
595   // Print out code for the function.
596   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
597        I != E; ++I) {
598     // Print a label for the basic block.
599     if (I != MF.begin()) {
600       printBasicBlockLabel(I, true);
601       O << '\n';
602     }
603     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
604          II != E; ++II) {
605       // Print the assembly for the instruction.
606       O << "\t";
607       printMachineInstruction(II);
608     }
609   }
610
611   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
612
613   // Print out jump tables referenced by the function.
614   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
615   
616   // Emit post-function debug information.
617   DW.EndFunction();
618   
619   // We didn't modify anything.
620   return false;
621 }
622
623 bool LinuxAsmPrinter::doInitialization(Module &M) {
624   AsmPrinter::doInitialization(M);
625   
626   // GNU as handles section names wrapped in quotes
627   Mang->setUseQuotes(true);
628
629   SwitchToTextSection(TAI->getTextSection());
630   
631   // Emit initial debug information.
632   DW.BeginModule(&M);
633   return false;
634 }
635
636 bool LinuxAsmPrinter::doFinalization(Module &M) {
637   const TargetData *TD = TM.getTargetData();
638
639   // Print out module-level global variables here.
640   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
641        I != E; ++I) {
642     if (!I->hasInitializer()) continue;   // External global require no code
643     
644     // Check to see if this is a special global used by LLVM, if so, emit it.
645     if (EmitSpecialLLVMGlobal(I))
646       continue;
647
648     std::string name = Mang->getValueName(I);
649
650     if (I->hasHiddenVisibility())
651       if (const char *Directive = TAI->getHiddenDirective())
652         O << Directive << name << "\n";
653     
654     Constant *C = I->getInitializer();
655     unsigned Size = TD->getTypeSize(C->getType());
656     unsigned Align = TD->getPreferredAlignmentLog(I);
657
658     if (C->isNullValue() && /* FIXME: Verify correct */
659         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
660          I->hasLinkOnceLinkage() ||
661          (I->hasExternalLinkage() && !I->hasSection()))) {
662       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
663       if (I->hasExternalLinkage()) {
664         O << "\t.global " << name << '\n';
665         O << "\t.type " << name << ", @object\n";
666         //O << "\t.zerofill __DATA, __common, " << name << ", "
667         //  << Size << ", " << Align;
668       } else if (I->hasInternalLinkage()) {
669         SwitchToDataSection("\t.data", I);
670         O << TAI->getLCOMMDirective() << name << "," << Size;
671       } else {
672         SwitchToDataSection("\t.data", I);
673         O << ".comm " << name << "," << Size;
674       }
675       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
676     } else {
677       switch (I->getLinkage()) {
678       case GlobalValue::LinkOnceLinkage:
679       case GlobalValue::WeakLinkage:
680         O << "\t.global " << name << '\n'
681           << "\t.type " << name << ", @object\n"
682           << "\t.weak " << name << '\n';
683         SwitchToDataSection("\t.data", I);
684         break;
685       case GlobalValue::AppendingLinkage:
686         // FIXME: appending linkage variables should go into a section of
687         // their name or something.  For now, just emit them as external.
688       case GlobalValue::ExternalLinkage:
689         // If external or appending, declare as a global symbol
690         O << "\t.global " << name << "\n"
691           << "\t.type " << name << ", @object\n";
692         // FALL THROUGH
693       case GlobalValue::InternalLinkage:
694         if (I->isConstant()) {
695           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
696           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
697             SwitchToDataSection(TAI->getCStringSection(), I);
698             break;
699           }
700         }
701
702         // FIXME: special handling for ".ctors" & ".dtors" sections
703         if (I->hasSection() &&
704             (I->getSection() == ".ctors" ||
705              I->getSection() == ".dtors")) {
706           std::string SectionName = ".section " + I->getSection()
707                                                 + ",\"aw\",@progbits";
708           SwitchToDataSection(SectionName.c_str());
709         } else {
710           if (I->isConstant() && TAI->getReadOnlySection())
711             SwitchToDataSection(TAI->getReadOnlySection(), I);
712           else
713             SwitchToDataSection(TAI->getDataSection(), I);
714         }
715         break;
716       default:
717         cerr << "Unknown linkage type!";
718         abort();
719       }
720
721       EmitAlignment(Align, I);
722       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
723         << I->getName() << "'\n";
724
725       // If the initializer is a extern weak symbol, remember to emit the weak
726       // reference!
727       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
728         if (GV->hasExternalWeakLinkage())
729           ExtWeakSymbols.insert(GV);
730
731       EmitGlobalConstant(C);
732       O << '\n';
733     }
734   }
735
736   // TODO
737
738   // Emit initial debug information.
739   DW.EndModule();
740
741   AsmPrinter::doFinalization(M);
742   return false; // success
743 }
744
745 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
746   switch (F.getLinkage()) {
747   default: assert(0 && "Unknown linkage type!");
748   case Function::ExternalLinkage:
749   case Function::InternalLinkage: return TAI->getTextSection();
750   case Function::WeakLinkage:
751   case Function::LinkOnceLinkage:
752     return ".text";
753   }
754 }
755
756 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
757   switch (F.getLinkage()) {
758   default: assert(0 && "Unknown linkage type!");
759   case Function::ExternalLinkage:
760   case Function::InternalLinkage: return TAI->getTextSection();
761   case Function::WeakLinkage:
762   case Function::LinkOnceLinkage:
763     return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
764   }
765 }
766
767 /// runOnMachineFunction - This uses the printMachineInstruction()
768 /// method to print assembly for each instruction.
769 ///
770 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
771   DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
772
773   SetupMachineFunction(MF);
774   O << "\n\n";
775   
776   // Print out constants referenced by the function
777   EmitConstantPool(MF.getConstantPool());
778
779   // Print out labels for the function.
780   const Function *F = MF.getFunction();
781   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
782   
783   switch (F->getLinkage()) {
784   default: assert(0 && "Unknown linkage type!");
785   case Function::InternalLinkage:  // Symbols default to internal.
786     break;
787   case Function::ExternalLinkage:
788     O << "\t.globl\t" << CurrentFnName << "\n";
789     break;
790   case Function::WeakLinkage:
791   case Function::LinkOnceLinkage:
792     O << "\t.globl\t" << CurrentFnName << "\n";
793     O << "\t.weak_definition\t" << CurrentFnName << "\n";
794     break;
795   }
796   
797   if (F->hasHiddenVisibility())
798     if (const char *Directive = TAI->getHiddenDirective())
799       O << Directive << CurrentFnName << "\n";
800   
801   EmitAlignment(4, F);
802   O << CurrentFnName << ":\n";
803
804   // Emit pre-function debug information.
805   DW.BeginFunction(&MF);
806
807   // Print out code for the function.
808   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
809        I != E; ++I) {
810     // Print a label for the basic block.
811     if (I != MF.begin()) {
812       printBasicBlockLabel(I, true);
813       O << '\n';
814     }
815     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
816          II != E; ++II) {
817       // Print the assembly for the instruction.
818       O << "\t";
819       printMachineInstruction(II);
820     }
821   }
822
823   // Print out jump tables referenced by the function.
824   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
825   
826   // Emit post-function debug information.
827   DW.EndFunction();
828   
829   // We didn't modify anything.
830   return false;
831 }
832
833
834 bool DarwinAsmPrinter::doInitialization(Module &M) {
835   static const char *CPUDirectives[] = {
836     "ppc",
837     "ppc601",
838     "ppc602",
839     "ppc603",
840     "ppc7400",
841     "ppc750",
842     "ppc970",
843     "ppc64"
844   };
845
846   unsigned Directive = Subtarget.getDarwinDirective();
847   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
848     Directive = PPC::DIR_970;
849   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
850     Directive = PPC::DIR_7400;
851   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
852     Directive = PPC::DIR_64;
853   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
854   O << "\t.machine " << CPUDirectives[Directive] << "\n";
855      
856   AsmPrinter::doInitialization(M);
857   
858   // Darwin wants symbols to be quoted if they have complex names.
859   Mang->setUseQuotes(true);
860   
861   // Prime text sections so they are adjacent.  This reduces the likelihood a
862   // large data or debug section causes a branch to exceed 16M limit.
863   SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
864                       "pure_instructions");
865   if (TM.getRelocationModel() == Reloc::PIC_) {
866     SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
867                           "pure_instructions,32");
868   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
869     SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
870                         "pure_instructions,16");
871   }
872   SwitchToTextSection(TAI->getTextSection());
873   
874   // Emit initial debug information.
875   DW.BeginModule(&M);
876   return false;
877 }
878
879 bool DarwinAsmPrinter::doFinalization(Module &M) {
880   const TargetData *TD = TM.getTargetData();
881
882   // Print out module-level global variables here.
883   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
884        I != E; ++I) {
885     if (!I->hasInitializer()) continue;   // External global require no code
886     
887     // Check to see if this is a special global used by LLVM, if so, emit it.
888     if (EmitSpecialLLVMGlobal(I)) {
889       if (TM.getRelocationModel() == Reloc::Static) {
890         if (I->getName() == "llvm.global_ctors")
891           O << ".reference .constructors_used\n";
892         else if (I->getName() == "llvm.global_dtors")
893           O << ".reference .destructors_used\n";
894       }
895       continue;
896     }
897     
898     std::string name = Mang->getValueName(I);
899     
900     if (I->hasHiddenVisibility())
901       if (const char *Directive = TAI->getHiddenDirective())
902         O << Directive << name << "\n";
903     
904     Constant *C = I->getInitializer();
905     const Type *Type = C->getType();
906     unsigned Size = TD->getTypeSize(Type);
907     unsigned Align = TD->getPreferredAlignmentLog(I);
908
909     if (C->isNullValue() && /* FIXME: Verify correct */
910         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
911          I->hasLinkOnceLinkage() ||
912          (I->hasExternalLinkage() && !I->hasSection()))) {
913       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
914       if (I->hasExternalLinkage()) {
915         O << "\t.globl " << name << '\n';
916         O << "\t.zerofill __DATA, __common, " << name << ", "
917           << Size << ", " << Align;
918       } else if (I->hasInternalLinkage()) {
919         SwitchToDataSection("\t.data", I);
920         O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
921       } else {
922         SwitchToDataSection("\t.data", I);
923         O << ".comm " << name << "," << Size;
924       }
925       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
926     } else {
927       switch (I->getLinkage()) {
928       case GlobalValue::LinkOnceLinkage:
929       case GlobalValue::WeakLinkage:
930         O << "\t.globl " << name << '\n'
931           << "\t.weak_definition " << name << '\n';
932         SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
933         break;
934       case GlobalValue::AppendingLinkage:
935         // FIXME: appending linkage variables should go into a section of
936         // their name or something.  For now, just emit them as external.
937       case GlobalValue::ExternalLinkage:
938         // If external or appending, declare as a global symbol
939         O << "\t.globl " << name << "\n";
940         // FALL THROUGH
941       case GlobalValue::InternalLinkage:
942         if (I->isConstant()) {
943           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
944           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
945             SwitchToDataSection(TAI->getCStringSection(), I);
946             break;
947           }
948         }
949
950         if (!I->isConstant())
951           SwitchToDataSection(TAI->getDataSection(), I);
952         else {
953           // Read-only data.
954           bool HasReloc = C->ContainsRelocations();
955           if (HasReloc &&
956               TM.getRelocationModel() != Reloc::Static)
957             SwitchToDataSection("\t.const_data\n");
958           else if (!HasReloc && Size == 4 &&
959                    TAI->getFourByteConstantSection())
960             SwitchToDataSection(TAI->getFourByteConstantSection(), I);
961           else if (!HasReloc && Size == 8 &&
962                    TAI->getEightByteConstantSection())
963             SwitchToDataSection(TAI->getEightByteConstantSection(), I);
964           else if (!HasReloc && Size == 16 &&
965                    TAI->getSixteenByteConstantSection())
966             SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
967           else if (TAI->getReadOnlySection())
968             SwitchToDataSection(TAI->getReadOnlySection(), I);
969           else
970             SwitchToDataSection(TAI->getDataSection(), I);
971         }
972         break;
973       default:
974         cerr << "Unknown linkage type!";
975         abort();
976       }
977
978       EmitAlignment(Align, I);
979       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
980         << I->getName() << "'\n";
981
982       // If the initializer is a extern weak symbol, remember to emit the weak
983       // reference!
984       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
985         if (GV->hasExternalWeakLinkage())
986           ExtWeakSymbols.insert(GV);
987
988       EmitGlobalConstant(C);
989       O << '\n';
990     }
991   }
992
993   bool isPPC64 = TD->getPointerSizeInBits() == 64;
994
995   // Output stubs for dynamically-linked functions
996   if (TM.getRelocationModel() == Reloc::PIC_) {
997     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
998          i != e; ++i) {
999       SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
1000                           "pure_instructions,32");
1001       EmitAlignment(4);
1002       O << "L" << *i << "$stub:\n";
1003       O << "\t.indirect_symbol " << *i << "\n";
1004       O << "\tmflr r0\n";
1005       O << "\tbcl 20,31,L0$" << *i << "\n";
1006       O << "L0$" << *i << ":\n";
1007       O << "\tmflr r11\n";
1008       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
1009       O << "\tmtlr r0\n";
1010       if (isPPC64)
1011         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1012       else
1013         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
1014       O << "\tmtctr r12\n";
1015       O << "\tbctr\n";
1016       SwitchToDataSection(".lazy_symbol_pointer");
1017       O << "L" << *i << "$lazy_ptr:\n";
1018       O << "\t.indirect_symbol " << *i << "\n";
1019       if (isPPC64)
1020         O << "\t.quad dyld_stub_binding_helper\n";
1021       else
1022         O << "\t.long dyld_stub_binding_helper\n";
1023     }
1024   } else {
1025     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
1026          i != e; ++i) {
1027       SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
1028                           "pure_instructions,16");
1029       EmitAlignment(4);
1030       O << "L" << *i << "$stub:\n";
1031       O << "\t.indirect_symbol " << *i << "\n";
1032       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
1033       if (isPPC64)
1034         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1035       else
1036         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1037       O << "\tmtctr r12\n";
1038       O << "\tbctr\n";
1039       SwitchToDataSection(".lazy_symbol_pointer");
1040       O << "L" << *i << "$lazy_ptr:\n";
1041       O << "\t.indirect_symbol " << *i << "\n";
1042       if (isPPC64)
1043         O << "\t.quad dyld_stub_binding_helper\n";
1044       else
1045         O << "\t.long dyld_stub_binding_helper\n";
1046     }
1047   }
1048
1049   O << "\n";
1050
1051   // Output stubs for external and common global variables.
1052   if (GVStubs.begin() != GVStubs.end()) {
1053     SwitchToDataSection(".non_lazy_symbol_pointer");
1054     for (std::set<std::string>::iterator I = GVStubs.begin(),
1055          E = GVStubs.end(); I != E; ++I) {
1056       O << "L" << *I << "$non_lazy_ptr:\n";
1057       O << "\t.indirect_symbol " << *I << "\n";
1058       if (isPPC64)
1059         O << "\t.quad\t0\n";
1060       else
1061         O << "\t.long\t0\n";
1062         
1063     }
1064   }
1065
1066   // Emit initial debug information.
1067   DW.EndModule();
1068
1069   // Funny Darwin hack: This flag tells the linker that no global symbols
1070   // contain code that falls through to other global symbols (e.g. the obvious
1071   // implementation of multiple entry points).  If this doesn't occur, the
1072   // linker can safely perform dead code stripping.  Since LLVM never generates
1073   // code that does this, it is always safe to set.
1074   O << "\t.subsections_via_symbols\n";
1075
1076   AsmPrinter::doFinalization(M);
1077   return false; // success
1078 }
1079
1080
1081
1082 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1083 /// for a MachineFunction to the given output stream, in a format that the
1084 /// Darwin assembler can deal with.
1085 ///
1086 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1087                                             PPCTargetMachine &tm) {
1088   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1089
1090   if (Subtarget->isDarwin()) {
1091     return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1092   } else {
1093     return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1094   }
1095 }
1096