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 #include "MipsAsmPrinter.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsABIInfo.h"
18 #include "MCTargetDesc/MipsBaseInfo.h"
19 #include "MCTargetDesc/MipsMCNaCl.h"
20 #include "MCTargetDesc/MipsMCTargetDesc.h"
22 #include "MipsMCInstLower.h"
23 #include "MipsMachineFunction.h"
24 #include "MipsSubtarget.h"
25 #include "MipsTargetMachine.h"
26 #include "MipsTargetStreamer.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Triple.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/BinaryFormat/ELF.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/IR/Attributes.h"
42 #include "llvm/IR/BasicBlock.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/InlineAsm.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCInst.h"
50 #include "llvm/MC/MCInstBuilder.h"
51 #include "llvm/MC/MCObjectFileInfo.h"
52 #include "llvm/MC/MCSectionELF.h"
53 #include "llvm/MC/MCSymbol.h"
54 #include "llvm/MC/MCSymbolELF.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/TargetRegistry.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Target/TargetMachine.h"
69 #define DEBUG_TYPE "mips-asm-printer"
71 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const {
72 return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer());
75 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
76 Subtarget = &MF.getSubtarget<MipsSubtarget>();
78 MipsFI = MF.getInfo<MipsFunctionInfo>();
79 if (Subtarget->inMips16Mode())
82 const Mips16HardFloatInfo::FuncSignature *>::const_iterator
83 it = MipsFI->StubsNeeded.begin();
84 it != MipsFI->StubsNeeded.end(); ++it) {
85 const char *Symbol = it->first;
86 const Mips16HardFloatInfo::FuncSignature *Signature = it->second;
87 if (StubsNeeded.find(Symbol) == StubsNeeded.end())
88 StubsNeeded[Symbol] = Signature;
90 MCP = MF.getConstantPool();
92 // In NaCl, all indirect jump targets must be aligned to bundle size.
93 if (Subtarget->isTargetNaCl())
94 NaClAlignIndirectJumpTargets(MF);
96 AsmPrinter::runOnMachineFunction(MF);
103 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
104 MCOp = MCInstLowering.LowerOperand(MO);
105 return MCOp.isValid();
108 #include "MipsGenMCPseudoLowering.inc"
110 // Lower PseudoReturn/PseudoIndirectBranch/PseudoIndirectBranch64 to JR, JR_MM,
111 // JALR, or JALR64 as appropriate for the target.
112 void MipsAsmPrinter::emitPseudoIndirectBranch(MCStreamer &OutStreamer,
113 const MachineInstr *MI) {
114 bool HasLinkReg = false;
115 bool InMicroMipsMode = Subtarget->inMicroMipsMode();
118 if (Subtarget->hasMips64r6()) {
119 // MIPS64r6 should use (JALR64 ZERO_64, $rs)
120 TmpInst0.setOpcode(Mips::JALR64);
122 } else if (Subtarget->hasMips32r6()) {
123 // MIPS32r6 should use (JALR ZERO, $rs)
125 TmpInst0.setOpcode(Mips::JRC16_MMR6);
127 TmpInst0.setOpcode(Mips::JALR);
130 } else if (Subtarget->inMicroMipsMode())
131 // microMIPS should use (JR_MM $rs)
132 TmpInst0.setOpcode(Mips::JR_MM);
134 // Everything else should use (JR $rs)
135 TmpInst0.setOpcode(Mips::JR);
141 unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::ZERO_64 : Mips::ZERO;
142 TmpInst0.addOperand(MCOperand::createReg(ZeroReg));
145 lowerOperand(MI->getOperand(0), MCOp);
146 TmpInst0.addOperand(MCOp);
148 EmitToStreamer(OutStreamer, TmpInst0);
151 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
152 MipsTargetStreamer &TS = getTargetStreamer();
153 unsigned Opc = MI->getOpcode();
154 TS.forbidModuleDirective();
156 if (MI->isDebugValue()) {
157 SmallString<128> Str;
158 raw_svector_ostream OS(Str);
160 PrintDebugValueComment(MI, OS);
164 // If we just ended a constant pool, mark it as such.
165 if (InConstantPool && Opc != Mips::CONSTPOOL_ENTRY) {
166 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
167 InConstantPool = false;
169 if (Opc == Mips::CONSTPOOL_ENTRY) {
170 // CONSTPOOL_ENTRY - This instruction represents a floating
171 // constant pool in the function. The first operand is the ID#
172 // for this instruction, the second is the index into the
173 // MachineConstantPool that this is, the third is the size in
174 // bytes of this constant pool entry.
175 // The required alignment is specified on the basic block holding this MI.
177 unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
178 unsigned CPIdx = (unsigned)MI->getOperand(1).getIndex();
180 // If this is the first entry of the pool, mark it.
181 if (!InConstantPool) {
182 OutStreamer->EmitDataRegion(MCDR_DataRegion);
183 InConstantPool = true;
186 OutStreamer->EmitLabel(GetCPISymbol(LabelId));
188 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
189 if (MCPE.isMachineConstantPoolEntry())
190 EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
192 EmitGlobalConstant(MF->getDataLayout(), MCPE.Val.ConstVal);
197 case Mips::PATCHABLE_FUNCTION_ENTER:
198 LowerPATCHABLE_FUNCTION_ENTER(*MI);
200 case Mips::PATCHABLE_FUNCTION_EXIT:
201 LowerPATCHABLE_FUNCTION_EXIT(*MI);
203 case Mips::PATCHABLE_TAIL_CALL:
204 LowerPATCHABLE_TAIL_CALL(*MI);
208 MachineBasicBlock::const_instr_iterator I = MI->getIterator();
209 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
212 // Do any auto-generated pseudo lowerings.
213 if (emitPseudoExpansionLowering(*OutStreamer, &*I))
216 if (I->getOpcode() == Mips::PseudoReturn ||
217 I->getOpcode() == Mips::PseudoReturn64 ||
218 I->getOpcode() == Mips::PseudoIndirectBranch ||
219 I->getOpcode() == Mips::PseudoIndirectBranch64 ||
220 I->getOpcode() == Mips::TAILCALLREG ||
221 I->getOpcode() == Mips::TAILCALLREG64) {
222 emitPseudoIndirectBranch(*OutStreamer, &*I);
226 // The inMips16Mode() test is not permanent.
227 // Some instructions are marked as pseudo right now which
228 // would make the test fail for the wrong reason but
229 // that will be fixed soon. We need this here because we are
230 // removing another test for this situation downstream in the
233 if (I->isPseudo() && !Subtarget->inMips16Mode()
234 && !isLongBranchPseudo(I->getOpcode()))
235 llvm_unreachable("Pseudo opcode found in EmitInstruction()");
238 MCInstLowering.Lower(&*I, TmpInst0);
239 EmitToStreamer(*OutStreamer, TmpInst0);
240 } while ((++I != E) && I->isInsideBundle()); // Delay slot check
243 //===----------------------------------------------------------------------===//
245 // Mips Asm Directives
247 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
248 // Describe the stack frame.
250 // -- Mask directives "(f)mask bitmask, offset"
251 // Tells the assembler which registers are saved and where.
252 // bitmask - contain a little endian bitset indicating which registers are
253 // saved on function prologue (e.g. with a 0x80000000 mask, the
254 // assembler knows the register 31 (RA) is saved at prologue.
255 // offset - the position before stack pointer subtraction indicating where
256 // the first saved register on prologue is located. (e.g. with a
258 // Consider the following function prologue:
261 // .mask 0xc0000000,-8
262 // addiu $sp, $sp, -48
266 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
267 // 30 (FP) are saved at prologue. As the save order on prologue is from
268 // left to right, RA is saved first. A -8 offset means that after the
269 // stack pointer subtration, the first register in the mask (RA) will be
270 // saved at address 48-8=40.
272 //===----------------------------------------------------------------------===//
274 //===----------------------------------------------------------------------===//
276 //===----------------------------------------------------------------------===//
278 // Create a bitmask with all callee saved registers for CPU or Floating Point
279 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
280 void MipsAsmPrinter::printSavedRegsBitmask() {
281 // CPU and FPU Saved Registers Bitmasks
282 unsigned CPUBitmask = 0, FPUBitmask = 0;
283 int CPUTopSavedRegOff, FPUTopSavedRegOff;
285 // Set the CPU and FPU Bitmasks
286 const MachineFrameInfo &MFI = MF->getFrameInfo();
287 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
288 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
289 // size of stack area to which FP callee-saved regs are saved.
290 unsigned CPURegSize = TRI->getRegSizeInBits(Mips::GPR32RegClass) / 8;
291 unsigned FGR32RegSize = TRI->getRegSizeInBits(Mips::FGR32RegClass) / 8;
292 unsigned AFGR64RegSize = TRI->getRegSizeInBits(Mips::AFGR64RegClass) / 8;
293 bool HasAFGR64Reg = false;
294 unsigned CSFPRegsSize = 0;
296 for (const auto &I : CSI) {
297 unsigned Reg = I.getReg();
298 unsigned RegNum = TRI->getEncodingValue(Reg);
300 // If it's a floating point register, set the FPU Bitmask.
301 // If it's a general purpose register, set the CPU Bitmask.
302 if (Mips::FGR32RegClass.contains(Reg)) {
303 FPUBitmask |= (1 << RegNum);
304 CSFPRegsSize += FGR32RegSize;
305 } else if (Mips::AFGR64RegClass.contains(Reg)) {
306 FPUBitmask |= (3 << RegNum);
307 CSFPRegsSize += AFGR64RegSize;
309 } else if (Mips::GPR32RegClass.contains(Reg))
310 CPUBitmask |= (1 << RegNum);
313 // FP Regs are saved right below where the virtual frame pointer points to.
314 FPUTopSavedRegOff = FPUBitmask ?
315 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
317 // CPU Regs are saved below FP Regs.
318 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
320 MipsTargetStreamer &TS = getTargetStreamer();
322 TS.emitMask(CPUBitmask, CPUTopSavedRegOff);
325 TS.emitFMask(FPUBitmask, FPUTopSavedRegOff);
328 //===----------------------------------------------------------------------===//
329 // Frame and Set directives
330 //===----------------------------------------------------------------------===//
333 void MipsAsmPrinter::emitFrameDirective() {
334 const TargetRegisterInfo &RI = *MF->getSubtarget().getRegisterInfo();
336 unsigned stackReg = RI.getFrameRegister(*MF);
337 unsigned returnReg = RI.getRARegister();
338 unsigned stackSize = MF->getFrameInfo().getStackSize();
340 getTargetStreamer().emitFrame(stackReg, stackSize, returnReg);
343 /// Emit Set directives.
344 const char *MipsAsmPrinter::getCurrentABIString() const {
345 switch (static_cast<MipsTargetMachine &>(TM).getABI().GetEnumValue()) {
346 case MipsABIInfo::ABI::O32: return "abi32";
347 case MipsABIInfo::ABI::N32: return "abiN32";
348 case MipsABIInfo::ABI::N64: return "abi64";
349 default: llvm_unreachable("Unknown Mips ABI");
353 void MipsAsmPrinter::EmitFunctionEntryLabel() {
354 MipsTargetStreamer &TS = getTargetStreamer();
356 // NaCl sandboxing requires that indirect call instructions are masked.
357 // This means that function entry points should be bundle-aligned.
358 if (Subtarget->isTargetNaCl())
359 EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN));
361 if (Subtarget->inMicroMipsMode()) {
362 TS.emitDirectiveSetMicroMips();
363 TS.setUsesMicroMips();
364 TS.updateABIInfo(*Subtarget);
366 TS.emitDirectiveSetNoMicroMips();
368 if (Subtarget->inMips16Mode())
369 TS.emitDirectiveSetMips16();
371 TS.emitDirectiveSetNoMips16();
373 TS.emitDirectiveEnt(*CurrentFnSym);
374 OutStreamer->EmitLabel(CurrentFnSym);
377 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
378 /// the first basic block in the function.
379 void MipsAsmPrinter::EmitFunctionBodyStart() {
380 MipsTargetStreamer &TS = getTargetStreamer();
382 MCInstLowering.Initialize(&MF->getContext());
384 bool IsNakedFunction = MF->getFunction().hasFnAttribute(Attribute::Naked);
385 if (!IsNakedFunction)
386 emitFrameDirective();
388 if (!IsNakedFunction)
389 printSavedRegsBitmask();
391 if (!Subtarget->inMips16Mode()) {
392 TS.emitDirectiveSetNoReorder();
393 TS.emitDirectiveSetNoMacro();
394 TS.emitDirectiveSetNoAt();
398 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
399 /// the last basic block in the function.
400 void MipsAsmPrinter::EmitFunctionBodyEnd() {
401 MipsTargetStreamer &TS = getTargetStreamer();
403 // There are instruction for this macros, but they must
404 // always be at the function end, and we can't emit and
405 // break with BB logic.
406 if (!Subtarget->inMips16Mode()) {
407 TS.emitDirectiveSetAt();
408 TS.emitDirectiveSetMacro();
409 TS.emitDirectiveSetReorder();
411 TS.emitDirectiveEnd(CurrentFnSym->getName());
412 // Make sure to terminate any constant pools that were at the end
416 InConstantPool = false;
417 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
420 void MipsAsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {
421 AsmPrinter::EmitBasicBlockEnd(MBB);
422 MipsTargetStreamer &TS = getTargetStreamer();
424 TS.emitDirectiveInsn();
427 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
428 /// exactly one predecessor and the control transfer mechanism between
429 /// the predecessor and this block is a fall-through.
430 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
432 // The predecessor has to be immediately before this block.
433 const MachineBasicBlock *Pred = *MBB->pred_begin();
435 // If the predecessor is a switch statement, assume a jump table
436 // implementation, so it is not a fall through.
437 if (const BasicBlock *bb = Pred->getBasicBlock())
438 if (isa<SwitchInst>(bb->getTerminator()))
441 // If this is a landing pad, it isn't a fall through. If it has no preds,
442 // then nothing falls through to it.
443 if (MBB->isEHPad() || MBB->pred_empty())
446 // If there isn't exactly one predecessor, it can't be a fall through.
447 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
450 if (PI2 != MBB->pred_end())
453 // The predecessor has to be immediately before this block.
454 if (!Pred->isLayoutSuccessor(MBB))
457 // If the block is completely empty, then it definitely does fall through.
461 // Otherwise, check the last instruction.
462 // Check if the last terminator is an unconditional branch.
463 MachineBasicBlock::const_iterator I = Pred->end();
464 while (I != Pred->begin() && !(--I)->isTerminator()) ;
466 return !I->isBarrier();
469 // Print out an operand for an inline asm expression.
470 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
471 unsigned AsmVariant, const char *ExtraCode,
473 // Does this asm operand have a single letter operand modifier?
474 if (ExtraCode && ExtraCode[0]) {
475 if (ExtraCode[1] != 0) return true; // Unknown modifier.
477 const MachineOperand &MO = MI->getOperand(OpNum);
478 switch (ExtraCode[0]) {
480 // See if this is a generic print operand
481 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
482 case 'X': // hex const int
483 if ((MO.getType()) != MachineOperand::MO_Immediate)
485 O << "0x" << Twine::utohexstr(MO.getImm());
487 case 'x': // hex const int (low 16 bits)
488 if ((MO.getType()) != MachineOperand::MO_Immediate)
490 O << "0x" << Twine::utohexstr(MO.getImm() & 0xffff);
492 case 'd': // decimal const int
493 if ((MO.getType()) != MachineOperand::MO_Immediate)
497 case 'm': // decimal const int minus 1
498 if ((MO.getType()) != MachineOperand::MO_Immediate)
500 O << MO.getImm() - 1;
503 // $0 if zero, regular printing otherwise
504 if (MO.getType() == MachineOperand::MO_Immediate && MO.getImm() == 0) {
508 // If not, call printOperand as normal.
510 case 'D': // Second part of a double word register operand
511 case 'L': // Low order register of a double word register operand
512 case 'M': // High order register of a double word register operand
516 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
517 if (!FlagsOP.isImm())
519 unsigned Flags = FlagsOP.getImm();
520 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
521 // Number of registers represented by this operand. We are looking
522 // for 2 for 32 bit mode and 1 for 64 bit mode.
524 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
525 unsigned Reg = MO.getReg();
526 O << '$' << MipsInstPrinter::getRegisterName(Reg);
532 unsigned RegOp = OpNum;
533 if (!Subtarget->isGP64bit()){
534 // Endianness reverses which register holds the high or low value
536 switch(ExtraCode[0]) {
538 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
541 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
543 case 'D': // Always the second part
546 if (RegOp >= MI->getNumOperands())
548 const MachineOperand &MO = MI->getOperand(RegOp);
551 unsigned Reg = MO.getReg();
552 O << '$' << MipsInstPrinter::getRegisterName(Reg);
557 // Print MSA registers for the 'f' constraint
558 // In LLVM, the 'w' modifier doesn't need to do anything.
559 // We can just call printOperand as normal.
564 printOperand(MI, OpNum, O);
568 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
569 unsigned OpNum, unsigned AsmVariant,
570 const char *ExtraCode,
572 assert(OpNum + 1 < MI->getNumOperands() && "Insufficient operands");
573 const MachineOperand &BaseMO = MI->getOperand(OpNum);
574 const MachineOperand &OffsetMO = MI->getOperand(OpNum + 1);
575 assert(BaseMO.isReg() && "Unexpected base pointer for inline asm memory operand.");
576 assert(OffsetMO.isImm() && "Unexpected offset for inline asm memory operand.");
577 int Offset = OffsetMO.getImm();
579 // Currently we are expecting either no ExtraCode or 'D'
581 if (ExtraCode[0] == 'D')
584 return true; // Unknown modifier.
585 // FIXME: M = high order bits
586 // FIXME: L = low order bits
589 O << Offset << "($" << MipsInstPrinter::getRegisterName(BaseMO.getReg()) << ")";
594 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
596 const MachineOperand &MO = MI->getOperand(opNum);
599 if (MO.getTargetFlags())
602 switch(MO.getTargetFlags()) {
603 case MipsII::MO_GPREL: O << "%gp_rel("; break;
604 case MipsII::MO_GOT_CALL: O << "%call16("; break;
605 case MipsII::MO_GOT: O << "%got("; break;
606 case MipsII::MO_ABS_HI: O << "%hi("; break;
607 case MipsII::MO_ABS_LO: O << "%lo("; break;
608 case MipsII::MO_HIGHER: O << "%higher("; break;
609 case MipsII::MO_HIGHEST: O << "%highest(("; break;
610 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
611 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
612 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
613 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
614 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
615 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
616 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
617 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
618 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
621 switch (MO.getType()) {
622 case MachineOperand::MO_Register:
624 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
627 case MachineOperand::MO_Immediate:
631 case MachineOperand::MO_MachineBasicBlock:
632 MO.getMBB()->getSymbol()->print(O, MAI);
635 case MachineOperand::MO_GlobalAddress:
636 getSymbol(MO.getGlobal())->print(O, MAI);
639 case MachineOperand::MO_BlockAddress: {
640 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
645 case MachineOperand::MO_ConstantPoolIndex:
646 O << getDataLayout().getPrivateGlobalPrefix() << "CPI"
647 << getFunctionNumber() << "_" << MO.getIndex();
649 O << "+" << MO.getOffset();
653 llvm_unreachable("<unknown operand type>");
656 if (closeP) O << ")";
659 void MipsAsmPrinter::
660 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
661 // Load/Store memory operands -- imm($reg)
662 // If PIC target the target is loaded as the
663 // pattern lw $25,%call16($28)
665 // opNum can be invalid if instruction has reglist as operand.
666 // MemOperand is always last operand of instruction (base + offset).
667 switch (MI->getOpcode()) {
672 opNum = MI->getNumOperands() - 2;
676 printOperand(MI, opNum+1, O);
678 printOperand(MI, opNum, O);
682 void MipsAsmPrinter::
683 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
684 // when using stack locations for not load/store instructions
685 // print the same way as all normal 3 operand instructions.
686 printOperand(MI, opNum, O);
688 printOperand(MI, opNum+1, O);
691 void MipsAsmPrinter::
692 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
693 const char *Modifier) {
694 const MachineOperand &MO = MI->getOperand(opNum);
695 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
698 void MipsAsmPrinter::
699 printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) {
700 for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) {
701 if (i != opNum) O << ", ";
702 printOperand(MI, i, O);
706 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
707 MipsTargetStreamer &TS = getTargetStreamer();
709 // MipsTargetStreamer has an initialization order problem when emitting an
710 // object file directly (see MipsTargetELFStreamer for full details). Work
711 // around it by re-initializing the PIC state here.
712 TS.setPic(OutContext.getObjectFileInfo()->isPositionIndependent());
714 // Compute MIPS architecture attributes based on the default subtarget
715 // that we'd have constructed. Module level directives aren't LTO
717 // FIXME: For ifunc related functions we could iterate over and look
718 // for a feature string that doesn't match the default one.
719 const Triple &TT = TM.getTargetTriple();
720 StringRef CPU = MIPS_MC::selectMipsCPU(TT, TM.getTargetCPU());
721 StringRef FS = TM.getTargetFeatureString();
722 const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM);
723 const MipsSubtarget STI(TT, CPU, FS, MTM.isLittleEndian(), MTM, 0);
725 bool IsABICalls = STI.isABICalls();
726 const MipsABIInfo &ABI = MTM.getABI();
728 TS.emitDirectiveAbiCalls();
729 // FIXME: This condition should be a lot more complicated that it is here.
730 // Ideally it should test for properties of the ABI and not the ABI
732 // For the moment, I'm only correcting enough to make MIPS-IV work.
733 if (!isPositionIndependent() && STI.hasSym32())
734 TS.emitDirectiveOptionPic0();
737 // Tell the assembler which ABI we are using
738 std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
739 OutStreamer->SwitchSection(
740 OutContext.getELFSection(SectionName, ELF::SHT_PROGBITS, 0));
742 // NaN: At the moment we only support:
743 // 1. .nan legacy (default)
745 STI.isNaN2008() ? TS.emitDirectiveNaN2008()
746 : TS.emitDirectiveNaNLegacy();
748 // TODO: handle O64 ABI
750 TS.updateABIInfo(STI);
752 // We should always emit a '.module fp=...' but binutils 2.24 does not accept
753 // it. We therefore emit it when it contradicts the ABI defaults (-mfpxx or
754 // -mfp64) and omit it otherwise.
755 if (ABI.IsO32() && (STI.isABI_FPXX() || STI.isFP64bit()))
756 TS.emitDirectiveModuleFP();
758 // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not
759 // accept it. We therefore emit it when it contradicts the default or an
760 // option has changed the default (i.e. FPXX) and omit it otherwise.
761 if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX()))
762 TS.emitDirectiveModuleOddSPReg();
765 void MipsAsmPrinter::emitInlineAsmStart() const {
766 MipsTargetStreamer &TS = getTargetStreamer();
768 // GCC's choice of assembler options for inline assembly code ('at', 'macro'
769 // and 'reorder') is different from LLVM's choice for generated code ('noat',
770 // 'nomacro' and 'noreorder').
771 // In order to maintain compatibility with inline assembly code which depends
772 // on GCC's assembler options being used, we have to switch to those options
773 // for the duration of the inline assembly block and then switch back.
774 TS.emitDirectiveSetPush();
775 TS.emitDirectiveSetAt();
776 TS.emitDirectiveSetMacro();
777 TS.emitDirectiveSetReorder();
778 OutStreamer->AddBlankLine();
781 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
782 const MCSubtargetInfo *EndInfo) const {
783 OutStreamer->AddBlankLine();
784 getTargetStreamer().emitDirectiveSetPop();
787 void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) {
789 I.setOpcode(Mips::JAL);
791 MCOperand::createExpr(MCSymbolRefExpr::create(Symbol, OutContext)));
792 OutStreamer->EmitInstruction(I, STI);
795 void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode,
799 I.addOperand(MCOperand::createReg(Reg));
800 OutStreamer->EmitInstruction(I, STI);
803 void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI,
804 unsigned Opcode, unsigned Reg1,
808 // Because of the current td files for Mips32, the operands for MTC1
809 // appear backwards from their normal assembly order. It's not a trivial
810 // change to fix this in the td file so we adjust for it here.
812 if (Opcode == Mips::MTC1) {
813 unsigned Temp = Reg1;
818 I.addOperand(MCOperand::createReg(Reg1));
819 I.addOperand(MCOperand::createReg(Reg2));
820 OutStreamer->EmitInstruction(I, STI);
823 void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI,
824 unsigned Opcode, unsigned Reg1,
825 unsigned Reg2, unsigned Reg3) {
828 I.addOperand(MCOperand::createReg(Reg1));
829 I.addOperand(MCOperand::createReg(Reg2));
830 I.addOperand(MCOperand::createReg(Reg3));
831 OutStreamer->EmitInstruction(I, STI);
834 void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI,
835 unsigned MovOpc, unsigned Reg1,
836 unsigned Reg2, unsigned FPReg1,
837 unsigned FPReg2, bool LE) {
839 unsigned temp = Reg1;
843 EmitInstrRegReg(STI, MovOpc, Reg1, FPReg1);
844 EmitInstrRegReg(STI, MovOpc, Reg2, FPReg2);
847 void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI,
848 Mips16HardFloatInfo::FPParamVariant PV,
849 bool LE, bool ToFP) {
850 using namespace Mips16HardFloatInfo;
852 unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
855 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
858 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
861 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12);
862 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
865 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
868 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
869 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
872 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
873 EmitInstrRegReg(STI, MovOpc, Mips::A2, Mips::F14);
880 void MipsAsmPrinter::EmitSwapFPIntRetval(
881 const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV,
883 using namespace Mips16HardFloatInfo;
885 unsigned MovOpc = Mips::MFC1;
888 EmitInstrRegReg(STI, MovOpc, Mips::V0, Mips::F0);
891 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
894 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
897 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
898 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
905 void MipsAsmPrinter::EmitFPCallStub(
906 const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
907 using namespace Mips16HardFloatInfo;
909 MCSymbol *MSymbol = OutContext.getOrCreateSymbol(StringRef(Symbol));
910 bool LE = getDataLayout().isLittleEndian();
911 // Construct a local MCSubtargetInfo here.
912 // This is because the MachineFunction won't exist (but have not yet been
913 // freed) and since we're at the global level we can use the default
914 // constructed subtarget.
915 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
916 TM.getTargetTriple().str(), TM.getTargetCPU(),
917 TM.getTargetFeatureString()));
922 OutStreamer->EmitSymbolAttribute(MSymbol, MCSA_Global);
925 // make the comment field identifying the return and parameter
926 // types of the floating point stub
927 // # Stub function to call rettype xxxx (params)
929 switch (Signature->RetSig) {
940 RetType = "double complex";
947 switch (Signature->ParamSig) {
952 Parms = "float, float";
955 Parms = "float, double";
961 Parms = "double, double";
964 Parms = "double, float";
970 OutStreamer->AddComment("\t# Stub function to call " + Twine(RetType) + " " +
971 Twine(Symbol) + " (" + Twine(Parms) + ")");
973 // probably not necessary but we save and restore the current section state
975 OutStreamer->PushSection();
977 // .section mips16.call.fpxxxx,"ax",@progbits
979 MCSectionELF *M = OutContext.getELFSection(
980 ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
981 ELF::SHF_ALLOC | ELF::SHF_EXECINSTR);
982 OutStreamer->SwitchSection(M, nullptr);
986 OutStreamer->EmitValueToAlignment(4);
987 MipsTargetStreamer &TS = getTargetStreamer();
992 TS.emitDirectiveSetNoMips16();
993 TS.emitDirectiveSetNoMicroMips();
995 // .ent __call_stub_fp_xxxx
996 // .type __call_stub_fp_xxxx,@function
997 // __call_stub_fp_xxxx:
999 std::string x = "__call_stub_fp_" + std::string(Symbol);
1001 cast<MCSymbolELF>(OutContext.getOrCreateSymbol(StringRef(x)));
1002 TS.emitDirectiveEnt(*Stub);
1004 OutContext.getOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
1005 OutStreamer->EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
1006 OutStreamer->EmitLabel(Stub);
1008 // Only handle non-pic for now.
1009 assert(!isPositionIndependent() &&
1010 "should not be here if we are compiling pic");
1011 TS.emitDirectiveSetReorder();
1013 // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
1014 // stubs without raw text but this current patch is for compiler generated
1015 // functions and they all return some value.
1016 // The calling sequence for non pic is different in that case and we need
1017 // to implement %lo and %hi in order to handle the case of no return value
1018 // See the corresponding method in Mips16HardFloat for details.
1020 // mov the return address to S2.
1021 // we have no stack space to store it and we are about to make another call.
1022 // We need to make sure that the enclosing function knows to save S2
1023 // This should have already been handled.
1027 EmitInstrRegRegReg(*STI, Mips::OR, Mips::S2, Mips::RA, Mips::ZERO);
1029 EmitSwapFPIntParams(*STI, Signature->ParamSig, LE, true);
1033 EmitJal(*STI, MSymbol);
1035 // fix return values
1036 EmitSwapFPIntRetval(*STI, Signature->RetSig, LE);
1039 // if (Signature->RetSig == NoFPRet)
1040 // llvm_unreachable("should not be any stubs here with no return value");
1042 EmitInstrReg(*STI, Mips::JR, Mips::S2);
1044 MCSymbol *Tmp = OutContext.createTempSymbol();
1045 OutStreamer->EmitLabel(Tmp);
1046 const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Stub, OutContext);
1047 const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Tmp, OutContext);
1048 const MCExpr *T_min_E = MCBinaryExpr::createSub(T, E, OutContext);
1049 OutStreamer->emitELFSize(Stub, T_min_E);
1050 TS.emitDirectiveEnd(x);
1051 OutStreamer->PopSection();
1054 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
1055 // Emit needed stubs
1059 const Mips16HardFloatInfo::FuncSignature *>::const_iterator
1060 it = StubsNeeded.begin();
1061 it != StubsNeeded.end(); ++it) {
1062 const char *Symbol = it->first;
1063 const Mips16HardFloatInfo::FuncSignature *Signature = it->second;
1064 EmitFPCallStub(Symbol, Signature);
1066 // return to the text section
1067 OutStreamer->SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
1070 void MipsAsmPrinter::EmitSled(const MachineInstr &MI, SledKind Kind) {
1071 const uint8_t NoopsInSledCount = Subtarget->isGP64bit() ? 15 : 11;
1072 // For mips32 we want to emit the following pattern:
1077 // 11 NOP instructions (44 bytes)
1081 // We need the 44 bytes (11 instructions) because at runtime, we'd
1082 // be patching over the full 48 bytes (12 instructions) with the following
1089 // LUI T9, %hi(__xray_FunctionEntry/Exit)
1090 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit)
1091 // LUI T0, %hi(function_id)
1093 // ORI T0, T0, %lo(function_id)
1098 // We add 52 bytes to t9 because we want to adjust the function pointer to
1099 // the actual start of function i.e. the address just after the noop sled.
1100 // We do this because gp displacement relocation is emitted at the start of
1101 // of the function i.e after the nop sled and to correctly calculate the
1102 // global offset table address, t9 must hold the address of the instruction
1103 // containing the gp displacement relocation.
1104 // FIXME: Is this correct for the static relocation model?
1106 // For mips64 we want to emit the following pattern:
1111 // 15 NOP instructions (60 bytes)
1114 // We need the 60 bytes (15 instructions) because at runtime, we'd
1115 // be patching over the full 64 bytes (16 instructions) with the following
1118 // DADDIU SP, SP, -16
1122 // LUI T9, %highest(__xray_FunctionEntry/Exit)
1123 // ORI T9, T9, %higher(__xray_FunctionEntry/Exit)
1125 // ORI T9, T9, %hi(__xray_FunctionEntry/Exit)
1127 // ORI T9, T9, %lo(__xray_FunctionEntry/Exit)
1128 // LUI T0, %hi(function_id)
1130 // ADDIU T0, T0, %lo(function_id)
1133 // DADDIU SP, SP, 16
1135 OutStreamer->EmitCodeAlignment(4);
1136 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
1137 OutStreamer->EmitLabel(CurSled);
1138 auto Target = OutContext.createTempSymbol();
1140 // Emit "B .tmpN" instruction, which jumps over the nop sled to the actual
1141 // start of function
1142 const MCExpr *TargetExpr = MCSymbolRefExpr::create(
1143 Target, MCSymbolRefExpr::VariantKind::VK_None, OutContext);
1144 EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::BEQ)
1147 .addExpr(TargetExpr));
1149 for (int8_t I = 0; I < NoopsInSledCount; I++)
1150 EmitToStreamer(*OutStreamer, MCInstBuilder(Mips::SLL)
1155 OutStreamer->EmitLabel(Target);
1157 if (!Subtarget->isGP64bit()) {
1158 EmitToStreamer(*OutStreamer,
1159 MCInstBuilder(Mips::ADDiu)
1165 recordSled(CurSled, MI, Kind);
1168 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI) {
1169 EmitSled(MI, SledKind::FUNCTION_ENTER);
1172 void MipsAsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI) {
1173 EmitSled(MI, SledKind::FUNCTION_EXIT);
1176 void MipsAsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI) {
1177 EmitSled(MI, SledKind::TAIL_CALL);
1180 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1185 // Emit .dtprelword or .dtpreldword directive
1186 // and value for debug thread local expression.
1187 void MipsAsmPrinter::EmitDebugThreadLocal(const MCExpr *Value,
1188 unsigned Size) const {
1191 OutStreamer->EmitDTPRel32Value(Value);
1194 OutStreamer->EmitDTPRel64Value(Value);
1197 llvm_unreachable("Unexpected size of expression value.");
1201 // Align all targets of indirect branches on bundle size. Used only if target
1203 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
1204 // Align all blocks that are jumped to through jump table.
1205 if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
1206 const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
1207 for (unsigned I = 0; I < JT.size(); ++I) {
1208 const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs;
1210 for (unsigned J = 0; J < MBBs.size(); ++J)
1211 MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1215 // If basic block address is taken, block can be target of indirect branch.
1216 for (auto &MBB : MF) {
1217 if (MBB.hasAddressTaken())
1218 MBB.setAlignment(MIPS_NACL_BUNDLE_ALIGN);
1222 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
1223 return (Opcode == Mips::LONG_BRANCH_LUi
1224 || Opcode == Mips::LONG_BRANCH_ADDiu
1225 || Opcode == Mips::LONG_BRANCH_DADDiu);
1228 // Force static initialization.
1229 extern "C" void LLVMInitializeMipsAsmPrinter() {
1230 RegisterAsmPrinter<MipsAsmPrinter> X(getTheMipsTarget());
1231 RegisterAsmPrinter<MipsAsmPrinter> Y(getTheMipselTarget());
1232 RegisterAsmPrinter<MipsAsmPrinter> A(getTheMips64Target());
1233 RegisterAsmPrinter<MipsAsmPrinter> B(getTheMips64elTarget());