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