1 //===-- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-asm-printer"
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"
46 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
47 MipsFI = MF.getInfo<MipsFunctionInfo>();
48 AsmPrinter::runOnMachineFunction(MF);
52 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
53 if (MI->isDebugValue()) {
55 raw_svector_ostream OS(Str);
57 PrintDebugValueComment(MI, OS);
61 MachineBasicBlock::const_instr_iterator I = MI;
62 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
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
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();
81 MCInstLowering.LowerLargeShift(I, TmpInst0, Shift - 32);
82 OutStreamer.EmitInstruction(TmpInst0);
87 // Double extract instruction is chosen by pos and size operands
89 assert(Subtarget->hasMips64() &&
90 "DEXT is a MIPS64 instruction");
93 MCInstLowering.LowerDEXT(I, TmpInst0);
94 OutStreamer.EmitInstruction(TmpInst0);
99 MCInstLowering.Lower(I++, TmpInst0);
100 OutStreamer.EmitInstruction(TmpInst0);
102 } while ((I != E) && I->isInsideBundle()); // Delay slot check
105 //===----------------------------------------------------------------------===//
107 // Mips Asm Directives
109 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
110 // Describe the stack frame.
112 // -- Mask directives "(f)mask bitmask, offset"
113 // Tells the assembler which registers are saved and where.
114 // bitmask - contain a little endian bitset indicating which registers are
115 // saved on function prologue (e.g. with a 0x80000000 mask, the
116 // assembler knows the register 31 (RA) is saved at prologue.
117 // offset - the position before stack pointer subtraction indicating where
118 // the first saved register on prologue is located. (e.g. with a
120 // Consider the following function prologue:
123 // .mask 0xc0000000,-8
124 // addiu $sp, $sp, -48
128 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
129 // 30 (FP) are saved at prologue. As the save order on prologue is from
130 // left to right, RA is saved first. A -8 offset means that after the
131 // stack pointer subtration, the first register in the mask (RA) will be
132 // saved at address 48-8=40.
134 //===----------------------------------------------------------------------===//
136 //===----------------------------------------------------------------------===//
138 //===----------------------------------------------------------------------===//
140 // Create a bitmask with all callee saved registers for CPU or Floating Point
141 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
142 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
143 // CPU and FPU Saved Registers Bitmasks
144 unsigned CPUBitmask = 0, FPUBitmask = 0;
145 int CPUTopSavedRegOff, FPUTopSavedRegOff;
147 // Set the CPU and FPU Bitmasks
148 const MachineFrameInfo *MFI = MF->getFrameInfo();
149 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
150 // size of stack area to which FP callee-saved regs are saved.
151 unsigned CPURegSize = Mips::CPURegsRegClass.getSize();
152 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
153 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
154 bool HasAFGR64Reg = false;
155 unsigned CSFPRegsSize = 0;
156 unsigned i, e = CSI.size();
159 for (i = 0; i != e; ++i) {
160 unsigned Reg = CSI[i].getReg();
161 if (Mips::CPURegsRegClass.contains(Reg))
164 unsigned RegNum = getMipsRegisterNumbering(Reg);
165 if (Mips::AFGR64RegClass.contains(Reg)) {
166 FPUBitmask |= (3 << RegNum);
167 CSFPRegsSize += AFGR64RegSize;
172 FPUBitmask |= (1 << RegNum);
173 CSFPRegsSize += FGR32RegSize;
177 for (; i != e; ++i) {
178 unsigned Reg = CSI[i].getReg();
179 unsigned RegNum = getMipsRegisterNumbering(Reg);
180 CPUBitmask |= (1 << RegNum);
183 // FP Regs are saved right below where the virtual frame pointer points to.
184 FPUTopSavedRegOff = FPUBitmask ?
185 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
187 // CPU Regs are saved below FP Regs.
188 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
191 O << "\t.mask \t"; printHex32(CPUBitmask, O);
192 O << ',' << CPUTopSavedRegOff << '\n';
195 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
196 O << "," << FPUTopSavedRegOff << '\n';
199 // Print a 32 bit hex number with all numbers.
200 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
202 for (int i = 7; i >= 0; i--)
203 O.write_hex((Value & (0xF << (i*4))) >> (i*4));
206 //===----------------------------------------------------------------------===//
207 // Frame and Set directives
208 //===----------------------------------------------------------------------===//
211 void MipsAsmPrinter::emitFrameDirective() {
212 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
214 unsigned stackReg = RI.getFrameRegister(*MF);
215 unsigned returnReg = RI.getRARegister();
216 unsigned stackSize = MF->getFrameInfo()->getStackSize();
218 if (OutStreamer.hasRawTextSupport())
219 OutStreamer.EmitRawText("\t.frame\t$" +
220 StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
221 "," + Twine(stackSize) + ",$" +
222 StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
225 /// Emit Set directives.
226 const char *MipsAsmPrinter::getCurrentABIString() const {
227 switch (Subtarget->getTargetABI()) {
228 case MipsSubtarget::O32: return "abi32";
229 case MipsSubtarget::N32: return "abiN32";
230 case MipsSubtarget::N64: return "abi64";
231 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
232 default: llvm_unreachable("Unknown Mips ABI");;
236 void MipsAsmPrinter::EmitFunctionEntryLabel() {
237 if (OutStreamer.hasRawTextSupport()) {
238 if (Subtarget->inMips16Mode())
239 OutStreamer.EmitRawText(StringRef("\t.set\tmips16"));
241 OutStreamer.EmitRawText(StringRef("\t.set\tnomips16"));
242 // leave out until FSF available gas has micromips changes
243 // OutStreamer.EmitRawText(StringRef("\t.set\tnomicromips"));
244 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
246 OutStreamer.EmitLabel(CurrentFnSym);
249 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
250 /// the first basic block in the function.
251 void MipsAsmPrinter::EmitFunctionBodyStart() {
252 MCInstLowering.Initialize(Mang, &MF->getContext());
254 emitFrameDirective();
256 if (OutStreamer.hasRawTextSupport()) {
257 SmallString<128> Str;
258 raw_svector_ostream OS(Str);
259 printSavedRegsBitmask(OS);
260 OutStreamer.EmitRawText(OS.str());
262 OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
263 OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
264 if (MipsFI->getEmitNOAT())
265 OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
269 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
270 /// the last basic block in the function.
271 void MipsAsmPrinter::EmitFunctionBodyEnd() {
272 // There are instruction for this macros, but they must
273 // always be at the function end, and we can't emit and
274 // break with BB logic.
275 if (OutStreamer.hasRawTextSupport()) {
276 if (MipsFI->getEmitNOAT())
277 OutStreamer.EmitRawText(StringRef("\t.set\tat"));
279 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
280 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
281 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
285 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
286 /// exactly one predecessor and the control transfer mechanism between
287 /// the predecessor and this block is a fall-through.
288 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
290 // The predecessor has to be immediately before this block.
291 const MachineBasicBlock *Pred = *MBB->pred_begin();
293 // If the predecessor is a switch statement, assume a jump table
294 // implementation, so it is not a fall through.
295 if (const BasicBlock *bb = Pred->getBasicBlock())
296 if (isa<SwitchInst>(bb->getTerminator()))
299 // If this is a landing pad, it isn't a fall through. If it has no preds,
300 // then nothing falls through to it.
301 if (MBB->isLandingPad() || MBB->pred_empty())
304 // If there isn't exactly one predecessor, it can't be a fall through.
305 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
308 if (PI2 != MBB->pred_end())
311 // The predecessor has to be immediately before this block.
312 if (!Pred->isLayoutSuccessor(MBB))
315 // If the block is completely empty, then it definitely does fall through.
319 // Otherwise, check the last instruction.
320 // Check if the last terminator is an unconditional branch.
321 MachineBasicBlock::const_iterator I = Pred->end();
322 while (I != Pred->begin() && !(--I)->isTerminator()) ;
324 return !I->isBarrier();
327 // Print out an operand for an inline asm expression.
328 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
329 unsigned AsmVariant,const char *ExtraCode,
331 // Does this asm operand have a single letter operand modifier?
332 if (ExtraCode && ExtraCode[0]) {
333 if (ExtraCode[1] != 0) return true; // Unknown modifier.
335 const MachineOperand &MO = MI->getOperand(OpNum);
336 switch (ExtraCode[0]) {
338 // See if this is a generic print operand
339 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
340 case 'X': // hex const int
341 if ((MO.getType()) != MachineOperand::MO_Immediate)
343 O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
345 case 'x': // hex const int (low 16 bits)
346 if ((MO.getType()) != MachineOperand::MO_Immediate)
348 O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
350 case 'd': // decimal const int
351 if ((MO.getType()) != MachineOperand::MO_Immediate)
355 case 'm': // decimal const int minus 1
356 if ((MO.getType()) != MachineOperand::MO_Immediate)
358 O << MO.getImm() - 1;
361 // $0 if zero, regular printing otherwise
362 if (MO.getType() != MachineOperand::MO_Immediate)
364 int64_t Val = MO.getImm();
371 case 'D': // Second part of a double word register operand
372 case 'L': // Low order register of a double word register operand
373 case 'M': // High order register of a double word register operand
377 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
378 if (!FlagsOP.isImm())
380 unsigned Flags = FlagsOP.getImm();
381 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
382 // Number of registers represented by this operand. We are looking
383 // for 2 for 32 bit mode and 1 for 64 bit mode.
385 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
386 unsigned Reg = MO.getReg();
387 O << '$' << MipsInstPrinter::getRegisterName(Reg);
393 unsigned RegOp = OpNum;
394 if (!Subtarget->isGP64bit()){
395 // Endianess reverses which register holds the high or low value
397 switch(ExtraCode[0]) {
399 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
402 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
404 case 'D': // Always the second part
407 if (RegOp >= MI->getNumOperands())
409 const MachineOperand &MO = MI->getOperand(RegOp);
412 unsigned Reg = MO.getReg();
413 O << '$' << MipsInstPrinter::getRegisterName(Reg);
420 printOperand(MI, OpNum, O);
424 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
425 unsigned OpNum, unsigned AsmVariant,
426 const char *ExtraCode,
428 if (ExtraCode && ExtraCode[0])
429 return true; // Unknown modifier.
431 const MachineOperand &MO = MI->getOperand(OpNum);
432 assert(MO.isReg() && "unexpected inline asm memory operand");
433 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
438 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
440 const MachineOperand &MO = MI->getOperand(opNum);
443 if (MO.getTargetFlags())
446 switch(MO.getTargetFlags()) {
447 case MipsII::MO_GPREL: O << "%gp_rel("; break;
448 case MipsII::MO_GOT_CALL: O << "%call16("; break;
449 case MipsII::MO_GOT: O << "%got("; break;
450 case MipsII::MO_ABS_HI: O << "%hi("; break;
451 case MipsII::MO_ABS_LO: O << "%lo("; break;
452 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
453 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
454 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
455 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
456 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
457 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
458 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
459 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
460 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
463 switch (MO.getType()) {
464 case MachineOperand::MO_Register:
466 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
469 case MachineOperand::MO_Immediate:
473 case MachineOperand::MO_MachineBasicBlock:
474 O << *MO.getMBB()->getSymbol();
477 case MachineOperand::MO_GlobalAddress:
478 O << *Mang->getSymbol(MO.getGlobal());
481 case MachineOperand::MO_BlockAddress: {
482 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
487 case MachineOperand::MO_ExternalSymbol:
488 O << *GetExternalSymbolSymbol(MO.getSymbolName());
491 case MachineOperand::MO_JumpTableIndex:
492 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
493 << '_' << MO.getIndex();
496 case MachineOperand::MO_ConstantPoolIndex:
497 O << MAI->getPrivateGlobalPrefix() << "CPI"
498 << getFunctionNumber() << "_" << MO.getIndex();
500 O << "+" << MO.getOffset();
504 llvm_unreachable("<unknown operand type>");
507 if (closeP) O << ")";
510 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
512 const MachineOperand &MO = MI->getOperand(opNum);
514 O << (unsigned short int)MO.getImm();
516 printOperand(MI, opNum, O);
519 void MipsAsmPrinter::
520 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
521 // Load/Store memory operands -- imm($reg)
522 // If PIC target the target is loaded as the
523 // pattern lw $25,%call16($28)
524 printOperand(MI, opNum+1, O);
526 printOperand(MI, opNum, O);
530 void MipsAsmPrinter::
531 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
532 // when using stack locations for not load/store instructions
533 // print the same way as all normal 3 operand instructions.
534 printOperand(MI, opNum, O);
536 printOperand(MI, opNum+1, O);
540 void MipsAsmPrinter::
541 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
542 const char *Modifier) {
543 const MachineOperand &MO = MI->getOperand(opNum);
544 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
547 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
548 // FIXME: Use SwitchSection.
550 // Tell the assembler which ABI we are using
551 if (OutStreamer.hasRawTextSupport())
552 OutStreamer.EmitRawText("\t.section .mdebug." +
553 Twine(getCurrentABIString()));
555 // TODO: handle O64 ABI
556 if (OutStreamer.hasRawTextSupport()) {
557 if (Subtarget->isABI_EABI()) {
558 if (Subtarget->isGP32bit())
559 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
561 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
565 // return to previous section
566 if (OutStreamer.hasRawTextSupport())
567 OutStreamer.EmitRawText(StringRef("\t.previous"));
571 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
572 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
573 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
574 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
575 "Unexpected MachineOperand types");
576 return MachineLocation(MI->getOperand(0).getReg(),
577 MI->getOperand(1).getImm());
580 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
585 // Force static initialization.
586 extern "C" void LLVMInitializeMipsAsmPrinter() {
587 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
588 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
589 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
590 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);