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 "MipsMCSymbolRefExpr.h"
22 #include "InstPrinter/MipsInstPrinter.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Target/Mangler.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Analysis/DebugInfo.h"
47 static bool isUnalignedLoadStore(unsigned Opc) {
48 return Opc == Mips::ULW || Opc == Mips::ULH || Opc == Mips::ULHu ||
49 Opc == Mips::USW || Opc == Mips::USH;
52 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
54 raw_svector_ostream OS(Str);
56 if (MI->isDebugValue()) {
57 PrintDebugValueComment(MI, OS);
61 MipsMCInstLower MCInstLowering(Mang, *MF, *this);
62 unsigned Opc = MI->getOpcode();
64 MCInstLowering.Lower(MI, TmpInst0);
66 // Enclose unaligned load or store with .macro & .nomacro directives.
67 if (isUnalignedLoadStore(Opc)) {
69 Directive.setOpcode(Mips::MACRO);
70 OutStreamer.EmitInstruction(Directive);
71 OutStreamer.EmitInstruction(TmpInst0);
72 Directive.setOpcode(Mips::NOMACRO);
73 OutStreamer.EmitInstruction(Directive);
77 OutStreamer.EmitInstruction(TmpInst0);
80 //===----------------------------------------------------------------------===//
82 // Mips Asm Directives
84 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
85 // Describe the stack frame.
87 // -- Mask directives "(f)mask bitmask, offset"
88 // Tells the assembler which registers are saved and where.
89 // bitmask - contain a little endian bitset indicating which registers are
90 // saved on function prologue (e.g. with a 0x80000000 mask, the
91 // assembler knows the register 31 (RA) is saved at prologue.
92 // offset - the position before stack pointer subtraction indicating where
93 // the first saved register on prologue is located. (e.g. with a
95 // Consider the following function prologue:
98 // .mask 0xc0000000,-8
99 // addiu $sp, $sp, -48
103 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
104 // 30 (FP) are saved at prologue. As the save order on prologue is from
105 // left to right, RA is saved first. A -8 offset means that after the
106 // stack pointer subtration, the first register in the mask (RA) will be
107 // saved at address 48-8=40.
109 //===----------------------------------------------------------------------===//
111 //===----------------------------------------------------------------------===//
113 //===----------------------------------------------------------------------===//
115 // Create a bitmask with all callee saved registers for CPU or Floating Point
116 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
117 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
118 // CPU and FPU Saved Registers Bitmasks
119 unsigned CPUBitmask = 0, FPUBitmask = 0;
120 int CPUTopSavedRegOff, FPUTopSavedRegOff;
122 // Set the CPU and FPU Bitmasks
123 const MachineFrameInfo *MFI = MF->getFrameInfo();
124 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
125 // size of stack area to which FP callee-saved regs are saved.
126 unsigned CPURegSize = Mips::CPURegsRegisterClass->getSize();
127 unsigned FGR32RegSize = Mips::FGR32RegisterClass->getSize();
128 unsigned AFGR64RegSize = Mips::AFGR64RegisterClass->getSize();
129 bool HasAFGR64Reg = false;
130 unsigned CSFPRegsSize = 0;
131 unsigned i, e = CSI.size();
134 for (i = 0; i != e; ++i) {
135 unsigned Reg = CSI[i].getReg();
136 if (Mips::CPURegsRegisterClass->contains(Reg))
139 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
140 if (Mips::AFGR64RegisterClass->contains(Reg)) {
141 FPUBitmask |= (3 << RegNum);
142 CSFPRegsSize += AFGR64RegSize;
147 FPUBitmask |= (1 << RegNum);
148 CSFPRegsSize += FGR32RegSize;
152 for (; i != e; ++i) {
153 unsigned Reg = CSI[i].getReg();
154 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(Reg);
155 CPUBitmask |= (1 << RegNum);
158 // FP Regs are saved right below where the virtual frame pointer points to.
159 FPUTopSavedRegOff = FPUBitmask ?
160 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
162 // CPU Regs are saved below FP Regs.
163 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
166 O << "\t.mask \t"; printHex32(CPUBitmask, O);
167 O << ',' << CPUTopSavedRegOff << '\n';
170 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
171 O << "," << FPUTopSavedRegOff << '\n';
174 // Print a 32 bit hex number with all numbers.
175 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
177 for (int i = 7; i >= 0; i--)
178 O << utohexstr((Value & (0xF << (i*4))) >> (i*4));
181 //===----------------------------------------------------------------------===//
182 // Frame and Set directives
183 //===----------------------------------------------------------------------===//
186 void MipsAsmPrinter::emitFrameDirective() {
187 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
189 unsigned stackReg = RI.getFrameRegister(*MF);
190 unsigned returnReg = RI.getRARegister();
191 unsigned stackSize = MF->getFrameInfo()->getStackSize();
193 OutStreamer.EmitRawText("\t.frame\t$" +
194 Twine(LowercaseString(MipsInstPrinter::getRegisterName(stackReg))) +
195 "," + Twine(stackSize) + ",$" +
196 Twine(LowercaseString(MipsInstPrinter::getRegisterName(returnReg))));
199 /// Emit Set directives.
200 const char *MipsAsmPrinter::getCurrentABIString() const {
201 switch (Subtarget->getTargetABI()) {
202 case MipsSubtarget::O32: return "abi32";
203 case MipsSubtarget::N32: return "abiN32";
204 case MipsSubtarget::N64: return "abi64";
205 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
209 llvm_unreachable("Unknown Mips ABI");
213 void MipsAsmPrinter::EmitFunctionEntryLabel() {
214 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
215 OutStreamer.EmitLabel(CurrentFnSym);
218 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
219 /// the first basic block in the function.
220 void MipsAsmPrinter::EmitFunctionBodyStart() {
221 emitFrameDirective();
223 SmallString<128> Str;
224 raw_svector_ostream OS(Str);
225 printSavedRegsBitmask(OS);
226 OutStreamer.EmitRawText(OS.str());
229 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
230 /// the last basic block in the function.
231 void MipsAsmPrinter::EmitFunctionBodyEnd() {
232 // There are instruction for this macros, but they must
233 // always be at the function end, and we can't emit and
234 // break with BB logic.
235 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
236 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
237 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
241 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
242 /// exactly one predecessor and the control transfer mechanism between
243 /// the predecessor and this block is a fall-through.
244 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
246 // The predecessor has to be immediately before this block.
247 const MachineBasicBlock *Pred = *MBB->pred_begin();
249 // If the predecessor is a switch statement, assume a jump table
250 // implementation, so it is not a fall through.
251 if (const BasicBlock *bb = Pred->getBasicBlock())
252 if (isa<SwitchInst>(bb->getTerminator()))
255 // If this is a landing pad, it isn't a fall through. If it has no preds,
256 // then nothing falls through to it.
257 if (MBB->isLandingPad() || MBB->pred_empty())
260 // If there isn't exactly one predecessor, it can't be a fall through.
261 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
264 if (PI2 != MBB->pred_end())
267 // The predecessor has to be immediately before this block.
268 if (!Pred->isLayoutSuccessor(MBB))
271 // If the block is completely empty, then it definitely does fall through.
275 // Otherwise, check the last instruction.
276 // Check if the last terminator is an unconditional branch.
277 MachineBasicBlock::const_iterator I = Pred->end();
278 while (I != Pred->begin() && !(--I)->getDesc().isTerminator()) ;
280 return !I->getDesc().isBarrier();
283 // Print out an operand for an inline asm expression.
284 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
285 unsigned AsmVariant,const char *ExtraCode,
287 // Does this asm operand have a single letter operand modifier?
288 if (ExtraCode && ExtraCode[0])
289 return true; // Unknown modifier.
291 printOperand(MI, OpNo, O);
295 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
296 unsigned OpNum, unsigned AsmVariant,
297 const char *ExtraCode,
299 if (ExtraCode && ExtraCode[0])
300 return true; // Unknown modifier.
302 const MachineOperand &MO = MI->getOperand(OpNum);
303 assert(MO.isReg() && "unexpected inline asm memory operand");
304 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
308 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
310 const MachineOperand &MO = MI->getOperand(opNum);
313 if (MO.getTargetFlags())
316 switch(MO.getTargetFlags()) {
317 case MipsII::MO_GPREL: O << "%gp_rel("; break;
318 case MipsII::MO_GOT_CALL: O << "%call16("; break;
319 case MipsII::MO_GOT: O << "%got("; break;
320 case MipsII::MO_ABS_HI: O << "%hi("; break;
321 case MipsII::MO_ABS_LO: O << "%lo("; break;
322 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
323 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
324 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
325 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
326 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
327 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
328 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
329 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
330 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
333 switch (MO.getType()) {
334 case MachineOperand::MO_Register:
336 << LowercaseString(MipsInstPrinter::getRegisterName(MO.getReg()));
339 case MachineOperand::MO_Immediate:
343 case MachineOperand::MO_MachineBasicBlock:
344 O << *MO.getMBB()->getSymbol();
347 case MachineOperand::MO_GlobalAddress:
348 O << *Mang->getSymbol(MO.getGlobal());
351 case MachineOperand::MO_BlockAddress: {
352 MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
357 case MachineOperand::MO_ExternalSymbol:
358 O << *GetExternalSymbolSymbol(MO.getSymbolName());
361 case MachineOperand::MO_JumpTableIndex:
362 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
363 << '_' << MO.getIndex();
366 case MachineOperand::MO_ConstantPoolIndex:
367 O << MAI->getPrivateGlobalPrefix() << "CPI"
368 << getFunctionNumber() << "_" << MO.getIndex();
370 O << "+" << MO.getOffset();
374 llvm_unreachable("<unknown operand type>");
377 if (closeP) O << ")";
380 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
382 const MachineOperand &MO = MI->getOperand(opNum);
384 O << (unsigned short int)MO.getImm();
386 printOperand(MI, opNum, O);
389 void MipsAsmPrinter::
390 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
391 // Load/Store memory operands -- imm($reg)
392 // If PIC target the target is loaded as the
393 // pattern lw $25,%call16($28)
394 printOperand(MI, opNum+1, O);
396 printOperand(MI, opNum, O);
400 void MipsAsmPrinter::
401 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
402 // when using stack locations for not load/store instructions
403 // print the same way as all normal 3 operand instructions.
404 printOperand(MI, opNum, O);
406 printOperand(MI, opNum+1, O);
410 void MipsAsmPrinter::
411 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
412 const char *Modifier) {
413 const MachineOperand& MO = MI->getOperand(opNum);
414 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
417 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
418 // FIXME: Use SwitchSection.
420 // Tell the assembler which ABI we are using
421 OutStreamer.EmitRawText("\t.section .mdebug." + Twine(getCurrentABIString()));
423 // TODO: handle O64 ABI
424 if (Subtarget->isABI_EABI()) {
425 if (Subtarget->isGP32bit())
426 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
428 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
431 // return to previous section
432 OutStreamer.EmitRawText(StringRef("\t.previous"));
436 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
437 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
438 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
439 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
440 "Unexpected MachineOperand types");
441 return MachineLocation(MI->getOperand(0).getReg(),
442 MI->getOperand(1).getImm());
445 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
450 // Force static initialization.
451 extern "C" void LLVMInitializeMipsAsmPrinter() {
452 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
453 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
454 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
455 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);