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