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