1 //===-- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains a printer that converts from our internal representation 11 // of machine-dependent LLVM code to GAS-format MIPS assembly language. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "InstPrinter/MipsInstPrinter.h" 16 #include "MCTargetDesc/MipsBaseInfo.h" 17 #include "MCTargetDesc/MipsMCNaCl.h" 18 #include "Mips.h" 19 #include "MipsAsmPrinter.h" 20 #include "MipsInstrInfo.h" 21 #include "MipsMCInstLower.h" 22 #include "MipsTargetMachine.h" 23 #include "MipsTargetStreamer.h" 24 #include "llvm/ADT/SmallString.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/MCSymbolELF.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" 50 #include <string> 51 52 using namespace llvm; 53 54 #define DEBUG_TYPE "mips-asm-printer" 55 56 MipsTargetStreamer &MipsAsmPrinter::getTargetStreamer() const { 57 return static_cast<MipsTargetStreamer &>(*OutStreamer->getTargetStreamer()); 58 } 59 60 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 61 Subtarget = &MF.getSubtarget<MipsSubtarget>(); 62 63 // Initialize TargetLoweringObjectFile. 64 const_cast<TargetLoweringObjectFile &>(getObjFileLowering()) 65 .Initialize(OutContext, TM); 66 67 MipsFI = MF.getInfo<MipsFunctionInfo>(); 68 if (Subtarget->inMips16Mode()) 69 for (std::map< 70 const char *, 71 const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator 72 it = MipsFI->StubsNeeded.begin(); 73 it != MipsFI->StubsNeeded.end(); ++it) { 74 const char *Symbol = it->first; 75 const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second; 76 if (StubsNeeded.find(Symbol) == StubsNeeded.end()) 77 StubsNeeded[Symbol] = Signature; 78 } 79 MCP = MF.getConstantPool(); 80 81 // In NaCl, all indirect jump targets must be aligned to bundle size. 82 if (Subtarget->isTargetNaCl()) 83 NaClAlignIndirectJumpTargets(MF); 84 85 AsmPrinter::runOnMachineFunction(MF); 86 return true; 87 } 88 89 bool MipsAsmPrinter::lowerOperand(const MachineOperand &MO, MCOperand &MCOp) { 90 MCOp = MCInstLowering.LowerOperand(MO); 91 return MCOp.isValid(); 92 } 93 94 #include "MipsGenMCPseudoLowering.inc" 95 96 // Lower PseudoReturn/PseudoIndirectBranch/PseudoIndirectBranch64 to JR, JR_MM, 97 // JALR, or JALR64 as appropriate for the target 98 void MipsAsmPrinter::emitPseudoIndirectBranch(MCStreamer &OutStreamer, 99 const MachineInstr *MI) { 100 bool HasLinkReg = false; 101 MCInst TmpInst0; 102 103 if (Subtarget->hasMips64r6()) { 104 // MIPS64r6 should use (JALR64 ZERO_64, $rs) 105 TmpInst0.setOpcode(Mips::JALR64); 106 HasLinkReg = true; 107 } else if (Subtarget->hasMips32r6()) { 108 // MIPS32r6 should use (JALR ZERO, $rs) 109 TmpInst0.setOpcode(Mips::JALR); 110 HasLinkReg = true; 111 } else if (Subtarget->inMicroMipsMode()) 112 // microMIPS should use (JR_MM $rs) 113 TmpInst0.setOpcode(Mips::JR_MM); 114 else { 115 // Everything else should use (JR $rs) 116 TmpInst0.setOpcode(Mips::JR); 117 } 118 119 MCOperand MCOp; 120 121 if (HasLinkReg) { 122 unsigned ZeroReg = Subtarget->isGP64bit() ? Mips::ZERO_64 : Mips::ZERO; 123 TmpInst0.addOperand(MCOperand::createReg(ZeroReg)); 124 } 125 126 lowerOperand(MI->getOperand(0), MCOp); 127 TmpInst0.addOperand(MCOp); 128 129 EmitToStreamer(OutStreamer, TmpInst0); 130 } 131 132 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) { 133 MipsTargetStreamer &TS = getTargetStreamer(); 134 TS.forbidModuleDirective(); 135 136 if (MI->isDebugValue()) { 137 SmallString<128> Str; 138 raw_svector_ostream OS(Str); 139 140 PrintDebugValueComment(MI, OS); 141 return; 142 } 143 144 // If we just ended a constant pool, mark it as such. 145 if (InConstantPool && MI->getOpcode() != Mips::CONSTPOOL_ENTRY) { 146 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 147 InConstantPool = false; 148 } 149 if (MI->getOpcode() == Mips::CONSTPOOL_ENTRY) { 150 // CONSTPOOL_ENTRY - This instruction represents a floating 151 //constant pool in the function. The first operand is the ID# 152 // for this instruction, the second is the index into the 153 // MachineConstantPool that this is, the third is the size in 154 // bytes of this constant pool entry. 155 // The required alignment is specified on the basic block holding this MI. 156 // 157 unsigned LabelId = (unsigned)MI->getOperand(0).getImm(); 158 unsigned CPIdx = (unsigned)MI->getOperand(1).getIndex(); 159 160 // If this is the first entry of the pool, mark it. 161 if (!InConstantPool) { 162 OutStreamer->EmitDataRegion(MCDR_DataRegion); 163 InConstantPool = true; 164 } 165 166 OutStreamer->EmitLabel(GetCPISymbol(LabelId)); 167 168 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx]; 169 if (MCPE.isMachineConstantPoolEntry()) 170 EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal); 171 else 172 EmitGlobalConstant(MF->getDataLayout(), MCPE.Val.ConstVal); 173 return; 174 } 175 176 177 MachineBasicBlock::const_instr_iterator I = MI->getIterator(); 178 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end(); 179 180 do { 181 // Do any auto-generated pseudo lowerings. 182 if (emitPseudoExpansionLowering(*OutStreamer, &*I)) 183 continue; 184 185 if (I->getOpcode() == Mips::PseudoReturn || 186 I->getOpcode() == Mips::PseudoReturn64 || 187 I->getOpcode() == Mips::PseudoIndirectBranch || 188 I->getOpcode() == Mips::PseudoIndirectBranch64) { 189 emitPseudoIndirectBranch(*OutStreamer, &*I); 190 continue; 191 } 192 193 // The inMips16Mode() test is not permanent. 194 // Some instructions are marked as pseudo right now which 195 // would make the test fail for the wrong reason but 196 // that will be fixed soon. We need this here because we are 197 // removing another test for this situation downstream in the 198 // callchain. 199 // 200 if (I->isPseudo() && !Subtarget->inMips16Mode() 201 && !isLongBranchPseudo(I->getOpcode())) 202 llvm_unreachable("Pseudo opcode found in EmitInstruction()"); 203 204 MCInst TmpInst0; 205 MCInstLowering.Lower(&*I, TmpInst0); 206 EmitToStreamer(*OutStreamer, TmpInst0); 207 } while ((++I != E) && I->isInsideBundle()); // Delay slot check 208 } 209 210 //===----------------------------------------------------------------------===// 211 // 212 // Mips Asm Directives 213 // 214 // -- Frame directive "frame Stackpointer, Stacksize, RARegister" 215 // Describe the stack frame. 216 // 217 // -- Mask directives "(f)mask bitmask, offset" 218 // Tells the assembler which registers are saved and where. 219 // bitmask - contain a little endian bitset indicating which registers are 220 // saved on function prologue (e.g. with a 0x80000000 mask, the 221 // assembler knows the register 31 (RA) is saved at prologue. 222 // offset - the position before stack pointer subtraction indicating where 223 // the first saved register on prologue is located. (e.g. with a 224 // 225 // Consider the following function prologue: 226 // 227 // .frame $fp,48,$ra 228 // .mask 0xc0000000,-8 229 // addiu $sp, $sp, -48 230 // sw $ra, 40($sp) 231 // sw $fp, 36($sp) 232 // 233 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and 234 // 30 (FP) are saved at prologue. As the save order on prologue is from 235 // left to right, RA is saved first. A -8 offset means that after the 236 // stack pointer subtration, the first register in the mask (RA) will be 237 // saved at address 48-8=40. 238 // 239 //===----------------------------------------------------------------------===// 240 241 //===----------------------------------------------------------------------===// 242 // Mask directives 243 //===----------------------------------------------------------------------===// 244 245 // Create a bitmask with all callee saved registers for CPU or Floating Point 246 // registers. For CPU registers consider RA, GP and FP for saving if necessary. 247 void MipsAsmPrinter::printSavedRegsBitmask() { 248 // CPU and FPU Saved Registers Bitmasks 249 unsigned CPUBitmask = 0, FPUBitmask = 0; 250 int CPUTopSavedRegOff, FPUTopSavedRegOff; 251 252 // Set the CPU and FPU Bitmasks 253 const MachineFrameInfo *MFI = MF->getFrameInfo(); 254 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 255 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 256 // size of stack area to which FP callee-saved regs are saved. 257 unsigned CPURegSize = Mips::GPR32RegClass.getSize(); 258 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize(); 259 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize(); 260 bool HasAFGR64Reg = false; 261 unsigned CSFPRegsSize = 0; 262 263 for (const auto &I : CSI) { 264 unsigned Reg = I.getReg(); 265 unsigned RegNum = TRI->getEncodingValue(Reg); 266 267 // If it's a floating point register, set the FPU Bitmask. 268 // If it's a general purpose register, set the CPU Bitmask. 269 if (Mips::FGR32RegClass.contains(Reg)) { 270 FPUBitmask |= (1 << RegNum); 271 CSFPRegsSize += FGR32RegSize; 272 } else if (Mips::AFGR64RegClass.contains(Reg)) { 273 FPUBitmask |= (3 << RegNum); 274 CSFPRegsSize += AFGR64RegSize; 275 HasAFGR64Reg = true; 276 } else if (Mips::GPR32RegClass.contains(Reg)) 277 CPUBitmask |= (1 << RegNum); 278 } 279 280 // FP Regs are saved right below where the virtual frame pointer points to. 281 FPUTopSavedRegOff = FPUBitmask ? 282 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0; 283 284 // CPU Regs are saved below FP Regs. 285 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0; 286 287 MipsTargetStreamer &TS = getTargetStreamer(); 288 // Print CPUBitmask 289 TS.emitMask(CPUBitmask, CPUTopSavedRegOff); 290 291 // Print FPUBitmask 292 TS.emitFMask(FPUBitmask, FPUTopSavedRegOff); 293 } 294 295 //===----------------------------------------------------------------------===// 296 // Frame and Set directives 297 //===----------------------------------------------------------------------===// 298 299 /// Frame Directive 300 void MipsAsmPrinter::emitFrameDirective() { 301 const TargetRegisterInfo &RI = *MF->getSubtarget().getRegisterInfo(); 302 303 unsigned stackReg = RI.getFrameRegister(*MF); 304 unsigned returnReg = RI.getRARegister(); 305 unsigned stackSize = MF->getFrameInfo()->getStackSize(); 306 307 getTargetStreamer().emitFrame(stackReg, stackSize, returnReg); 308 } 309 310 /// Emit Set directives. 311 const char *MipsAsmPrinter::getCurrentABIString() const { 312 switch (static_cast<MipsTargetMachine &>(TM).getABI().GetEnumValue()) { 313 case MipsABIInfo::ABI::O32: return "abi32"; 314 case MipsABIInfo::ABI::N32: return "abiN32"; 315 case MipsABIInfo::ABI::N64: return "abi64"; 316 default: llvm_unreachable("Unknown Mips ABI"); 317 } 318 } 319 320 void MipsAsmPrinter::EmitFunctionEntryLabel() { 321 MipsTargetStreamer &TS = getTargetStreamer(); 322 323 // NaCl sandboxing requires that indirect call instructions are masked. 324 // This means that function entry points should be bundle-aligned. 325 if (Subtarget->isTargetNaCl()) 326 EmitAlignment(std::max(MF->getAlignment(), MIPS_NACL_BUNDLE_ALIGN)); 327 328 if (Subtarget->inMicroMipsMode()) 329 TS.emitDirectiveSetMicroMips(); 330 else 331 TS.emitDirectiveSetNoMicroMips(); 332 333 if (Subtarget->inMips16Mode()) 334 TS.emitDirectiveSetMips16(); 335 else 336 TS.emitDirectiveSetNoMips16(); 337 338 TS.emitDirectiveEnt(*CurrentFnSym); 339 OutStreamer->EmitLabel(CurrentFnSym); 340 } 341 342 /// EmitFunctionBodyStart - Targets can override this to emit stuff before 343 /// the first basic block in the function. 344 void MipsAsmPrinter::EmitFunctionBodyStart() { 345 MipsTargetStreamer &TS = getTargetStreamer(); 346 347 MCInstLowering.Initialize(&MF->getContext()); 348 349 bool IsNakedFunction = MF->getFunction()->hasFnAttribute(Attribute::Naked); 350 if (!IsNakedFunction) 351 emitFrameDirective(); 352 353 if (!IsNakedFunction) 354 printSavedRegsBitmask(); 355 356 if (!Subtarget->inMips16Mode()) { 357 TS.emitDirectiveSetNoReorder(); 358 TS.emitDirectiveSetNoMacro(); 359 TS.emitDirectiveSetNoAt(); 360 } 361 } 362 363 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after 364 /// the last basic block in the function. 365 void MipsAsmPrinter::EmitFunctionBodyEnd() { 366 MipsTargetStreamer &TS = getTargetStreamer(); 367 368 // There are instruction for this macros, but they must 369 // always be at the function end, and we can't emit and 370 // break with BB logic. 371 if (!Subtarget->inMips16Mode()) { 372 TS.emitDirectiveSetAt(); 373 TS.emitDirectiveSetMacro(); 374 TS.emitDirectiveSetReorder(); 375 } 376 TS.emitDirectiveEnd(CurrentFnSym->getName()); 377 // Make sure to terminate any constant pools that were at the end 378 // of the function. 379 if (!InConstantPool) 380 return; 381 InConstantPool = false; 382 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 383 } 384 385 void MipsAsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) { 386 MipsTargetStreamer &TS = getTargetStreamer(); 387 if (MBB.size() == 0) 388 TS.emitDirectiveInsn(); 389 } 390 391 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 392 /// exactly one predecessor and the control transfer mechanism between 393 /// the predecessor and this block is a fall-through. 394 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock* 395 MBB) const { 396 // The predecessor has to be immediately before this block. 397 const MachineBasicBlock *Pred = *MBB->pred_begin(); 398 399 // If the predecessor is a switch statement, assume a jump table 400 // implementation, so it is not a fall through. 401 if (const BasicBlock *bb = Pred->getBasicBlock()) 402 if (isa<SwitchInst>(bb->getTerminator())) 403 return false; 404 405 // If this is a landing pad, it isn't a fall through. If it has no preds, 406 // then nothing falls through to it. 407 if (MBB->isEHPad() || MBB->pred_empty()) 408 return false; 409 410 // If there isn't exactly one predecessor, it can't be a fall through. 411 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI; 412 ++PI2; 413 414 if (PI2 != MBB->pred_end()) 415 return false; 416 417 // The predecessor has to be immediately before this block. 418 if (!Pred->isLayoutSuccessor(MBB)) 419 return false; 420 421 // If the block is completely empty, then it definitely does fall through. 422 if (Pred->empty()) 423 return true; 424 425 // Otherwise, check the last instruction. 426 // Check if the last terminator is an unconditional branch. 427 MachineBasicBlock::const_iterator I = Pred->end(); 428 while (I != Pred->begin() && !(--I)->isTerminator()) ; 429 430 return !I->isBarrier(); 431 } 432 433 // Print out an operand for an inline asm expression. 434 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum, 435 unsigned AsmVariant, const char *ExtraCode, 436 raw_ostream &O) { 437 // Does this asm operand have a single letter operand modifier? 438 if (ExtraCode && ExtraCode[0]) { 439 if (ExtraCode[1] != 0) return true; // Unknown modifier. 440 441 const MachineOperand &MO = MI->getOperand(OpNum); 442 switch (ExtraCode[0]) { 443 default: 444 // See if this is a generic print operand 445 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O); 446 case 'X': // hex const int 447 if ((MO.getType()) != MachineOperand::MO_Immediate) 448 return true; 449 O << "0x" << Twine::utohexstr(MO.getImm()); 450 return false; 451 case 'x': // hex const int (low 16 bits) 452 if ((MO.getType()) != MachineOperand::MO_Immediate) 453 return true; 454 O << "0x" << Twine::utohexstr(MO.getImm() & 0xffff); 455 return false; 456 case 'd': // decimal const int 457 if ((MO.getType()) != MachineOperand::MO_Immediate) 458 return true; 459 O << MO.getImm(); 460 return false; 461 case 'm': // decimal const int minus 1 462 if ((MO.getType()) != MachineOperand::MO_Immediate) 463 return true; 464 O << MO.getImm() - 1; 465 return false; 466 case 'z': { 467 // $0 if zero, regular printing otherwise 468 if (MO.getType() == MachineOperand::MO_Immediate && MO.getImm() == 0) { 469 O << "$0"; 470 return false; 471 } 472 // If not, call printOperand as normal. 473 break; 474 } 475 case 'D': // Second part of a double word register operand 476 case 'L': // Low order register of a double word register operand 477 case 'M': // High order register of a double word register operand 478 { 479 if (OpNum == 0) 480 return true; 481 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1); 482 if (!FlagsOP.isImm()) 483 return true; 484 unsigned Flags = FlagsOP.getImm(); 485 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags); 486 // Number of registers represented by this operand. We are looking 487 // for 2 for 32 bit mode and 1 for 64 bit mode. 488 if (NumVals != 2) { 489 if (Subtarget->isGP64bit() && NumVals == 1 && MO.isReg()) { 490 unsigned Reg = MO.getReg(); 491 O << '$' << MipsInstPrinter::getRegisterName(Reg); 492 return false; 493 } 494 return true; 495 } 496 497 unsigned RegOp = OpNum; 498 if (!Subtarget->isGP64bit()){ 499 // Endianess reverses which register holds the high or low value 500 // between M and L. 501 switch(ExtraCode[0]) { 502 case 'M': 503 RegOp = (Subtarget->isLittle()) ? OpNum + 1 : OpNum; 504 break; 505 case 'L': 506 RegOp = (Subtarget->isLittle()) ? OpNum : OpNum + 1; 507 break; 508 case 'D': // Always the second part 509 RegOp = OpNum + 1; 510 } 511 if (RegOp >= MI->getNumOperands()) 512 return true; 513 const MachineOperand &MO = MI->getOperand(RegOp); 514 if (!MO.isReg()) 515 return true; 516 unsigned Reg = MO.getReg(); 517 O << '$' << MipsInstPrinter::getRegisterName(Reg); 518 return false; 519 } 520 } 521 case 'w': 522 // Print MSA registers for the 'f' constraint 523 // In LLVM, the 'w' modifier doesn't need to do anything. 524 // We can just call printOperand as normal. 525 break; 526 } 527 } 528 529 printOperand(MI, OpNum, O); 530 return false; 531 } 532 533 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, 534 unsigned OpNum, unsigned AsmVariant, 535 const char *ExtraCode, 536 raw_ostream &O) { 537 assert(OpNum + 1 < MI->getNumOperands() && "Insufficient operands"); 538 const MachineOperand &BaseMO = MI->getOperand(OpNum); 539 const MachineOperand &OffsetMO = MI->getOperand(OpNum + 1); 540 assert(BaseMO.isReg() && "Unexpected base pointer for inline asm memory operand."); 541 assert(OffsetMO.isImm() && "Unexpected offset for inline asm memory operand."); 542 int Offset = OffsetMO.getImm(); 543 544 // Currently we are expecting either no ExtraCode or 'D' 545 if (ExtraCode) { 546 if (ExtraCode[0] == 'D') 547 Offset += 4; 548 else 549 return true; // Unknown modifier. 550 // FIXME: M = high order bits 551 // FIXME: L = low order bits 552 } 553 554 O << Offset << "($" << MipsInstPrinter::getRegisterName(BaseMO.getReg()) << ")"; 555 556 return false; 557 } 558 559 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum, 560 raw_ostream &O) { 561 const MachineOperand &MO = MI->getOperand(opNum); 562 bool closeP = false; 563 564 if (MO.getTargetFlags()) 565 closeP = true; 566 567 switch(MO.getTargetFlags()) { 568 case MipsII::MO_GPREL: O << "%gp_rel("; break; 569 case MipsII::MO_GOT_CALL: O << "%call16("; break; 570 case MipsII::MO_GOT: O << "%got("; break; 571 case MipsII::MO_ABS_HI: O << "%hi("; break; 572 case MipsII::MO_ABS_LO: O << "%lo("; break; 573 case MipsII::MO_TLSGD: O << "%tlsgd("; break; 574 case MipsII::MO_GOTTPREL: O << "%gottprel("; break; 575 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break; 576 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break; 577 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break; 578 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break; 579 case MipsII::MO_GOT_DISP: O << "%got_disp("; break; 580 case MipsII::MO_GOT_PAGE: O << "%got_page("; break; 581 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break; 582 } 583 584 switch (MO.getType()) { 585 case MachineOperand::MO_Register: 586 O << '$' 587 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower(); 588 break; 589 590 case MachineOperand::MO_Immediate: 591 O << MO.getImm(); 592 break; 593 594 case MachineOperand::MO_MachineBasicBlock: 595 MO.getMBB()->getSymbol()->print(O, MAI); 596 return; 597 598 case MachineOperand::MO_GlobalAddress: 599 getSymbol(MO.getGlobal())->print(O, MAI); 600 break; 601 602 case MachineOperand::MO_BlockAddress: { 603 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress()); 604 O << BA->getName(); 605 break; 606 } 607 608 case MachineOperand::MO_ConstantPoolIndex: 609 O << getDataLayout().getPrivateGlobalPrefix() << "CPI" 610 << getFunctionNumber() << "_" << MO.getIndex(); 611 if (MO.getOffset()) 612 O << "+" << MO.getOffset(); 613 break; 614 615 default: 616 llvm_unreachable("<unknown operand type>"); 617 } 618 619 if (closeP) O << ")"; 620 } 621 622 void MipsAsmPrinter:: 623 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) { 624 // Load/Store memory operands -- imm($reg) 625 // If PIC target the target is loaded as the 626 // pattern lw $25,%call16($28) 627 628 // opNum can be invalid if instruction has reglist as operand. 629 // MemOperand is always last operand of instruction (base + offset). 630 switch (MI->getOpcode()) { 631 default: 632 break; 633 case Mips::SWM32_MM: 634 case Mips::LWM32_MM: 635 opNum = MI->getNumOperands() - 2; 636 break; 637 } 638 639 printOperand(MI, opNum+1, O); 640 O << "("; 641 printOperand(MI, opNum, O); 642 O << ")"; 643 } 644 645 void MipsAsmPrinter:: 646 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) { 647 // when using stack locations for not load/store instructions 648 // print the same way as all normal 3 operand instructions. 649 printOperand(MI, opNum, O); 650 O << ", "; 651 printOperand(MI, opNum+1, O); 652 return; 653 } 654 655 void MipsAsmPrinter:: 656 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O, 657 const char *Modifier) { 658 const MachineOperand &MO = MI->getOperand(opNum); 659 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm()); 660 } 661 662 void MipsAsmPrinter:: 663 printRegisterList(const MachineInstr *MI, int opNum, raw_ostream &O) { 664 for (int i = opNum, e = MI->getNumOperands(); i != e; ++i) { 665 if (i != opNum) O << ", "; 666 printOperand(MI, i, O); 667 } 668 } 669 670 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) { 671 MipsTargetStreamer &TS = getTargetStreamer(); 672 673 // MipsTargetStreamer has an initialization order problem when emitting an 674 // object file directly (see MipsTargetELFStreamer for full details). Work 675 // around it by re-initializing the PIC state here. 676 TS.setPic(OutContext.getObjectFileInfo()->isPositionIndependent()); 677 678 // Compute MIPS architecture attributes based on the default subtarget 679 // that we'd have constructed. Module level directives aren't LTO 680 // clean anyhow. 681 // FIXME: For ifunc related functions we could iterate over and look 682 // for a feature string that doesn't match the default one. 683 const Triple &TT = TM.getTargetTriple(); 684 StringRef CPU = MIPS_MC::selectMipsCPU(TT, TM.getTargetCPU()); 685 StringRef FS = TM.getTargetFeatureString(); 686 const MipsTargetMachine &MTM = static_cast<const MipsTargetMachine &>(TM); 687 const MipsSubtarget STI(TT, CPU, FS, MTM.isLittleEndian(), MTM); 688 689 bool IsABICalls = STI.isABICalls(); 690 const MipsABIInfo &ABI = MTM.getABI(); 691 if (IsABICalls) { 692 TS.emitDirectiveAbiCalls(); 693 Reloc::Model RM = TM.getRelocationModel(); 694 // FIXME: This condition should be a lot more complicated that it is here. 695 // Ideally it should test for properties of the ABI and not the ABI 696 // itself. 697 // For the moment, I'm only correcting enough to make MIPS-IV work. 698 if (RM == Reloc::Static && !ABI.IsN64()) 699 TS.emitDirectiveOptionPic0(); 700 } 701 702 // Tell the assembler which ABI we are using 703 std::string SectionName = std::string(".mdebug.") + getCurrentABIString(); 704 OutStreamer->SwitchSection( 705 OutContext.getELFSection(SectionName, ELF::SHT_PROGBITS, 0)); 706 707 // NaN: At the moment we only support: 708 // 1. .nan legacy (default) 709 // 2. .nan 2008 710 STI.isNaN2008() ? TS.emitDirectiveNaN2008() 711 : TS.emitDirectiveNaNLegacy(); 712 713 // TODO: handle O64 ABI 714 715 TS.updateABIInfo(STI); 716 717 // We should always emit a '.module fp=...' but binutils 2.24 does not accept 718 // it. We therefore emit it when it contradicts the ABI defaults (-mfpxx or 719 // -mfp64) and omit it otherwise. 720 if (ABI.IsO32() && (STI.isABI_FPXX() || STI.isFP64bit())) 721 TS.emitDirectiveModuleFP(); 722 723 // We should always emit a '.module [no]oddspreg' but binutils 2.24 does not 724 // accept it. We therefore emit it when it contradicts the default or an 725 // option has changed the default (i.e. FPXX) and omit it otherwise. 726 if (ABI.IsO32() && (!STI.useOddSPReg() || STI.isABI_FPXX())) 727 TS.emitDirectiveModuleOddSPReg(); 728 } 729 730 void MipsAsmPrinter::emitInlineAsmStart() const { 731 MipsTargetStreamer &TS = getTargetStreamer(); 732 733 // GCC's choice of assembler options for inline assembly code ('at', 'macro' 734 // and 'reorder') is different from LLVM's choice for generated code ('noat', 735 // 'nomacro' and 'noreorder'). 736 // In order to maintain compatibility with inline assembly code which depends 737 // on GCC's assembler options being used, we have to switch to those options 738 // for the duration of the inline assembly block and then switch back. 739 TS.emitDirectiveSetPush(); 740 TS.emitDirectiveSetAt(); 741 TS.emitDirectiveSetMacro(); 742 TS.emitDirectiveSetReorder(); 743 OutStreamer->AddBlankLine(); 744 } 745 746 void MipsAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo, 747 const MCSubtargetInfo *EndInfo) const { 748 OutStreamer->AddBlankLine(); 749 getTargetStreamer().emitDirectiveSetPop(); 750 } 751 752 void MipsAsmPrinter::EmitJal(const MCSubtargetInfo &STI, MCSymbol *Symbol) { 753 MCInst I; 754 I.setOpcode(Mips::JAL); 755 I.addOperand( 756 MCOperand::createExpr(MCSymbolRefExpr::create(Symbol, OutContext))); 757 OutStreamer->EmitInstruction(I, STI); 758 } 759 760 void MipsAsmPrinter::EmitInstrReg(const MCSubtargetInfo &STI, unsigned Opcode, 761 unsigned Reg) { 762 MCInst I; 763 I.setOpcode(Opcode); 764 I.addOperand(MCOperand::createReg(Reg)); 765 OutStreamer->EmitInstruction(I, STI); 766 } 767 768 void MipsAsmPrinter::EmitInstrRegReg(const MCSubtargetInfo &STI, 769 unsigned Opcode, unsigned Reg1, 770 unsigned Reg2) { 771 MCInst I; 772 // 773 // Because of the current td files for Mips32, the operands for MTC1 774 // appear backwards from their normal assembly order. It's not a trivial 775 // change to fix this in the td file so we adjust for it here. 776 // 777 if (Opcode == Mips::MTC1) { 778 unsigned Temp = Reg1; 779 Reg1 = Reg2; 780 Reg2 = Temp; 781 } 782 I.setOpcode(Opcode); 783 I.addOperand(MCOperand::createReg(Reg1)); 784 I.addOperand(MCOperand::createReg(Reg2)); 785 OutStreamer->EmitInstruction(I, STI); 786 } 787 788 void MipsAsmPrinter::EmitInstrRegRegReg(const MCSubtargetInfo &STI, 789 unsigned Opcode, unsigned Reg1, 790 unsigned Reg2, unsigned Reg3) { 791 MCInst I; 792 I.setOpcode(Opcode); 793 I.addOperand(MCOperand::createReg(Reg1)); 794 I.addOperand(MCOperand::createReg(Reg2)); 795 I.addOperand(MCOperand::createReg(Reg3)); 796 OutStreamer->EmitInstruction(I, STI); 797 } 798 799 void MipsAsmPrinter::EmitMovFPIntPair(const MCSubtargetInfo &STI, 800 unsigned MovOpc, unsigned Reg1, 801 unsigned Reg2, unsigned FPReg1, 802 unsigned FPReg2, bool LE) { 803 if (!LE) { 804 unsigned temp = Reg1; 805 Reg1 = Reg2; 806 Reg2 = temp; 807 } 808 EmitInstrRegReg(STI, MovOpc, Reg1, FPReg1); 809 EmitInstrRegReg(STI, MovOpc, Reg2, FPReg2); 810 } 811 812 void MipsAsmPrinter::EmitSwapFPIntParams(const MCSubtargetInfo &STI, 813 Mips16HardFloatInfo::FPParamVariant PV, 814 bool LE, bool ToFP) { 815 using namespace Mips16HardFloatInfo; 816 unsigned MovOpc = ToFP ? Mips::MTC1 : Mips::MFC1; 817 switch (PV) { 818 case FSig: 819 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12); 820 break; 821 case FFSig: 822 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F14, LE); 823 break; 824 case FDSig: 825 EmitInstrRegReg(STI, MovOpc, Mips::A0, Mips::F12); 826 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE); 827 break; 828 case DSig: 829 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE); 830 break; 831 case DDSig: 832 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE); 833 EmitMovFPIntPair(STI, MovOpc, Mips::A2, Mips::A3, Mips::F14, Mips::F15, LE); 834 break; 835 case DFSig: 836 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F12, Mips::F13, LE); 837 EmitInstrRegReg(STI, MovOpc, Mips::A2, Mips::F14); 838 break; 839 case NoSig: 840 return; 841 } 842 } 843 844 void MipsAsmPrinter::EmitSwapFPIntRetval( 845 const MCSubtargetInfo &STI, Mips16HardFloatInfo::FPReturnVariant RV, 846 bool LE) { 847 using namespace Mips16HardFloatInfo; 848 unsigned MovOpc = Mips::MFC1; 849 switch (RV) { 850 case FRet: 851 EmitInstrRegReg(STI, MovOpc, Mips::V0, Mips::F0); 852 break; 853 case DRet: 854 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE); 855 break; 856 case CFRet: 857 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE); 858 break; 859 case CDRet: 860 EmitMovFPIntPair(STI, MovOpc, Mips::V0, Mips::V1, Mips::F0, Mips::F1, LE); 861 EmitMovFPIntPair(STI, MovOpc, Mips::A0, Mips::A1, Mips::F2, Mips::F3, LE); 862 break; 863 case NoFPRet: 864 break; 865 } 866 } 867 868 void MipsAsmPrinter::EmitFPCallStub( 869 const char *Symbol, const Mips16HardFloatInfo::FuncSignature *Signature) { 870 MCSymbol *MSymbol = OutContext.getOrCreateSymbol(StringRef(Symbol)); 871 using namespace Mips16HardFloatInfo; 872 bool LE = getDataLayout().isLittleEndian(); 873 // Construct a local MCSubtargetInfo here. 874 // This is because the MachineFunction won't exist (but have not yet been 875 // freed) and since we're at the global level we can use the default 876 // constructed subtarget. 877 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 878 TM.getTargetTriple().str(), TM.getTargetCPU(), 879 TM.getTargetFeatureString())); 880 881 // 882 // .global xxxx 883 // 884 OutStreamer->EmitSymbolAttribute(MSymbol, MCSA_Global); 885 const char *RetType; 886 // 887 // make the comment field identifying the return and parameter 888 // types of the floating point stub 889 // # Stub function to call rettype xxxx (params) 890 // 891 switch (Signature->RetSig) { 892 case FRet: 893 RetType = "float"; 894 break; 895 case DRet: 896 RetType = "double"; 897 break; 898 case CFRet: 899 RetType = "complex"; 900 break; 901 case CDRet: 902 RetType = "double complex"; 903 break; 904 case NoFPRet: 905 RetType = ""; 906 break; 907 } 908 const char *Parms; 909 switch (Signature->ParamSig) { 910 case FSig: 911 Parms = "float"; 912 break; 913 case FFSig: 914 Parms = "float, float"; 915 break; 916 case FDSig: 917 Parms = "float, double"; 918 break; 919 case DSig: 920 Parms = "double"; 921 break; 922 case DDSig: 923 Parms = "double, double"; 924 break; 925 case DFSig: 926 Parms = "double, float"; 927 break; 928 case NoSig: 929 Parms = ""; 930 break; 931 } 932 OutStreamer->AddComment("\t# Stub function to call " + Twine(RetType) + " " + 933 Twine(Symbol) + " (" + Twine(Parms) + ")"); 934 // 935 // probably not necessary but we save and restore the current section state 936 // 937 OutStreamer->PushSection(); 938 // 939 // .section mips16.call.fpxxxx,"ax",@progbits 940 // 941 MCSectionELF *M = OutContext.getELFSection( 942 ".mips16.call.fp." + std::string(Symbol), ELF::SHT_PROGBITS, 943 ELF::SHF_ALLOC | ELF::SHF_EXECINSTR); 944 OutStreamer->SwitchSection(M, nullptr); 945 // 946 // .align 2 947 // 948 OutStreamer->EmitValueToAlignment(4); 949 MipsTargetStreamer &TS = getTargetStreamer(); 950 // 951 // .set nomips16 952 // .set nomicromips 953 // 954 TS.emitDirectiveSetNoMips16(); 955 TS.emitDirectiveSetNoMicroMips(); 956 // 957 // .ent __call_stub_fp_xxxx 958 // .type __call_stub_fp_xxxx,@function 959 // __call_stub_fp_xxxx: 960 // 961 std::string x = "__call_stub_fp_" + std::string(Symbol); 962 MCSymbolELF *Stub = 963 cast<MCSymbolELF>(OutContext.getOrCreateSymbol(StringRef(x))); 964 TS.emitDirectiveEnt(*Stub); 965 MCSymbol *MType = 966 OutContext.getOrCreateSymbol("__call_stub_fp_" + Twine(Symbol)); 967 OutStreamer->EmitSymbolAttribute(MType, MCSA_ELF_TypeFunction); 968 OutStreamer->EmitLabel(Stub); 969 970 // Only handle non-pic for now. 971 assert(TM.getRelocationModel() != Reloc::PIC_ && 972 "should not be here if we are compiling pic"); 973 TS.emitDirectiveSetReorder(); 974 // 975 // We need to add a MipsMCExpr class to MCTargetDesc to fully implement 976 // stubs without raw text but this current patch is for compiler generated 977 // functions and they all return some value. 978 // The calling sequence for non pic is different in that case and we need 979 // to implement %lo and %hi in order to handle the case of no return value 980 // See the corresponding method in Mips16HardFloat for details. 981 // 982 // mov the return address to S2. 983 // we have no stack space to store it and we are about to make another call. 984 // We need to make sure that the enclosing function knows to save S2 985 // This should have already been handled. 986 // 987 // Mov $18, $31 988 989 EmitInstrRegRegReg(*STI, Mips::OR, Mips::S2, Mips::RA, Mips::ZERO); 990 991 EmitSwapFPIntParams(*STI, Signature->ParamSig, LE, true); 992 993 // Jal xxxx 994 // 995 EmitJal(*STI, MSymbol); 996 997 // fix return values 998 EmitSwapFPIntRetval(*STI, Signature->RetSig, LE); 999 // 1000 // do the return 1001 // if (Signature->RetSig == NoFPRet) 1002 // llvm_unreachable("should not be any stubs here with no return value"); 1003 // else 1004 EmitInstrReg(*STI, Mips::JR, Mips::S2); 1005 1006 MCSymbol *Tmp = OutContext.createTempSymbol(); 1007 OutStreamer->EmitLabel(Tmp); 1008 const MCSymbolRefExpr *E = MCSymbolRefExpr::create(Stub, OutContext); 1009 const MCSymbolRefExpr *T = MCSymbolRefExpr::create(Tmp, OutContext); 1010 const MCExpr *T_min_E = MCBinaryExpr::createSub(T, E, OutContext); 1011 OutStreamer->emitELFSize(Stub, T_min_E); 1012 TS.emitDirectiveEnd(x); 1013 OutStreamer->PopSection(); 1014 } 1015 1016 void MipsAsmPrinter::EmitEndOfAsmFile(Module &M) { 1017 // Emit needed stubs 1018 // 1019 for (std::map< 1020 const char *, 1021 const llvm::Mips16HardFloatInfo::FuncSignature *>::const_iterator 1022 it = StubsNeeded.begin(); 1023 it != StubsNeeded.end(); ++it) { 1024 const char *Symbol = it->first; 1025 const llvm::Mips16HardFloatInfo::FuncSignature *Signature = it->second; 1026 EmitFPCallStub(Symbol, Signature); 1027 } 1028 // return to the text section 1029 OutStreamer->SwitchSection(OutContext.getObjectFileInfo()->getTextSection()); 1030 } 1031 1032 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI, 1033 raw_ostream &OS) { 1034 // TODO: implement 1035 } 1036 1037 // Align all targets of indirect branches on bundle size. Used only if target 1038 // is NaCl. 1039 void MipsAsmPrinter::NaClAlignIndirectJumpTargets(MachineFunction &MF) { 1040 // Align all blocks that are jumped to through jump table. 1041 if (MachineJumpTableInfo *JtInfo = MF.getJumpTableInfo()) { 1042 const std::vector<MachineJumpTableEntry> &JT = JtInfo->getJumpTables(); 1043 for (unsigned I = 0; I < JT.size(); ++I) { 1044 const std::vector<MachineBasicBlock*> &MBBs = JT[I].MBBs; 1045 1046 for (unsigned J = 0; J < MBBs.size(); ++J) 1047 MBBs[J]->setAlignment(MIPS_NACL_BUNDLE_ALIGN); 1048 } 1049 } 1050 1051 // If basic block address is taken, block can be target of indirect branch. 1052 for (auto &MBB : MF) { 1053 if (MBB.hasAddressTaken()) 1054 MBB.setAlignment(MIPS_NACL_BUNDLE_ALIGN); 1055 } 1056 } 1057 1058 bool MipsAsmPrinter::isLongBranchPseudo(int Opcode) const { 1059 return (Opcode == Mips::LONG_BRANCH_LUi 1060 || Opcode == Mips::LONG_BRANCH_ADDiu 1061 || Opcode == Mips::LONG_BRANCH_DADDiu); 1062 } 1063 1064 // Force static initialization. 1065 extern "C" void LLVMInitializeMipsAsmPrinter() { 1066 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget); 1067 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget); 1068 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target); 1069 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget); 1070 } 1071