Print comments with ;
[oota-llvm.git] / lib / Target / PowerPC / PPCAsmPrinter.cpp
1 //===-- PPC32AsmPrinter.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 "PowerPC.h"
21 #include "PPC32TargetMachine.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "Support/CommandLine.h"
33 #include "Support/Debug.h"
34 #include "Support/Statistic.h"
35 #include "Support/StringExtras.h"
36 #include <set>
37 using namespace llvm;
38
39 namespace {
40   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
41
42   struct PPC32AsmPrinter : public AsmPrinter {
43     std::set<std::string> FnStubs, GVStubs, LinkOnceStubs;
44     std::set<std::string> Strings;
45
46     PPC32AsmPrinter(std::ostream &O, TargetMachine &TM)
47       : AsmPrinter(O, TM), LabelNumber(0) {
48       CommentChar = ";";
49       GlobalPrefix = "_";
50       ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
51       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
52     }
53
54     /// Unique incrementer for label values for referencing Global values.
55     ///
56     unsigned LabelNumber;
57   
58     virtual const char *getPassName() const {
59       return "PPC32 Assembly Printer";
60     }
61
62     PPC32TargetMachine &getTM() {
63       return static_cast<PPC32TargetMachine&>(TM);
64     }
65
66     /// printInstruction - This method is automatically generated by tablegen
67     /// from the instruction set description.  This method returns true if the
68     /// machine instruction was sufficiently described to print it, otherwise it
69     /// returns false.
70     bool printInstruction(const MachineInstr *MI);
71
72     void printMachineInstruction(const MachineInstr *MI);
73     void printOp(const MachineOperand &MO, bool LoadAddrOp = false);
74     void printImmOp(const MachineOperand &MO, unsigned ArgType);
75
76     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
77       const MachineOperand &MO = MI->getOperand(OpNo);
78       if (MO.getType() == MachineOperand::MO_MachineRegister) {
79         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
80         O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
81       } else if (MO.isImmediate()) {
82         O << MO.getImmedValue();
83       } else {
84         printOp(MO);
85       }
86     }
87
88     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
89                             MVT::ValueType VT) {
90       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
91     }
92
93     void printConstantPool(MachineConstantPool *MCP);
94     bool runOnMachineFunction(MachineFunction &F);    
95     bool doFinalization(Module &M);
96   };
97 } // end of anonymous namespace
98
99 /// createPPC32AsmPrinterPass - Returns a pass that prints the PPC
100 /// assembly code for a MachineFunction to the given output stream,
101 /// using the given target machine description.  This should work
102 /// regardless of whether the function is in SSA form or not.
103 ///
104 FunctionPass *llvm::createPPC32AsmPrinter(std::ostream &o, TargetMachine &tm) {
105   return new PPC32AsmPrinter(o, tm);
106 }
107
108 // Include the auto-generated portion of the assembly writer
109 #include "PowerPCGenAsmWriter.inc"
110
111 /// printConstantPool - Print to the current output stream assembly
112 /// representations of the constants in the constant pool MCP. This is
113 /// used to print out constants which have been "spilled to memory" by
114 /// the code generator.
115 ///
116 void PPC32AsmPrinter::printConstantPool(MachineConstantPool *MCP) {
117   const std::vector<Constant*> &CP = MCP->getConstants();
118   const TargetData &TD = TM.getTargetData();
119  
120   if (CP.empty()) return;
121
122   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
123     O << "\t.const\n";
124     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
125       << "\n";
126     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t;"
127       << *CP[i] << "\n";
128     emitGlobalConstant(CP[i]);
129   }
130 }
131
132 /// runOnMachineFunction - This uses the printMachineInstruction()
133 /// method to print assembly for each instruction.
134 ///
135 bool PPC32AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
136   setupMachineFunction(MF);
137   O << "\n\n";
138
139   // Print out constants referenced by the function
140   printConstantPool(MF.getConstantPool());
141
142   // Print out labels for the function.
143   O << "\t.text\n"; 
144   O << "\t.globl\t" << CurrentFnName << "\n";
145   O << "\t.align 2\n";
146   O << CurrentFnName << ":\n";
147
148   // Print out code for the function.
149   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
150        I != E; ++I) {
151     // Print a label for the basic block.
152     O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t; "
153       << I->getBasicBlock()->getName() << "\n";
154     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
155       II != E; ++II) {
156       // Print the assembly for the instruction.
157       O << "\t";
158       printMachineInstruction(II);
159     }
160   }
161   ++LabelNumber;
162
163   // We didn't modify anything.
164   return false;
165 }
166
167 void PPC32AsmPrinter::printOp(const MachineOperand &MO,
168                               bool LoadAddrOp /* = false */) {
169   const MRegisterInfo &RI = *TM.getRegisterInfo();
170   int new_symbol;
171   
172   switch (MO.getType()) {
173   case MachineOperand::MO_VirtualRegister:
174     if (Value *V = MO.getVRegValueOrNull()) {
175       O << "<" << V->getName() << ">";
176       return;
177     }
178     // FALLTHROUGH
179   case MachineOperand::MO_MachineRegister:
180   case MachineOperand::MO_CCRegister:
181     O << LowercaseString(RI.get(MO.getReg()).Name);
182     return;
183
184   case MachineOperand::MO_SignExtendedImmed:
185   case MachineOperand::MO_UnextendedImmed:
186     std::cerr << "printOp() does not handle immediate values\n";
187     abort();
188     return;
189
190   case MachineOperand::MO_PCRelativeDisp:
191     std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
192     abort();
193     return;
194     
195   case MachineOperand::MO_MachineBasicBlock: {
196     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
197     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
198       << "_" << MBBOp->getNumber() << "\t; "
199       << MBBOp->getBasicBlock()->getName();
200     return;
201   }
202
203   case MachineOperand::MO_ConstantPoolIndex:
204     O << ".CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
205     return;
206
207   case MachineOperand::MO_ExternalSymbol:
208     O << MO.getSymbolName();
209     return;
210
211   case MachineOperand::MO_GlobalAddress: {
212     GlobalValue *GV = MO.getGlobal();
213     std::string Name = Mang->getValueName(GV);
214
215     // Dynamically-resolved functions need a stub for the function.  Be
216     // wary however not to output $stub for external functions whose addresses
217     // are taken.  Those should be emitted as $non_lazy_ptr below.
218     Function *F = dyn_cast<Function>(GV);
219     if (F && F->isExternal() && !LoadAddrOp &&
220         getTM().CalledFunctions.count(F)) {
221       FnStubs.insert(Name);
222       O << "L" << Name << "$stub";
223       return;
224     }
225     
226     // External global variables need a non-lazily-resolved stub
227     if (GV->isExternal() && getTM().AddressTaken.count(GV)) {
228       GVStubs.insert(Name);
229       O << "L" << Name << "$non_lazy_ptr";
230       return;
231     }
232     
233     if (F && LoadAddrOp && getTM().AddressTaken.count(GV)) {
234       LinkOnceStubs.insert(Name);
235       O << "L" << Name << "$non_lazy_ptr";
236       return;
237     }
238             
239     O << Mang->getValueName(GV);
240     return;
241   }
242     
243   default:
244     O << "<unknown operand type: " << MO.getType() << ">";
245     return;
246   }
247 }
248
249 void PPC32AsmPrinter::printImmOp(const MachineOperand &MO, unsigned ArgType) {
250   int Imm = MO.getImmedValue();
251   if (ArgType == PPCII::Simm16 || ArgType == PPCII::Disimm16) {
252     O << (short)Imm;
253   } else {
254     O << Imm;
255   }
256 }
257
258 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
259 /// the current output stream.
260 ///
261 void PPC32AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
262   ++EmittedInsts;
263   if (printInstruction(MI))
264     return; // Printer was automatically generated
265     
266   unsigned Opcode = MI->getOpcode();
267   const TargetInstrInfo &TII = *TM.getInstrInfo();
268   const TargetInstrDescriptor &Desc = TII.get(Opcode);
269   unsigned i;
270
271   unsigned ArgCount = MI->getNumOperands();
272   unsigned ArgType[] = {
273     (Desc.TSFlags >> PPCII::Arg0TypeShift) & PPCII::ArgTypeMask,
274     (Desc.TSFlags >> PPCII::Arg1TypeShift) & PPCII::ArgTypeMask,
275     (Desc.TSFlags >> PPCII::Arg2TypeShift) & PPCII::ArgTypeMask,
276     (Desc.TSFlags >> PPCII::Arg3TypeShift) & PPCII::ArgTypeMask,
277     (Desc.TSFlags >> PPCII::Arg4TypeShift) & PPCII::ArgTypeMask
278   };
279   assert(((Desc.TSFlags & PPCII::VMX) == 0) &&
280          "Instruction requires VMX support");
281   assert(((Desc.TSFlags & PPCII::PPC64) == 0) &&
282          "Instruction requires 64 bit support");
283
284   // CALLpcrel and CALLindirect are handled specially here to print only the
285   // appropriate number of args that the assembler expects.  This is because
286   // may have many arguments appended to record the uses of registers that are
287   // holding arguments to the called function.
288   if (Opcode == PPC::COND_BRANCH) {
289     std::cerr << "Error: untranslated conditional branch psuedo instruction!\n";
290     abort();
291   } else if (Opcode == PPC::IMPLICIT_DEF) {
292     O << "; IMPLICIT DEF ";
293     printOp(MI->getOperand(0));
294     O << "\n";
295     return;
296   } else if (Opcode == PPC::CALLpcrel) {
297     O << TII.getName(Opcode) << " ";
298     printOp(MI->getOperand(0));
299     O << "\n";
300     return;
301   } else if (Opcode == PPC::CALLindirect) {
302     O << TII.getName(Opcode) << " ";
303     printImmOp(MI->getOperand(0), ArgType[0]);
304     O << ", ";
305     printImmOp(MI->getOperand(1), ArgType[0]);
306     O << "\n";
307     return;
308   } else if (Opcode == PPC::MovePCtoLR) {
309     // FIXME: should probably be converted to cout.width and cout.fill
310     O << "bl \"L0000" << LabelNumber << "$pb\"\n";
311     O << "\"L0000" << LabelNumber << "$pb\":\n";
312     O << "\tmflr ";
313     printOp(MI->getOperand(0));
314     O << "\n";
315     return;
316   }
317
318   O << TII.getName(Opcode) << " ";
319   if (Opcode == PPC::LOADLoDirect || Opcode == PPC::LOADLoIndirect) {
320     printOp(MI->getOperand(0));
321     O << ", lo16(";
322     printOp(MI->getOperand(2), true /* LoadAddrOp */);
323     O << "-\"L0000" << LabelNumber << "$pb\")";
324     O << "(";
325     if (MI->getOperand(1).getReg() == PPC::R0)
326       O << "0";
327     else
328       printOp(MI->getOperand(1));
329     O << ")\n";
330   } else if (Opcode == PPC::LOADHiAddr) {
331     printOp(MI->getOperand(0));
332     O << ", ";
333     if (MI->getOperand(1).getReg() == PPC::R0)
334       O << "0";
335     else
336       printOp(MI->getOperand(1));
337     O << ", ha16(" ;
338     printOp(MI->getOperand(2), true /* LoadAddrOp */);
339      O << "-\"L0000" << LabelNumber << "$pb\")\n";
340   } else if (ArgCount == 3 && ArgType[1] == PPCII::Disimm16) {
341     printOp(MI->getOperand(0));
342     O << ", ";
343     printImmOp(MI->getOperand(1), ArgType[1]);
344     O << "(";
345     if (MI->getOperand(2).hasAllocatedReg() &&
346         MI->getOperand(2).getReg() == PPC::R0)
347       O << "0";
348     else
349       printOp(MI->getOperand(2));
350     O << ")\n";
351   } else {
352     for (i = 0; i < ArgCount; ++i) {
353       // addi and friends
354       if (i == 1 && ArgCount == 3 && ArgType[2] == PPCII::Simm16 &&
355           MI->getOperand(1).hasAllocatedReg() && 
356           MI->getOperand(1).getReg() == PPC::R0) {
357         O << "0";
358       // for long branch support, bc $+8
359       } else if (i == 1 && ArgCount == 2 && MI->getOperand(1).isImmediate() &&
360                  TII.isBranch(MI->getOpcode())) {
361         O << "$+8";
362         assert(8 == MI->getOperand(i).getImmedValue()
363           && "branch off PC not to pc+8?");
364         //printOp(MI->getOperand(i));
365       } else if (MI->getOperand(i).isImmediate()) {
366         printImmOp(MI->getOperand(i), ArgType[i]);
367       } else {
368         printOp(MI->getOperand(i));
369       }
370       if (ArgCount - 1 == i)
371         O << "\n";
372       else
373         O << ", ";
374     }
375   }
376   return;
377 }
378
379 // SwitchSection - Switch to the specified section of the executable if we are
380 // not already in it!
381 //
382 static void SwitchSection(std::ostream &OS, std::string &CurSection,
383                           const char *NewSection) {
384   if (CurSection != NewSection) {
385     CurSection = NewSection;
386     if (!CurSection.empty())
387       OS << "\t" << NewSection << "\n";
388   }
389 }
390
391 bool PPC32AsmPrinter::doFinalization(Module &M) {
392   const TargetData &TD = TM.getTargetData();
393   std::string CurSection;
394
395   // Print out module-level global variables here.
396   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
397     if (I->hasInitializer()) {   // External global require no code
398       O << "\n\n";
399       std::string name = Mang->getValueName(I);
400       Constant *C = I->getInitializer();
401       unsigned Size = TD.getTypeSize(C->getType());
402       unsigned Align = TD.getTypeAlignment(C->getType());
403
404       if (C->isNullValue() && /* FIXME: Verify correct */
405           (I->hasInternalLinkage() || I->hasWeakLinkage())) {
406         SwitchSection(O, CurSection, ".data");
407         if (I->hasInternalLinkage())
408           O << ".lcomm " << name << "," << TD.getTypeSize(C->getType())
409             << "," << (unsigned)TD.getTypeAlignment(C->getType());
410         else 
411           O << ".comm " << name << "," << TD.getTypeSize(C->getType());
412         O << "\t\t; ";
413         WriteAsOperand(O, I, true, true, &M);
414         O << "\n";
415       } else {
416         switch (I->getLinkage()) {
417         case GlobalValue::LinkOnceLinkage:
418           O << ".section __TEXT,__textcoal_nt,coalesced,no_toc\n"
419             << ".weak_definition " << name << '\n'
420             << ".private_extern " << name << '\n'
421             << ".section __DATA,__datacoal_nt,coalesced,no_toc\n";
422           LinkOnceStubs.insert(name);
423           break;  
424         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
425           // Nonnull linkonce -> weak
426           O << "\t.weak " << name << "\n";
427           SwitchSection(O, CurSection, "");
428           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
429           break;
430         case GlobalValue::AppendingLinkage:
431           // FIXME: appending linkage variables should go into a section of
432           // their name or something.  For now, just emit them as external.
433         case GlobalValue::ExternalLinkage:
434           // If external or appending, declare as a global symbol
435           O << "\t.globl " << name << "\n";
436           // FALL THROUGH
437         case GlobalValue::InternalLinkage:
438           SwitchSection(O, CurSection, ".data");
439           break;
440         }
441
442         O << "\t.align " << Align << "\n";
443         O << name << ":\t\t\t\t; ";
444         WriteAsOperand(O, I, true, true, &M);
445         O << " = ";
446         WriteAsOperand(O, C, false, false, &M);
447         O << "\n";
448         emitGlobalConstant(C);
449       }
450     }
451
452   // Output stubs for dynamically-linked functions
453   for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end(); 
454        i != e; ++i)
455   {
456     O << ".data\n";
457     O << ".section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n";
458     O << "\t.align 2\n";
459     O << "L" << *i << "$stub:\n";
460     O << "\t.indirect_symbol " << *i << "\n";
461     O << "\tmflr r0\n";
462     O << "\tbcl 20,31,L0$" << *i << "\n";
463     O << "L0$" << *i << ":\n";
464     O << "\tmflr r11\n";
465     O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
466     O << "\tmtlr r0\n";
467     O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
468     O << "\tmtctr r12\n";
469     O << "\tbctr\n";
470     O << ".data\n";
471     O << ".lazy_symbol_pointer\n";
472     O << "L" << *i << "$lazy_ptr:\n";
473     O << "\t.indirect_symbol " << *i << "\n";
474     O << "\t.long dyld_stub_binding_helper\n";
475   }
476
477   O << "\n";
478
479   // Output stubs for external global variables
480   if (GVStubs.begin() != GVStubs.end())
481     O << ".data\n.non_lazy_symbol_pointer\n";
482   for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end(); 
483        i != e; ++i) {
484     O << "L" << *i << "$non_lazy_ptr:\n";
485     O << "\t.indirect_symbol " << *i << "\n";
486     O << "\t.long\t0\n";
487   }
488   
489   // Output stubs for link-once variables
490   if (LinkOnceStubs.begin() != LinkOnceStubs.end())
491     O << ".data\n.align 2\n";
492   for (std::set<std::string>::iterator i = LinkOnceStubs.begin(), 
493          e = LinkOnceStubs.end(); i != e; ++i) {
494     O << "L" << *i << "$non_lazy_ptr:\n"
495       << "\t.long\t" << *i << '\n';
496   }
497   
498   AsmPrinter::doFinalization(M);
499   return false; // success
500 }