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