1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
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"
16 #include "MipsAsmPrinter.h"
18 #include "MipsInstrInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsMCInstLower.h"
21 #include "InstPrinter/MipsInstPrinter.h"
22 #include "llvm/BasicBlock.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Target/Mangler.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Analysis/DebugInfo.h"
46 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
48 raw_svector_ostream OS(Str);
50 if (MI->isDebugValue()) {
51 PrintDebugValueComment(MI, OS);
55 MipsMCInstLower MCInstLowering(Mang, *MF, *this);
57 MCInstLowering.Lower(MI, TmpInst0);
58 unsigned Opc = MI->getOpcode();
60 // Convert aligned loads/stores to their unaligned counterparts.
61 // FIXME: expand other unaligned memory accesses too.
62 if ((Opc == Mips::LW || Opc == Mips::SW) && !MI->memoperands_empty() &&
63 (*MI->memoperands_begin())->getAlignment() < 4) {
65 Directive.setOpcode(Mips::MACRO);
66 OutStreamer.EmitInstruction(Directive);
67 TmpInst0.setOpcode(Opc == Mips::LW ? Mips::ULW : Mips::USW);
68 OutStreamer.EmitInstruction(TmpInst0);
69 Directive.setOpcode(Mips::NOMACRO);
70 OutStreamer.EmitInstruction(Directive);
74 OutStreamer.EmitInstruction(TmpInst0);
77 //===----------------------------------------------------------------------===//
79 // Mips Asm Directives
81 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
82 // Describe the stack frame.
84 // -- Mask directives "(f)mask bitmask, offset"
85 // Tells the assembler which registers are saved and where.
86 // bitmask - contain a little endian bitset indicating which registers are
87 // saved on function prologue (e.g. with a 0x80000000 mask, the
88 // assembler knows the register 31 (RA) is saved at prologue.
89 // offset - the position before stack pointer subtraction indicating where
90 // the first saved register on prologue is located. (e.g. with a
92 // Consider the following function prologue:
95 // .mask 0xc0000000,-8
96 // addiu $sp, $sp, -48
100 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
101 // 30 (FP) are saved at prologue. As the save order on prologue is from
102 // left to right, RA is saved first. A -8 offset means that after the
103 // stack pointer subtration, the first register in the mask (RA) will be
104 // saved at address 48-8=40.
106 //===----------------------------------------------------------------------===//
108 //===----------------------------------------------------------------------===//
110 //===----------------------------------------------------------------------===//
112 // Create a bitmask with all callee saved registers for CPU or Floating Point
113 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
114 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
115 // CPU and FPU Saved Registers Bitmasks
116 unsigned CPUBitmask = 0, FPUBitmask = 0;
117 int CPUTopSavedRegOff, FPUTopSavedRegOff;
119 // Set the CPU and FPU Bitmasks
120 const MachineFrameInfo *MFI = MF->getFrameInfo();
121 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
122 // size of stack area to which FP callee-saved regs are saved.
123 unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
124 unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
125 unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
126 bool HasAFGR64Reg = false;
127 unsigned CSFPRegsSize = 0;
128 unsigned i, e = CSI.size();
131 for (i = 0; i != e; ++i) {
132 unsigned Reg = CSI[i].getReg();
133 if (Mips::CPURegsRegisterClass->contains(Reg))
136 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
137 if (Mips::AFGR64RegisterClass->contains(Reg)) {
138 FPUBitmask |= (3 << RegNum);
139 CSFPRegsSize += AFGR64RegSize;
144 FPUBitmask |= (1 << RegNum);
145 CSFPRegsSize += FGR32RegSize;
149 for (; i != e; ++i) {
150 unsigned Reg = CSI[i].getReg();
151 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
152 CPUBitmask |= (1 << RegNum);
155 // FP Regs are saved right below where the virtual frame pointer points to.
156 FPUTopSavedRegOff = FPUBitmask ?
157 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
159 // CPU Regs are saved below FP Regs.
160 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
163 O << "\t.mask \t"; printHex32(CPUBitmask, O);
164 O << ',' << CPUTopSavedRegOff << '\n';
167 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
168 O << "," << FPUTopSavedRegOff << '\n';
171 // Print a 32 bit hex number with all numbers.
172 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
174 for (int i = 7; i >= 0; i--)
175 O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
178 //===----------------------------------------------------------------------===//
179 // Frame and Set directives
180 //===----------------------------------------------------------------------===//
183 void MipsAsmPrinter::emitFrameDirective() {
184 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
186 unsigned stackReg = RI.getFrameRegister(*MF);
187 unsigned returnReg = RI.getRARegister();
188 unsigned stackSize = MF->getFrameInfo()->getStackSize();
190 OutStreamer.EmitRawText("\t.frame\t$" +
191 Twine(LowercaseString(MipsInstPrinter::getRegisterName(stackReg))) +
192 "," + Twine(stackSize) + ",$" +
193 Twine(LowercaseString(MipsInstPrinter::getRegisterName(returnReg))));
196 /// Emit Set directives.
197 const char *MipsAsmPrinter::getCurrentABIString() const {
198 switch (Subtarget->getTargetABI()) {
199 case MipsSubtarget::O32: return "abi32";
200 case MipsSubtarget::O64: return "abiO64";
201 case MipsSubtarget::N32: return "abiN32";
202 case MipsSubtarget::N64: return "abi64";
203 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
207 llvm_unreachable("Unknown Mips ABI");
211 void MipsAsmPrinter::EmitFunctionEntryLabel() {
212 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
213 OutStreamer.EmitLabel(CurrentFnSym);
216 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
217 /// the first basic block in the function.
218 void MipsAsmPrinter::EmitFunctionBodyStart() {
219 emitFrameDirective();
221 SmallString<128> Str;
222 raw_svector_ostream OS(Str);
223 printSavedRegsBitmask(OS);
224 OutStreamer.EmitRawText(OS.str());
227 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
228 /// the last basic block in the function.
229 void MipsAsmPrinter::EmitFunctionBodyEnd() {
230 // There are instruction for this macros, but they must
231 // always be at the function end, and we can't emit and
232 // break with BB logic.
233 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
234 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
235 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
239 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
240 /// exactly one predecessor and the control transfer mechanism between
241 /// the predecessor and this block is a fall-through.
242 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
244 // The predecessor has to be immediately before this block.
245 const MachineBasicBlock *Pred = *MBB->pred_begin();
247 // If the predecessor is a switch statement, assume a jump table
248 // implementation, so it is not a fall through.
249 if (const BasicBlock *bb = Pred->getBasicBlock())
250 if (isa<SwitchInst>(bb->getTerminator()))
253 // If this is a landing pad, it isn't a fall through. If it has no preds,
254 // then nothing falls through to it.
255 if (MBB->isLandingPad() || MBB->pred_empty())
258 // If there isn't exactly one predecessor, it can't be a fall through.
259 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
262 if (PI2 != MBB->pred_end())
265 // The predecessor has to be immediately before this block.
266 if (!Pred->isLayoutSuccessor(MBB))
269 // If the block is completely empty, then it definitely does fall through.
273 // Otherwise, check the last instruction.
274 // Check if the last terminator is an unconditional branch.
275 MachineBasicBlock::const_iterator I = Pred->end();
276 while (I != Pred->begin() && !(--I)->getDesc().isTerminator()) ;
278 return !I->getDesc().isBarrier();
281 // Print out an operand for an inline asm expression.
282 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
283 unsigned AsmVariant,const char *ExtraCode,
285 // Does this asm operand have a single letter operand modifier?
286 if (ExtraCode && ExtraCode[0])
287 return true; // Unknown modifier.
289 printOperand(MI, OpNo, O);
293 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
294 unsigned OpNum, unsigned AsmVariant,
295 const char *ExtraCode,
297 if (ExtraCode && ExtraCode[0])
298 return true; // Unknown modifier.
300 const MachineOperand &MO = MI->getOperand(OpNum);
301 assert(MO.isReg() && "unexpected inline asm memory operand");
302 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
306 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
308 const MachineOperand &MO = MI->getOperand(opNum);
311 if (MO.getTargetFlags())
314 switch(MO.getTargetFlags()) {
315 case MipsII::MO_GPREL: O << "%gp_rel("; break;
316 case MipsII::MO_GOT_CALL: O << "%call16("; break;
317 case MipsII::MO_GOT: O << "%got("; break;
318 case MipsII::MO_ABS_HI: O << "%hi("; break;
319 case MipsII::MO_ABS_LO: O << "%lo("; break;
320 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
321 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
322 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
323 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
326 switch (MO.getType()) {
327 case MachineOperand::MO_Register:
329 << LowercaseString(MipsInstPrinter::getRegisterName(MO.getReg()));
332 case MachineOperand::MO_Immediate:
336 case MachineOperand::MO_MachineBasicBlock:
337 O << *MO.getMBB()->getSymbol();
340 case MachineOperand::MO_GlobalAddress:
341 O << *Mang->getSymbol(MO.getGlobal());
344 case MachineOperand::MO_BlockAddress: {
345 MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
350 case MachineOperand::MO_ExternalSymbol:
351 O << *GetExternalSymbolSymbol(MO.getSymbolName());
354 case MachineOperand::MO_JumpTableIndex:
355 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
356 << '_' << MO.getIndex();
359 case MachineOperand::MO_ConstantPoolIndex:
360 O << MAI->getPrivateGlobalPrefix() << "CPI"
361 << getFunctionNumber() << "_" << MO.getIndex();
363 O << "+" << MO.getOffset();
367 llvm_unreachable("<unknown operand type>");
370 if (closeP) O << ")";
373 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
375 const MachineOperand &MO = MI->getOperand(opNum);
377 O << (unsigned short int)MO.getImm();
379 printOperand(MI, opNum, O);
382 void MipsAsmPrinter::
383 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
384 // Load/Store memory operands -- imm($reg)
385 // If PIC target the target is loaded as the
386 // pattern lw $25,%call16($28)
387 printOperand(MI, opNum+1, O);
389 printOperand(MI, opNum, O);
393 void MipsAsmPrinter::
394 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
395 // when using stack locations for not load/store instructions
396 // print the same way as all normal 3 operand instructions.
397 printOperand(MI, opNum, O);
399 printOperand(MI, opNum+1, O);
403 void MipsAsmPrinter::
404 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
405 const char *Modifier) {
406 const MachineOperand& MO = MI->getOperand(opNum);
407 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
410 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
411 // FIXME: Use SwitchSection.
413 // Tell the assembler which ABI we are using
414 OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
416 // TODO: handle O64 ABI
417 if (Subtarget->isABI_EABI()) {
418 if (Subtarget->isGP32bit())
419 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
421 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
424 // return to previous section
425 OutStreamer.EmitRawText(StringRef("\t.previous"));
429 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
430 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
431 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
432 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
433 "Unexpected MachineOperand types");
434 return MachineLocation(MI->getOperand(0).getReg(),
435 MI->getOperand(1).getImm());
438 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
443 // Force static initialization.
444 extern "C" void LLVMInitializeMipsAsmPrinter() {
445 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
446 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);