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