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