O64 will not be supported.
[oota-llvm.git] / lib / Target / Mips / MipsAsmPrinter.cpp
1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mips-asm-printer"
16 #include "MipsAsmPrinter.h"
17 #include "Mips.h"
18 #include "MipsInstrInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsMCInstLower.h"
21 #include "MipsMCSymbolRefExpr.h"
22 #include "InstPrinter/MipsInstPrinter.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Target/Mangler.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Analysis/DebugInfo.h"
44
45 using namespace llvm;
46
47 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
48   SmallString<128> Str;
49   raw_svector_ostream OS(Str);
50
51   if (MI->isDebugValue()) {
52     PrintDebugValueComment(MI, OS);
53     return;
54   }
55
56   MipsMCInstLower MCInstLowering(Mang, *MF, *this);
57   unsigned Opc = MI->getOpcode();
58   MCInst TmpInst0;
59   MCInstLowering.Lower(MI, TmpInst0);
60   
61   // Convert aligned loads/stores to their unaligned counterparts.
62   if (!MI->memoperands_empty()) {
63     unsigned NaturalAlignment, UnalignedOpc;
64     
65     switch (Opc) {
66     case Mips::LW:  NaturalAlignment = 4; UnalignedOpc = Mips::ULW;  break;
67     case Mips::SW:  NaturalAlignment = 4; UnalignedOpc = Mips::USW;  break;
68     case Mips::LH:  NaturalAlignment = 2; UnalignedOpc = Mips::ULH;  break;
69     case Mips::LHu: NaturalAlignment = 2; UnalignedOpc = Mips::ULHu; break;
70     case Mips::SH:  NaturalAlignment = 2; UnalignedOpc = Mips::USH;  break;
71     default:        NaturalAlignment = 0;
72     }
73
74     if ((*MI->memoperands_begin())->getAlignment() < NaturalAlignment) {
75       MCInst Directive;
76       Directive.setOpcode(Mips::MACRO);
77       OutStreamer.EmitInstruction(Directive);
78       TmpInst0.setOpcode(UnalignedOpc);
79       OutStreamer.EmitInstruction(TmpInst0);
80       Directive.setOpcode(Mips::NOMACRO);
81       OutStreamer.EmitInstruction(Directive);
82       return;
83     }
84   }
85
86   OutStreamer.EmitInstruction(TmpInst0);
87 }
88
89 //===----------------------------------------------------------------------===//
90 //
91 //  Mips Asm Directives
92 //
93 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
94 //  Describe the stack frame.
95 //
96 //  -- Mask directives "(f)mask  bitmask, offset"
97 //  Tells the assembler which registers are saved and where.
98 //  bitmask - contain a little endian bitset indicating which registers are
99 //            saved on function prologue (e.g. with a 0x80000000 mask, the
100 //            assembler knows the register 31 (RA) is saved at prologue.
101 //  offset  - the position before stack pointer subtraction indicating where
102 //            the first saved register on prologue is located. (e.g. with a
103 //
104 //  Consider the following function prologue:
105 //
106 //    .frame  $fp,48,$ra
107 //    .mask   0xc0000000,-8
108 //       addiu $sp, $sp, -48
109 //       sw $ra, 40($sp)
110 //       sw $fp, 36($sp)
111 //
112 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
113 //    30 (FP) are saved at prologue. As the save order on prologue is from
114 //    left to right, RA is saved first. A -8 offset means that after the
115 //    stack pointer subtration, the first register in the mask (RA) will be
116 //    saved at address 48-8=40.
117 //
118 //===----------------------------------------------------------------------===//
119
120 //===----------------------------------------------------------------------===//
121 // Mask directives
122 //===----------------------------------------------------------------------===//
123
124 // Create a bitmask with all callee saved registers for CPU or Floating Point
125 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
126 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
127   // CPU and FPU Saved Registers Bitmasks
128   unsigned CPUBitmask = 0, FPUBitmask = 0;
129   int CPUTopSavedRegOff, FPUTopSavedRegOff;
130
131   // Set the CPU and FPU Bitmasks
132   const MachineFrameInfo *MFI = MF->getFrameInfo();
133   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
134   // size of stack area to which FP callee-saved regs are saved.
135   unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
136   unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
137   unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
138   bool HasAFGR64Reg = false;
139   unsigned CSFPRegsSize = 0;
140   unsigned i, e = CSI.size();
141
142   // Set FPU Bitmask.
143   for (i = 0; i != e; ++i) {
144     unsigned Reg = CSI[i].getReg();
145     if (Mips::CPURegsRegisterClass->contains(Reg))
146       break;
147
148     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
149     if (Mips::AFGR64RegisterClass->contains(Reg)) {
150       FPUBitmask |= (3 << RegNum);
151       CSFPRegsSize += AFGR64RegSize;
152       HasAFGR64Reg = true;
153       continue;
154     }
155
156     FPUBitmask |= (1 << RegNum);
157     CSFPRegsSize += FGR32RegSize;
158   }
159
160   // Set CPU Bitmask.
161   for (; i != e; ++i) {
162     unsigned Reg = CSI[i].getReg();
163     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
164     CPUBitmask |= (1 << RegNum);
165   }
166
167   // FP Regs are saved right below where the virtual frame pointer points to.
168   FPUTopSavedRegOff = FPUBitmask ?
169     (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
170
171   // CPU Regs are saved below FP Regs.
172   CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
173
174   // Print CPUBitmask
175   O << "\t.mask \t"; printHex32(CPUBitmask, O);
176   O << ',' << CPUTopSavedRegOff << '\n';
177
178   // Print FPUBitmask
179   O << "\t.fmask\t"; printHex32(FPUBitmask, O);
180   O << "," << FPUTopSavedRegOff << '\n';
181 }
182
183 // Print a 32 bit hex number with all numbers.
184 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
185   O << "0x";
186   for (int i = 7; i >= 0; i--)
187     O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
188 }
189
190 //===----------------------------------------------------------------------===//
191 // Frame and Set directives
192 //===----------------------------------------------------------------------===//
193
194 /// Frame Directive
195 void MipsAsmPrinter::emitFrameDirective() {
196   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
197
198   unsigned stackReg  = RI.getFrameRegister(*MF);
199   unsigned returnReg = RI.getRARegister();
200   unsigned stackSize = MF->getFrameInfo()->getStackSize();
201
202   OutStreamer.EmitRawText("\t.frame\t$" +
203            Twine(LowercaseString(MipsInstPrinter::getRegisterName(stackReg))) +
204            "," + Twine(stackSize) + ",$" +
205            Twine(LowercaseString(MipsInstPrinter::getRegisterName(returnReg))));
206 }
207
208 /// Emit Set directives.
209 const char *MipsAsmPrinter::getCurrentABIString() const {
210   switch (Subtarget->getTargetABI()) {
211   case MipsSubtarget::O32:  return "abi32";
212   case MipsSubtarget::N32:  return "abiN32";
213   case MipsSubtarget::N64:  return "abi64";
214   case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
215   default: break;
216   }
217
218   llvm_unreachable("Unknown Mips ABI");
219   return NULL;
220 }
221
222 void MipsAsmPrinter::EmitFunctionEntryLabel() {
223   OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
224   OutStreamer.EmitLabel(CurrentFnSym);
225 }
226
227 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
228 /// the first basic block in the function.
229 void MipsAsmPrinter::EmitFunctionBodyStart() {
230   emitFrameDirective();
231
232   SmallString<128> Str;
233   raw_svector_ostream OS(Str);
234   printSavedRegsBitmask(OS);
235   OutStreamer.EmitRawText(OS.str());
236 }
237
238 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
239 /// the last basic block in the function.
240 void MipsAsmPrinter::EmitFunctionBodyEnd() {
241   // There are instruction for this macros, but they must
242   // always be at the function end, and we can't emit and
243   // break with BB logic.
244   OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
245   OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
246   OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
247 }
248
249
250 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
251 /// exactly one predecessor and the control transfer mechanism between
252 /// the predecessor and this block is a fall-through.
253 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
254                                                        MBB) const {
255   // The predecessor has to be immediately before this block.
256   const MachineBasicBlock *Pred = *MBB->pred_begin();
257
258   // If the predecessor is a switch statement, assume a jump table
259   // implementation, so it is not a fall through.
260   if (const BasicBlock *bb = Pred->getBasicBlock())
261     if (isa<SwitchInst>(bb->getTerminator()))
262       return false;
263
264   // If this is a landing pad, it isn't a fall through.  If it has no preds,
265   // then nothing falls through to it.
266   if (MBB->isLandingPad() || MBB->pred_empty())
267     return false;
268
269   // If there isn't exactly one predecessor, it can't be a fall through.
270   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
271   ++PI2;
272  
273   if (PI2 != MBB->pred_end())
274     return false;  
275
276   // The predecessor has to be immediately before this block.
277   if (!Pred->isLayoutSuccessor(MBB))
278     return false;
279    
280   // If the block is completely empty, then it definitely does fall through.
281   if (Pred->empty())
282     return true;
283   
284   // Otherwise, check the last instruction.
285   // Check if the last terminator is an unconditional branch.
286   MachineBasicBlock::const_iterator I = Pred->end();
287   while (I != Pred->begin() && !(--I)->getDesc().isTerminator()) ;
288
289   return !I->getDesc().isBarrier();
290 }
291
292 // Print out an operand for an inline asm expression.
293 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
294                                      unsigned AsmVariant,const char *ExtraCode,
295                                      raw_ostream &O) {
296   // Does this asm operand have a single letter operand modifier?
297   if (ExtraCode && ExtraCode[0])
298     return true; // Unknown modifier.
299
300   printOperand(MI, OpNo, O);
301   return false;
302 }
303
304 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
305                                            unsigned OpNum, unsigned AsmVariant,
306                                            const char *ExtraCode,
307                                            raw_ostream &O) {
308   if (ExtraCode && ExtraCode[0])
309      return true; // Unknown modifier.
310    
311   const MachineOperand &MO = MI->getOperand(OpNum);
312   assert(MO.isReg() && "unexpected inline asm memory operand");
313   O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
314   return false;
315 }
316
317 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
318                                   raw_ostream &O) {
319   const MachineOperand &MO = MI->getOperand(opNum);
320   bool closeP = false;
321
322   if (MO.getTargetFlags())
323     closeP = true;
324
325   switch(MO.getTargetFlags()) {
326   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
327   case MipsII::MO_GOT_CALL: O << "%call16("; break;
328   case MipsII::MO_GOT:      O << "%got(";    break;
329   case MipsII::MO_ABS_HI:   O << "%hi(";     break;
330   case MipsII::MO_ABS_LO:   O << "%lo(";     break;
331   case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
332   case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
333   case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
334   case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
335   }
336
337   switch (MO.getType()) {
338     case MachineOperand::MO_Register:
339       O << '$'
340         << LowercaseString(MipsInstPrinter::getRegisterName(MO.getReg()));
341       break;
342
343     case MachineOperand::MO_Immediate:
344       O << MO.getImm();
345       break;
346
347     case MachineOperand::MO_MachineBasicBlock:
348       O << *MO.getMBB()->getSymbol();
349       return;
350
351     case MachineOperand::MO_GlobalAddress:
352       O << *Mang->getSymbol(MO.getGlobal());
353       break;
354
355     case MachineOperand::MO_BlockAddress: {
356       MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
357       O << BA->getName();
358       break;
359     }
360
361     case MachineOperand::MO_ExternalSymbol:
362       O << *GetExternalSymbolSymbol(MO.getSymbolName());
363       break;
364
365     case MachineOperand::MO_JumpTableIndex:
366       O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
367         << '_' << MO.getIndex();
368       break;
369
370     case MachineOperand::MO_ConstantPoolIndex:
371       O << MAI->getPrivateGlobalPrefix() << "CPI"
372         << getFunctionNumber() << "_" << MO.getIndex();
373       if (MO.getOffset())
374         O << "+" << MO.getOffset();
375       break;
376
377     default:
378       llvm_unreachable("<unknown operand type>");
379   }
380
381   if (closeP) O << ")";
382 }
383
384 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
385                                       raw_ostream &O) {
386   const MachineOperand &MO = MI->getOperand(opNum);
387   if (MO.isImm())
388     O << (unsigned short int)MO.getImm();
389   else
390     printOperand(MI, opNum, O);
391 }
392
393 void MipsAsmPrinter::
394 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
395   // Load/Store memory operands -- imm($reg)
396   // If PIC target the target is loaded as the
397   // pattern lw $25,%call16($28)
398   printOperand(MI, opNum+1, O);
399   O << "(";
400   printOperand(MI, opNum, O);
401   O << ")";
402 }
403
404 void MipsAsmPrinter::
405 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
406   // when using stack locations for not load/store instructions
407   // print the same way as all normal 3 operand instructions.
408   printOperand(MI, opNum, O);
409   O << ", ";
410   printOperand(MI, opNum+1, O);
411   return;
412 }
413
414 void MipsAsmPrinter::
415 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
416                 const char *Modifier) {
417   const MachineOperand& MO = MI->getOperand(opNum);
418   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
419 }
420
421 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
422   // FIXME: Use SwitchSection.
423
424   // Tell the assembler which ABI we are using
425   OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
426
427   // TODO: handle O64 ABI
428   if (Subtarget->isABI_EABI()) {
429     if (Subtarget->isGP32bit())
430       OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
431     else
432       OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
433   }
434
435   // return to previous section
436   OutStreamer.EmitRawText(StringRef("\t.previous"));
437 }
438
439 MachineLocation
440 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
441   // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
442   assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
443   assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
444          "Unexpected MachineOperand types");
445   return MachineLocation(MI->getOperand(0).getReg(),
446                          MI->getOperand(1).getImm());
447 }
448
449 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
450                                            raw_ostream &OS) {
451   // TODO: implement
452 }
453
454 // Force static initialization.
455 extern "C" void LLVMInitializeMipsAsmPrinter() {
456   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
457   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
458 }