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