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 "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MCTargetDesc/MipsMCNaCl.h"
19 #include "MipsAsmPrinter.h"
20 #include "MipsInstrInfo.h"
21 #include "MipsMCInstLower.h"
22 #include "MipsTargetStreamer.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Twine.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/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCELFStreamer.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCInst.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "mips-asm-printer"
56 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() {
57 return static_cast<MipsTargetStreamer &>(*OutStreamer.getTargetStreamer());
60 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
61 // Initialize TargetLoweringObjectFile.
62 if (Subtarget->allowMixed16_32())
63 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
64 .Initialize(OutContext, TM);
65 MipsFI = MF.getInfo<MipsFunctionInfo>();
66 if (Subtarget->inMips16Mode())
69 const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
70 it = MipsFI->StubsNeeded.begin();
71 it != MipsFI->StubsNeeded.end(); ++it) {
72 const char *Symbol = it->first;
73 const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
74 if (StubsNeeded.find(Symbol) == StubsNeeded.end())
75 StubsNeeded[Symbol] = Signature;
77 MCP = MF.getConstantPool();
79 // In NaCl, all indirect jump targets must be aligned to bundle size.
80 if (Subtarget->isTargetNaCl())
81 NaClAlignIndirectJumpTargets(MF);
83 AsmPrinter::runOnMachineFunction(MF);
87 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) {
88 MCOp = MCInstLowering.LowerOperand(MO);
89 return MCOp.isValid();
92 #include "MipsGenMCPseudoLowering.inc"
94 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
95 MipsTargetStreamer &TS = getTargetStreamer();
96 TS.setCanHaveModuleDir(false);
98 if (MI->isDebugValue()) {
100 raw_svector_ostream OS(Str);
102 PrintDebugValueComment(MI, OS);
106 // If we just ended a constant pool, mark it as such.
107 if (InConstantPool && MI->getOpcode() != Mips::CONSTPOOL_ENTRY) {
108 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
109 InConstantPool = false;
111 if (MI->getOpcode() == Mips::CONSTPOOL_ENTRY) {
112 // CONSTPOOL_ENTRY - This instruction represents a floating
113 //constant pool in the function. The first operand is the ID#
114 // for this instruction, the second is the index into the
115 // MachineConstantPool that this is, the third is the size in
116 // bytes of this constant pool entry.
117 // The required alignment is specified on the basic block holding this MI.
119 unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
120 unsigned CPIdx = (unsigned)MI->getOperand(1).getIndex();
122 // If this is the first entry of the pool, mark it.
123 if (!InConstantPool) {
124 OutStreamer.EmitDataRegion(MCDR_DataRegion);
125 InConstantPool = true;
128 OutStreamer.EmitLabel(GetCPISymbol(LabelId));
130 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
131 if (MCPE.isMachineConstantPoolEntry())
132 EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
134 EmitGlobalConstant(MCPE.Val.ConstVal);
139 MachineBasicBlock::const_instr_iterator I = MI;
140 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
143 // Do any auto-generated pseudo lowerings.
144 if (emitPseudoExpansionLowering(OutStreamer, &*I))
147 // The inMips16Mode() test is not permanent.
148 // Some instructions are marked as pseudo right now which
149 // would make the test fail for the wrong reason but
150 // that will be fixed soon. We need this here because we are
151 // removing another test for this situation downstream in the
154 if (I->isPseudo() && !Subtarget->inMips16Mode()
155 && !isLongBranchPseudo(I->getOpcode()))
156 llvm_unreachable("Pseudo opcode found in EmitInstruction()");
159 MCInstLowering.Lower(I, TmpInst0);
160 EmitToStreamer(OutStreamer, TmpInst0);
161 } while ((++I != E) && I->isInsideBundle()); // Delay slot check
164 //===----------------------------------------------------------------------===//
166 // Mips Asm Directives
168 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
169 // Describe the stack frame.
171 // -- Mask directives "(f)mask bitmask, offset"
172 // Tells the assembler which registers are saved and where.
173 // bitmask - contain a little endian bitset indicating which registers are
174 // saved on function prologue (e.g. with a 0x80000000 mask, the
175 // assembler knows the register 31 (RA) is saved at prologue.
176 // offset - the position before stack pointer subtraction indicating where
177 // the first saved register on prologue is located. (e.g. with a
179 // Consider the following function prologue:
182 // .mask 0xc0000000,-8
183 // addiu $sp, $sp, -48
187 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
188 // 30 (FP) are saved at prologue. As the save order on prologue is from
189 // left to right, RA is saved first. A -8 offset means that after the
190 // stack pointer subtration, the first register in the mask (RA) will be
191 // saved at address 48-8=40.
193 //===----------------------------------------------------------------------===//
195 //===----------------------------------------------------------------------===//
197 //===----------------------------------------------------------------------===//
199 // Create a bitmask with all callee saved registers for CPU or Floating Point
200 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
201 void MipsAsmPrinter::printSavedRegsBitmask() {
202 // CPU and FPU Saved Registers Bitmasks
203 unsigned CPUBitmask = 0, FPUBitmask = 0;
204 int CPUTopSavedRegOff, FPUTopSavedRegOff;
206 // Set the CPU and FPU Bitmasks
207 const MachineFrameInfo *MFI = MF->getFrameInfo();
208 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
209 // size of stack area to which FP callee-saved regs are saved.
210 unsigned CPURegSize = Mips::GPR32RegClass.getSize();
211 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
212 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
213 bool HasAFGR64Reg = false;
214 unsigned CSFPRegsSize = 0;
215 unsigned i, e = CSI.size();
218 for (i = 0; i != e; ++i) {
219 unsigned Reg = CSI[i].getReg();
220 if (Mips::GPR32RegClass.contains(Reg))
223 unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
224 if (Mips::AFGR64RegClass.contains(Reg)) {
225 FPUBitmask |= (3 << RegNum);
226 CSFPRegsSize += AFGR64RegSize;
231 FPUBitmask |= (1 << RegNum);
232 CSFPRegsSize += FGR32RegSize;
236 for (; i != e; ++i) {
237 unsigned Reg = CSI[i].getReg();
238 unsigned RegNum = TM.getRegisterInfo()->getEncodingValue(Reg);
239 CPUBitmask |= (1 << RegNum);
242 // FP Regs are saved right below where the virtual frame pointer points to.
243 FPUTopSavedRegOff = FPUBitmask ?
244 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
246 // CPU Regs are saved below FP Regs.
247 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
249 MipsTargetStreamer &TS = getTargetStreamer();
251 TS.emitMask(CPUBitmask, CPUTopSavedRegOff);
254 TS.emitFMask(FPUBitmask, FPUTopSavedRegOff);
257 //===----------------------------------------------------------------------===//
258 // Frame and Set directives
259 //===----------------------------------------------------------------------===//
262 void MipsAsmPrinter::emitFrameDirective() {
263 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
265 unsigned stackReg = RI.getFrameRegister(*MF);
266 unsigned returnReg = RI.getRARegister();
267 unsigned stackSize = MF->getFrameInfo()->getStackSize();
269 getTargetStreamer().emitFrame(stackReg, stackSize, returnReg);
272 /// Emit Set directives.
273 const char *MipsAsmPrinter::getCurrentABIString() const {
274 switch (Subtarget->getTargetABI()) {
275 case MipsSubtarget::O32: return "abi32";
276 case MipsSubtarget::N32: return "abiN32";
277 case MipsSubtarget::N64: return "abi64";
278 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
279 default: llvm_unreachable("Unknown Mips ABI");
283 void MipsAsmPrinter::EmitFunctionEntryLabel() {
284 MipsTargetStreamer &TS = getTargetStreamer();
286 // NaCl sandboxing requires that indirect call instructions are masked.
287 // This means that function entry points should be bundle-aligned.
288 if (Subtarget->isTargetNaCl())
289 EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN));
291 if (Subtarget->inMicroMipsMode())
292 TS.emitDirectiveSetMicroMips();
294 TS.emitDirectiveSetNoMicroMips();
296 if (Subtarget->inMips16Mode())
297 TS.emitDirectiveSetMips16();
299 TS.emitDirectiveSetNoMips16();
301 TS.emitDirectiveEnt(*CurrentFnSym);
302 OutStreamer.EmitLabel(CurrentFnSym);
305 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
306 /// the first basic block in the function.
307 void MipsAsmPrinter::EmitFunctionBodyStart() {
308 MipsTargetStreamer &TS = getTargetStreamer();
310 MCInstLowering.Initialize(&MF->getContext());
312 bool IsNakedFunction =
314 getAttributes().hasAttribute(AttributeSet::FunctionIndex,
316 if (!IsNakedFunction)
317 emitFrameDirective();
319 if (!IsNakedFunction)
320 printSavedRegsBitmask();
322 if (!Subtarget->inMips16Mode()) {
323 TS.emitDirectiveSetNoReorder();
324 TS.emitDirectiveSetNoMacro();
325 TS.emitDirectiveSetNoAt();
329 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
330 /// the last basic block in the function.
331 void MipsAsmPrinter::EmitFunctionBodyEnd() {
332 MipsTargetStreamer &TS = getTargetStreamer();
334 // There are instruction for this macros, but they must
335 // always be at the function end, and we can't emit and
336 // break with BB logic.
337 if (!Subtarget->inMips16Mode()) {
338 TS.emitDirectiveSetAt();
339 TS.emitDirectiveSetMacro();
340 TS.emitDirectiveSetReorder();
342 TS.emitDirectiveEnd(CurrentFnSym->getName());
343 // Make sure to terminate any constant pools that were at the end
347 InConstantPool = false;
348 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
351 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
352 /// exactly one predecessor and the control transfer mechanism between
353 /// the predecessor and this block is a fall-through.
354 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
356 // The predecessor has to be immediately before this block.
357 const MachineBasicBlock *Pred = *MBB->pred_begin();
359 // If the predecessor is a switch statement, assume a jump table
360 // implementation, so it is not a fall through.
361 if (const BasicBlock *bb = Pred->getBasicBlock())
362 if (isa<SwitchInst>(bb->getTerminator()))
365 // If this is a landing pad, it isn't a fall through. If it has no preds,
366 // then nothing falls through to it.
367 if (MBB->isLandingPad() || MBB->pred_empty())
370 // If there isn't exactly one predecessor, it can't be a fall through.
371 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
374 if (PI2 != MBB->pred_end())
377 // The predecessor has to be immediately before this block.
378 if (!Pred->isLayoutSuccessor(MBB))
381 // If the block is completely empty, then it definitely does fall through.
385 // Otherwise, check the last instruction.
386 // Check if the last terminator is an unconditional branch.
387 MachineBasicBlock::const_iterator I = Pred->end();
388 while (I != Pred->begin() && !(--I)->isTerminator()) ;
390 return !I->isBarrier();
393 // Print out an operand for an inline asm expression.
394 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
395 unsigned AsmVariant,const char *ExtraCode,
397 // Does this asm operand have a single letter operand modifier?
398 if (ExtraCode && ExtraCode[0]) {
399 if (ExtraCode[1] != 0) return true; // Unknown modifier.
401 const MachineOperand &MO = MI->getOperand(OpNum);
402 switch (ExtraCode[0]) {
404 // See if this is a generic print operand
405 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
406 case 'X': // hex const int
407 if ((MO.getType()) != MachineOperand::MO_Immediate)
409 O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
411 case 'x': // hex const int (low 16 bits)
412 if ((MO.getType()) != MachineOperand::MO_Immediate)
414 O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
416 case 'd': // decimal const int
417 if ((MO.getType()) != MachineOperand::MO_Immediate)
421 case 'm': // decimal const int minus 1
422 if ((MO.getType()) != MachineOperand::MO_Immediate)
424 O << MO.getImm() - 1;
427 // $0 if zero, regular printing otherwise
428 if (MO.getType() != MachineOperand::MO_Immediate)
430 int64_t Val = MO.getImm();
437 case 'D': // Second part of a double word register operand
438 case 'L': // Low order register of a double word register operand
439 case 'M': // High order register of a double word register operand
443 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
444 if (!FlagsOP.isImm())
446 unsigned Flags = FlagsOP.getImm();
447 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
448 // Number of registers represented by this operand. We are looking
449 // for 2 for 32 bit mode and 1 for 64 bit mode.
451 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) {
452 unsigned Reg = MO.getReg();
453 O << '$' << MipsInstPrinter::getRegisterName(Reg);
459 unsigned RegOp = OpNum;
460 if (!Subtarget->isGP64bit()){
461 // Endianess reverses which register holds the high or low value
463 switch(ExtraCode[0]) {
465 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum;
468 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1;
470 case 'D': // Always the second part
473 if (RegOp >= MI->getNumOperands())
475 const MachineOperand &MO = MI->getOperand(RegOp);
478 unsigned Reg = MO.getReg();
479 O << '$' << MipsInstPrinter::getRegisterName(Reg);
484 // Print MSA registers for the 'f' constraint
485 // In LLVM, the 'w' modifier doesn't need to do anything.
486 // We can just call printOperand as normal.
491 printOperand(MI, OpNum, O);
495 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
496 unsigned OpNum, unsigned AsmVariant,
497 const char *ExtraCode,
500 // Currently we are expecting either no ExtraCode or 'D'
502 if (ExtraCode[0] == 'D')
505 return true; // Unknown modifier.
508 const MachineOperand &MO = MI->getOperand(OpNum);
509 assert(MO.isReg() && "unexpected inline asm memory operand");
510 O << Offset << "($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
515 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
517 const DataLayout *DL = TM.getDataLayout();
518 const MachineOperand &MO = MI->getOperand(opNum);
521 if (MO.getTargetFlags())
524 switch(MO.getTargetFlags()) {
525 case MipsII::MO_GPREL: O << "%gp_rel("; break;
526 case MipsII::MO_GOT_CALL: O << "%call16("; break;
527 case MipsII::MO_GOT: O << "%got("; break;
528 case MipsII::MO_ABS_HI: O << "%hi("; break;
529 case MipsII::MO_ABS_LO: O << "%lo("; break;
530 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
531 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
532 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
533 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
534 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
535 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
536 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
537 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
538 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
541 switch (MO.getType()) {
542 case MachineOperand::MO_Register:
544 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
547 case MachineOperand::MO_Immediate:
551 case MachineOperand::MO_MachineBasicBlock:
552 O << *MO.getMBB()->getSymbol();
555 case MachineOperand::MO_GlobalAddress:
556 O << *getSymbol(MO.getGlobal());
559 case MachineOperand::MO_BlockAddress: {
560 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
565 case MachineOperand::MO_ConstantPoolIndex:
566 O << DL->getPrivateGlobalPrefix() << "CPI"
567 << getFunctionNumber() << "_" << MO.getIndex();
569 O << "+" << MO.getOffset();
573 llvm_unreachable("<unknown operand type>");
576 if (closeP) O << ")";
579 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
581 const MachineOperand &MO = MI->getOperand(opNum);
583 O << (unsigned short int)MO.getImm();
585 printOperand(MI, opNum, O);
588 void MipsAsmPrinter::printUnsignedImm8(const MachineInstr *MI, int opNum,
590 const MachineOperand &MO = MI->getOperand(opNum);
592 O << (unsigned short int)(unsigned char)MO.getImm();
594 printOperand(MI, opNum, O);
597 void MipsAsmPrinter::
598 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
599 // Load/Store memory operands -- imm($reg)
600 // If PIC target the target is loaded as the
601 // pattern lw $25,%call16($28)
602 printOperand(MI, opNum+1, O);
604 printOperand(MI, opNum, O);
608 void MipsAsmPrinter::
609 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
610 // when using stack locations for not load/store instructions
611 // print the same way as all normal 3 operand instructions.
612 printOperand(MI, opNum, O);
614 printOperand(MI, opNum+1, O);
618 void MipsAsmPrinter::
619 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
620 const char *Modifier) {
621 const MachineOperand &MO = MI->getOperand(opNum);
622 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
625 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
626 // TODO: Need to add -mabicalls and -mno-abicalls flags.
627 // Currently we assume that -mabicalls is the default.
628 bool IsABICalls = true;
630 getTargetStreamer().emitDirectiveAbiCalls();
631 Reloc::Model RM = Subtarget->getRelocationModel();
632 // FIXME: This condition should be a lot more complicated that it is here.
633 // Ideally it should test for properties of the ABI and not the ABI
635 // For the moment, I'm only correcting enough to make MIPS-IV work.
636 if (RM == Reloc::Static && !Subtarget->isABI_N64())
637 getTargetStreamer().emitDirectiveOptionPic0();
640 // Tell the assembler which ABI we are using
641 std::string SectionName = std::string(".mdebug.") + getCurrentABIString();
642 OutStreamer.SwitchSection(OutContext.getELFSection(
643 SectionName, ELF::SHT_PROGBITS, 0, SectionKind::getDataRel()));
645 // NaN: At the moment we only support:
646 // 1. .nan legacy (default)
648 Subtarget->isNaN2008() ? getTargetStreamer().emitDirectiveNaN2008()
649 : getTargetStreamer().emitDirectiveNaNLegacy();
651 // TODO: handle O64 ABI
653 if (Subtarget->isABI_EABI()) {
654 if (Subtarget->isGP32bit())
655 OutStreamer.SwitchSection(
656 OutContext.getELFSection(".gcc_compiled_long32", ELF::SHT_PROGBITS, 0,
657 SectionKind::getDataRel()));
659 OutStreamer.SwitchSection(
660 OutContext.getELFSection(".gcc_compiled_long64", ELF::SHT_PROGBITS, 0,
661 SectionKind::getDataRel()));
663 getTargetStreamer().updateABIInfo(*Subtarget);
664 getTargetStreamer().emitDirectiveModuleFP(
665 getTargetStreamer().getABIFlagsSection().FpABI, Subtarget->isABI_O32());
668 void MipsAsmPrinter::EmitJal(MCSymbol *Symbol) {
670 I.setOpcode(Mips::JAL);
672 MCOperand::CreateExpr(MCSymbolRefExpr::Create(Symbol, OutContext)));
673 OutStreamer.EmitInstruction(I, getSubtargetInfo());
676 void MipsAsmPrinter::EmitInstrReg(unsigned Opcode, unsigned Reg) {
679 I.addOperand(MCOperand::CreateReg(Reg));
680 OutStreamer.EmitInstruction(I, getSubtargetInfo());
683 void MipsAsmPrinter::EmitInstrRegReg(unsigned Opcode, unsigned Reg1,
687 // Because of the current td files for Mips32, the operands for MTC1
688 // appear backwards from their normal assembly order. It's not a trivial
689 // change to fix this in the td file so we adjust for it here.
691 if (Opcode == Mips::MTC1) {
692 unsigned Temp = Reg1;
697 I.addOperand(MCOperand::CreateReg(Reg1));
698 I.addOperand(MCOperand::CreateReg(Reg2));
699 OutStreamer.EmitInstruction(I, getSubtargetInfo());
702 void MipsAsmPrinter::EmitInstrRegRegReg(unsigned Opcode, unsigned Reg1,
703 unsigned Reg2, unsigned Reg3) {
706 I.addOperand(MCOperand::CreateReg(Reg1));
707 I.addOperand(MCOperand::CreateReg(Reg2));
708 I.addOperand(MCOperand::CreateReg(Reg3));
709 OutStreamer.EmitInstruction(I, getSubtargetInfo());
712 void MipsAsmPrinter::EmitMovFPIntPair(unsigned MovOpc, unsigned Reg1,
713 unsigned Reg2, unsigned FPReg1,
714 unsigned FPReg2, bool LE) {
716 unsigned temp = Reg1;
720 EmitInstrRegReg(MovOpc, Reg1, FPReg1);
721 EmitInstrRegReg(MovOpc, Reg2, FPReg2);
724 void MipsAsmPrinter::EmitSwapFPIntParams(Mips16HardFloatInfo::FPParamVariant PV,
725 bool LE, bool ToFP) {
726 using namespace Mips16HardFloatInfo;
727 unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1;
730 EmitInstrRegReg(MovOpc, Mips::A0, Mips::F12);
733 EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE);
736 EmitInstrRegReg(MovOpc, Mips::A0, Mips::F12);
737 EmitMovFPIntPair(MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
740 EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
743 EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
744 EmitMovFPIntPair(MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE);
747 EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE);
748 EmitInstrRegReg(MovOpc, Mips::A2, Mips::F14);
756 MipsAsmPrinter::EmitSwapFPIntRetval(Mips16HardFloatInfo::FPReturnVariant RV,
758 using namespace Mips16HardFloatInfo;
759 unsigned MovOpc = Mips::MFC1;
762 EmitInstrRegReg(MovOpc, Mips::V0, Mips::F0);
765 EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
768 EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
771 EmitMovFPIntPair(MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE);
772 EmitMovFPIntPair(MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE);
779 void MipsAsmPrinter::EmitFPCallStub(
780 const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) {
781 MCSymbol *MSymbol = OutContext.GetOrCreateSymbol(StringRef(Symbol));
782 using namespace Mips16HardFloatInfo;
783 bool LE = Subtarget->isLittle();
787 OutStreamer.EmitSymbolAttribute(MSymbol, MCSA_Global);
790 // make the comment field identifying the return and parameter
791 // types of the floating point stub
792 // # Stub function to call rettype xxxx (params)
794 switch (Signature->RetSig) {
805 RetType = "double complex";
812 switch (Signature->ParamSig) {
817 Parms = "float, float";
820 Parms = "float, double";
826 Parms = "double, double";
829 Parms = "double, float";
835 OutStreamer.AddComment("\t# Stub function to call " + Twine(RetType) + " " +
836 Twine(Symbol) + " (" + Twine(Parms) + ")");
838 // probably not necessary but we save and restore the current section state
840 OutStreamer.PushSection();
842 // .section mips16.call.fpxxxx,"ax",@progbits
844 const MCSectionELF *M = OutContext.getELFSection(
845 ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS,
846 ELF::SHF_ALLOC | ELF::SHF_EXECINSTR, SectionKind::getText());
847 OutStreamer.SwitchSection(M, nullptr);
851 OutStreamer.EmitValueToAlignment(4);
852 MipsTargetStreamer &TS = getTargetStreamer();
857 TS.emitDirectiveSetNoMips16();
858 TS.emitDirectiveSetNoMicroMips();
860 // .ent __call_stub_fp_xxxx
861 // .type __call_stub_fp_xxxx,@function
862 // __call_stub_fp_xxxx:
864 std::string x = "__call_stub_fp_" + std::string(Symbol);
865 MCSymbol *Stub = OutContext.GetOrCreateSymbol(StringRef(x));
866 TS.emitDirectiveEnt(*Stub);
868 OutContext.GetOrCreateSymbol("__call_stub_fp_" + Twine(Symbol));
869 OutStreamer.EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction);
870 OutStreamer.EmitLabel(Stub);
872 // we just handle non pic for now. these function will not be
873 // called otherwise. when the full stub generation is moved here
874 // we need to deal with pic.
876 if (Subtarget->getRelocationModel() == Reloc::PIC_)
877 llvm_unreachable("should not be here if we are compiling pic");
878 TS.emitDirectiveSetReorder();
880 // We need to add a MipsMCExpr class to MCTargetDesc to fully implement
881 // stubs without raw text but this current patch is for compiler generated
882 // functions and they all return some value.
883 // The calling sequence for non pic is different in that case and we need
884 // to implement %lo and %hi in order to handle the case of no return value
885 // See the corresponding method in Mips16HardFloat for details.
887 // mov the return address to S2.
888 // we have no stack space to store it and we are about to make another call.
889 // We need to make sure that the enclosing function knows to save S2
890 // This should have already been handled.
894 EmitInstrRegRegReg(Mips::ADDu, Mips::S2, Mips::RA, Mips::ZERO);
896 EmitSwapFPIntParams(Signature->ParamSig, LE, true);
903 EmitSwapFPIntRetval(Signature->RetSig, LE);
906 // if (Signature->RetSig == NoFPRet)
907 // llvm_unreachable("should not be any stubs here with no return value");
909 EmitInstrReg(Mips::JR, Mips::S2);
911 MCSymbol *Tmp = OutContext.CreateTempSymbol();
912 OutStreamer.EmitLabel(Tmp);
913 const MCSymbolRefExpr *E = MCSymbolRefExpr::Create(Stub, OutContext);
914 const MCSymbolRefExpr *T = MCSymbolRefExpr::Create(Tmp, OutContext);
915 const MCExpr *T_min_E = MCBinaryExpr::CreateSub(T, E, OutContext);
916 OutStreamer.EmitELFSize(Stub, T_min_E);
917 TS.emitDirectiveEnd(x);
918 OutStreamer.PopSection();
921 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) {
926 const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator
927 it = StubsNeeded.begin();
928 it != StubsNeeded.end(); ++it) {
929 const char *Symbol = it->first;
930 const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second;
931 EmitFPCallStub(Symbol, Signature);
933 // return to the text section
934 OutStreamer.SwitchSection(OutContext.getObjectFileInfo()->getTextSection());
937 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
942 // Align all targets of indirect branches on bundle size. Used only if target
944 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) {
945 // Align all blocks that are jumped to through jump table.
946 if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) {
947 const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables();
948 for (unsigned I = 0; I < JT.size(); ++I) {
949 const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs;
951 for (unsigned J = 0; J < MBBs.size(); ++J)
952 MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
956 // If basic block address is taken, block can be target of indirect branch.
957 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
959 if (MBB->hasAddressTaken())
960 MBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
964 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const {
965 return (Opcode == Mips::LONG_BRANCH_LUi
966 || Opcode == Mips::LONG_BRANCH_ADDiu
967 || Opcode == Mips::LONG_BRANCH_DADDiu);
970 // Force static initialization.
971 extern "C" void LLVMInitializeMipsAsmPrinter() {
972 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
973 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
974 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
975 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);