1 //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the Base ARM implementation of the TargetInstrInfo class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ARMBaseInstrInfo.h" 14 #include "ARMBaseRegisterInfo.h" 15 #include "ARMConstantPoolValue.h" 16 #include "ARMFeatures.h" 17 #include "ARMHazardRecognizer.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "ARMSubtarget.h" 20 #include "MCTargetDesc/ARMAddressingModes.h" 21 #include "MCTargetDesc/ARMBaseInfo.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Triple.h" 27 #include "llvm/CodeGen/LiveVariables.h" 28 #include "llvm/CodeGen/MachineBasicBlock.h" 29 #include "llvm/CodeGen/MachineConstantPool.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstr.h" 33 #include "llvm/CodeGen/MachineInstrBuilder.h" 34 #include "llvm/CodeGen/MachineMemOperand.h" 35 #include "llvm/CodeGen/MachineModuleInfo.h" 36 #include "llvm/CodeGen/MachineOperand.h" 37 #include "llvm/CodeGen/MachineRegisterInfo.h" 38 #include "llvm/CodeGen/MachineScheduler.h" 39 #include "llvm/CodeGen/MultiHazardRecognizer.h" 40 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h" 41 #include "llvm/CodeGen/SelectionDAGNodes.h" 42 #include "llvm/CodeGen/TargetInstrInfo.h" 43 #include "llvm/CodeGen/TargetRegisterInfo.h" 44 #include "llvm/CodeGen/TargetSchedule.h" 45 #include "llvm/IR/Attributes.h" 46 #include "llvm/IR/Constants.h" 47 #include "llvm/IR/DebugLoc.h" 48 #include "llvm/IR/Function.h" 49 #include "llvm/IR/GlobalValue.h" 50 #include "llvm/MC/MCAsmInfo.h" 51 #include "llvm/MC/MCInstrDesc.h" 52 #include "llvm/MC/MCInstrItineraries.h" 53 #include "llvm/Support/BranchProbability.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/CommandLine.h" 56 #include "llvm/Support/Compiler.h" 57 #include "llvm/Support/Debug.h" 58 #include "llvm/Support/ErrorHandling.h" 59 #include "llvm/Support/raw_ostream.h" 60 #include "llvm/Target/TargetMachine.h" 61 #include <algorithm> 62 #include <cassert> 63 #include <cstdint> 64 #include <iterator> 65 #include <new> 66 #include <utility> 67 #include <vector> 68 69 using namespace llvm; 70 71 #define DEBUG_TYPE "arm-instrinfo" 72 73 #define GET_INSTRINFO_CTOR_DTOR 74 #include "ARMGenInstrInfo.inc" 75 76 static cl::opt<bool> 77 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden, 78 cl::desc("Enable ARM 2-addr to 3-addr conv")); 79 80 /// ARM_MLxEntry - Record information about MLA / MLS instructions. 81 struct ARM_MLxEntry { 82 uint16_t MLxOpc; // MLA / MLS opcode 83 uint16_t MulOpc; // Expanded multiplication opcode 84 uint16_t AddSubOpc; // Expanded add / sub opcode 85 bool NegAcc; // True if the acc is negated before the add / sub. 86 bool HasLane; // True if instruction has an extra "lane" operand. 87 }; 88 89 static const ARM_MLxEntry ARM_MLxTable[] = { 90 // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane 91 // fp scalar ops 92 { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false }, 93 { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false }, 94 { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false }, 95 { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false }, 96 { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false }, 97 { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false }, 98 { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false }, 99 { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false }, 100 101 // fp SIMD ops 102 { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false }, 103 { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false }, 104 { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false }, 105 { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false }, 106 { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true }, 107 { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true }, 108 { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true }, 109 { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true }, 110 }; 111 112 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI) 113 : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP), 114 Subtarget(STI) { 115 for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) { 116 if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second) 117 llvm_unreachable("Duplicated entries?"); 118 MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc); 119 MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc); 120 } 121 } 122 123 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl 124 // currently defaults to no prepass hazard recognizer. 125 ScheduleHazardRecognizer * 126 ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, 127 const ScheduleDAG *DAG) const { 128 if (usePreRAHazardRecognizer()) { 129 const InstrItineraryData *II = 130 static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData(); 131 return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched"); 132 } 133 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG); 134 } 135 136 ScheduleHazardRecognizer *ARMBaseInstrInfo:: 137 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, 138 const ScheduleDAG *DAG) const { 139 MultiHazardRecognizer *MHR = new MultiHazardRecognizer(); 140 141 if (Subtarget.isThumb2() || Subtarget.hasVFP2Base()) 142 MHR->AddHazardRecognizer(std::make_unique<ARMHazardRecognizerFPMLx>()); 143 144 auto BHR = TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG); 145 if (BHR) 146 MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR)); 147 return MHR; 148 } 149 150 MachineInstr *ARMBaseInstrInfo::convertToThreeAddress( 151 MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const { 152 // FIXME: Thumb2 support. 153 154 if (!EnableARM3Addr) 155 return nullptr; 156 157 MachineFunction &MF = *MI.getParent()->getParent(); 158 uint64_t TSFlags = MI.getDesc().TSFlags; 159 bool isPre = false; 160 switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) { 161 default: return nullptr; 162 case ARMII::IndexModePre: 163 isPre = true; 164 break; 165 case ARMII::IndexModePost: 166 break; 167 } 168 169 // Try splitting an indexed load/store to an un-indexed one plus an add/sub 170 // operation. 171 unsigned MemOpc = getUnindexedOpcode(MI.getOpcode()); 172 if (MemOpc == 0) 173 return nullptr; 174 175 MachineInstr *UpdateMI = nullptr; 176 MachineInstr *MemMI = nullptr; 177 unsigned AddrMode = (TSFlags & ARMII::AddrModeMask); 178 const MCInstrDesc &MCID = MI.getDesc(); 179 unsigned NumOps = MCID.getNumOperands(); 180 bool isLoad = !MI.mayStore(); 181 const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0); 182 const MachineOperand &Base = MI.getOperand(2); 183 const MachineOperand &Offset = MI.getOperand(NumOps - 3); 184 Register WBReg = WB.getReg(); 185 Register BaseReg = Base.getReg(); 186 Register OffReg = Offset.getReg(); 187 unsigned OffImm = MI.getOperand(NumOps - 2).getImm(); 188 ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm(); 189 switch (AddrMode) { 190 default: llvm_unreachable("Unknown indexed op!"); 191 case ARMII::AddrMode2: { 192 bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub; 193 unsigned Amt = ARM_AM::getAM2Offset(OffImm); 194 if (OffReg == 0) { 195 if (ARM_AM::getSOImmVal(Amt) == -1) 196 // Can't encode it in a so_imm operand. This transformation will 197 // add more than 1 instruction. Abandon! 198 return nullptr; 199 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 200 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg) 201 .addReg(BaseReg) 202 .addImm(Amt) 203 .add(predOps(Pred)) 204 .add(condCodeOp()); 205 } else if (Amt != 0) { 206 ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm); 207 unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt); 208 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 209 get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg) 210 .addReg(BaseReg) 211 .addReg(OffReg) 212 .addReg(0) 213 .addImm(SOOpc) 214 .add(predOps(Pred)) 215 .add(condCodeOp()); 216 } else 217 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 218 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg) 219 .addReg(BaseReg) 220 .addReg(OffReg) 221 .add(predOps(Pred)) 222 .add(condCodeOp()); 223 break; 224 } 225 case ARMII::AddrMode3 : { 226 bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub; 227 unsigned Amt = ARM_AM::getAM3Offset(OffImm); 228 if (OffReg == 0) 229 // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand. 230 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 231 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg) 232 .addReg(BaseReg) 233 .addImm(Amt) 234 .add(predOps(Pred)) 235 .add(condCodeOp()); 236 else 237 UpdateMI = BuildMI(MF, MI.getDebugLoc(), 238 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg) 239 .addReg(BaseReg) 240 .addReg(OffReg) 241 .add(predOps(Pred)) 242 .add(condCodeOp()); 243 break; 244 } 245 } 246 247 std::vector<MachineInstr*> NewMIs; 248 if (isPre) { 249 if (isLoad) 250 MemMI = 251 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg()) 252 .addReg(WBReg) 253 .addImm(0) 254 .addImm(Pred); 255 else 256 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc)) 257 .addReg(MI.getOperand(1).getReg()) 258 .addReg(WBReg) 259 .addReg(0) 260 .addImm(0) 261 .addImm(Pred); 262 NewMIs.push_back(MemMI); 263 NewMIs.push_back(UpdateMI); 264 } else { 265 if (isLoad) 266 MemMI = 267 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg()) 268 .addReg(BaseReg) 269 .addImm(0) 270 .addImm(Pred); 271 else 272 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc)) 273 .addReg(MI.getOperand(1).getReg()) 274 .addReg(BaseReg) 275 .addReg(0) 276 .addImm(0) 277 .addImm(Pred); 278 if (WB.isDead()) 279 UpdateMI->getOperand(0).setIsDead(); 280 NewMIs.push_back(UpdateMI); 281 NewMIs.push_back(MemMI); 282 } 283 284 // Transfer LiveVariables states, kill / dead info. 285 if (LV) { 286 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 287 MachineOperand &MO = MI.getOperand(i); 288 if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) { 289 Register Reg = MO.getReg(); 290 291 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg); 292 if (MO.isDef()) { 293 MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI; 294 if (MO.isDead()) 295 LV->addVirtualRegisterDead(Reg, *NewMI); 296 } 297 if (MO.isUse() && MO.isKill()) { 298 for (unsigned j = 0; j < 2; ++j) { 299 // Look at the two new MI's in reverse order. 300 MachineInstr *NewMI = NewMIs[j]; 301 if (!NewMI->readsRegister(Reg)) 302 continue; 303 LV->addVirtualRegisterKilled(Reg, *NewMI); 304 if (VI.removeKill(MI)) 305 VI.Kills.push_back(NewMI); 306 break; 307 } 308 } 309 } 310 } 311 } 312 313 MachineBasicBlock::iterator MBBI = MI.getIterator(); 314 MFI->insert(MBBI, NewMIs[1]); 315 MFI->insert(MBBI, NewMIs[0]); 316 return NewMIs[0]; 317 } 318 319 // Branch analysis. 320 bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB, 321 MachineBasicBlock *&TBB, 322 MachineBasicBlock *&FBB, 323 SmallVectorImpl<MachineOperand> &Cond, 324 bool AllowModify) const { 325 TBB = nullptr; 326 FBB = nullptr; 327 328 MachineBasicBlock::instr_iterator I = MBB.instr_end(); 329 if (I == MBB.instr_begin()) 330 return false; // Empty blocks are easy. 331 --I; 332 333 // Walk backwards from the end of the basic block until the branch is 334 // analyzed or we give up. 335 while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) { 336 // Flag to be raised on unanalyzeable instructions. This is useful in cases 337 // where we want to clean up on the end of the basic block before we bail 338 // out. 339 bool CantAnalyze = false; 340 341 // Skip over DEBUG values and predicated nonterminators. 342 while (I->isDebugInstr() || !I->isTerminator()) { 343 if (I == MBB.instr_begin()) 344 return false; 345 --I; 346 } 347 348 if (isIndirectBranchOpcode(I->getOpcode()) || 349 isJumpTableBranchOpcode(I->getOpcode())) { 350 // Indirect branches and jump tables can't be analyzed, but we still want 351 // to clean up any instructions at the tail of the basic block. 352 CantAnalyze = true; 353 } else if (isUncondBranchOpcode(I->getOpcode())) { 354 TBB = I->getOperand(0).getMBB(); 355 } else if (isCondBranchOpcode(I->getOpcode())) { 356 // Bail out if we encounter multiple conditional branches. 357 if (!Cond.empty()) 358 return true; 359 360 assert(!FBB && "FBB should have been null."); 361 FBB = TBB; 362 TBB = I->getOperand(0).getMBB(); 363 Cond.push_back(I->getOperand(1)); 364 Cond.push_back(I->getOperand(2)); 365 } else if (I->isReturn()) { 366 // Returns can't be analyzed, but we should run cleanup. 367 CantAnalyze = true; 368 } else { 369 // We encountered other unrecognized terminator. Bail out immediately. 370 return true; 371 } 372 373 // Cleanup code - to be run for unpredicated unconditional branches and 374 // returns. 375 if (!isPredicated(*I) && 376 (isUncondBranchOpcode(I->getOpcode()) || 377 isIndirectBranchOpcode(I->getOpcode()) || 378 isJumpTableBranchOpcode(I->getOpcode()) || 379 I->isReturn())) { 380 // Forget any previous condition branch information - it no longer applies. 381 Cond.clear(); 382 FBB = nullptr; 383 384 // If we can modify the function, delete everything below this 385 // unconditional branch. 386 if (AllowModify) { 387 MachineBasicBlock::iterator DI = std::next(I); 388 while (DI != MBB.instr_end()) { 389 MachineInstr &InstToDelete = *DI; 390 ++DI; 391 InstToDelete.eraseFromParent(); 392 } 393 } 394 } 395 396 if (CantAnalyze) { 397 // We may not be able to analyze the block, but we could still have 398 // an unconditional branch as the last instruction in the block, which 399 // just branches to layout successor. If this is the case, then just 400 // remove it if we're allowed to make modifications. 401 if (AllowModify && !isPredicated(MBB.back()) && 402 isUncondBranchOpcode(MBB.back().getOpcode()) && 403 TBB && MBB.isLayoutSuccessor(TBB)) 404 removeBranch(MBB); 405 return true; 406 } 407 408 if (I == MBB.instr_begin()) 409 return false; 410 411 --I; 412 } 413 414 // We made it past the terminators without bailing out - we must have 415 // analyzed this branch successfully. 416 return false; 417 } 418 419 unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB, 420 int *BytesRemoved) const { 421 assert(!BytesRemoved && "code size not handled"); 422 423 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 424 if (I == MBB.end()) 425 return 0; 426 427 if (!isUncondBranchOpcode(I->getOpcode()) && 428 !isCondBranchOpcode(I->getOpcode())) 429 return 0; 430 431 // Remove the branch. 432 I->eraseFromParent(); 433 434 I = MBB.end(); 435 436 if (I == MBB.begin()) return 1; 437 --I; 438 if (!isCondBranchOpcode(I->getOpcode())) 439 return 1; 440 441 // Remove the branch. 442 I->eraseFromParent(); 443 return 2; 444 } 445 446 unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB, 447 MachineBasicBlock *TBB, 448 MachineBasicBlock *FBB, 449 ArrayRef<MachineOperand> Cond, 450 const DebugLoc &DL, 451 int *BytesAdded) const { 452 assert(!BytesAdded && "code size not handled"); 453 ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>(); 454 int BOpc = !AFI->isThumbFunction() 455 ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB); 456 int BccOpc = !AFI->isThumbFunction() 457 ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc); 458 bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function(); 459 460 // Shouldn't be a fall through. 461 assert(TBB && "insertBranch must not be told to insert a fallthrough"); 462 assert((Cond.size() == 2 || Cond.size() == 0) && 463 "ARM branch conditions have two components!"); 464 465 // For conditional branches, we use addOperand to preserve CPSR flags. 466 467 if (!FBB) { 468 if (Cond.empty()) { // Unconditional branch? 469 if (isThumb) 470 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL)); 471 else 472 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB); 473 } else 474 BuildMI(&MBB, DL, get(BccOpc)) 475 .addMBB(TBB) 476 .addImm(Cond[0].getImm()) 477 .add(Cond[1]); 478 return 1; 479 } 480 481 // Two-way conditional branch. 482 BuildMI(&MBB, DL, get(BccOpc)) 483 .addMBB(TBB) 484 .addImm(Cond[0].getImm()) 485 .add(Cond[1]); 486 if (isThumb) 487 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL)); 488 else 489 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB); 490 return 2; 491 } 492 493 bool ARMBaseInstrInfo:: 494 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const { 495 ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm(); 496 Cond[0].setImm(ARMCC::getOppositeCondition(CC)); 497 return false; 498 } 499 500 bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const { 501 if (MI.isBundle()) { 502 MachineBasicBlock::const_instr_iterator I = MI.getIterator(); 503 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 504 while (++I != E && I->isInsideBundle()) { 505 int PIdx = I->findFirstPredOperandIdx(); 506 if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL) 507 return true; 508 } 509 return false; 510 } 511 512 int PIdx = MI.findFirstPredOperandIdx(); 513 return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL; 514 } 515 516 std::string ARMBaseInstrInfo::createMIROperandComment( 517 const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx, 518 const TargetRegisterInfo *TRI) const { 519 520 // First, let's see if there is a generic comment for this operand 521 std::string GenericComment = 522 TargetInstrInfo::createMIROperandComment(MI, Op, OpIdx, TRI); 523 if (!GenericComment.empty()) 524 return GenericComment; 525 526 // If not, check if we have an immediate operand. 527 if (Op.getType() != MachineOperand::MO_Immediate) 528 return std::string(); 529 530 // And print its corresponding condition code if the immediate is a 531 // predicate. 532 int FirstPredOp = MI.findFirstPredOperandIdx(); 533 if (FirstPredOp != (int) OpIdx) 534 return std::string(); 535 536 std::string CC = "CC::"; 537 CC += ARMCondCodeToString((ARMCC::CondCodes)Op.getImm()); 538 return CC; 539 } 540 541 bool ARMBaseInstrInfo::PredicateInstruction( 542 MachineInstr &MI, ArrayRef<MachineOperand> Pred) const { 543 unsigned Opc = MI.getOpcode(); 544 if (isUncondBranchOpcode(Opc)) { 545 MI.setDesc(get(getMatchingCondBranchOpcode(Opc))); 546 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 547 .addImm(Pred[0].getImm()) 548 .addReg(Pred[1].getReg()); 549 return true; 550 } 551 552 int PIdx = MI.findFirstPredOperandIdx(); 553 if (PIdx != -1) { 554 MachineOperand &PMO = MI.getOperand(PIdx); 555 PMO.setImm(Pred[0].getImm()); 556 MI.getOperand(PIdx+1).setReg(Pred[1].getReg()); 557 558 // Thumb 1 arithmetic instructions do not set CPSR when executed inside an 559 // IT block. This affects how they are printed. 560 const MCInstrDesc &MCID = MI.getDesc(); 561 if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) { 562 assert(MCID.OpInfo[1].isOptionalDef() && "CPSR def isn't expected operand"); 563 assert((MI.getOperand(1).isDead() || 564 MI.getOperand(1).getReg() != ARM::CPSR) && 565 "if conversion tried to stop defining used CPSR"); 566 MI.getOperand(1).setReg(ARM::NoRegister); 567 } 568 569 return true; 570 } 571 return false; 572 } 573 574 bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1, 575 ArrayRef<MachineOperand> Pred2) const { 576 if (Pred1.size() > 2 || Pred2.size() > 2) 577 return false; 578 579 ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm(); 580 ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm(); 581 if (CC1 == CC2) 582 return true; 583 584 switch (CC1) { 585 default: 586 return false; 587 case ARMCC::AL: 588 return true; 589 case ARMCC::HS: 590 return CC2 == ARMCC::HI; 591 case ARMCC::LS: 592 return CC2 == ARMCC::LO || CC2 == ARMCC::EQ; 593 case ARMCC::GE: 594 return CC2 == ARMCC::GT; 595 case ARMCC::LE: 596 return CC2 == ARMCC::LT; 597 } 598 } 599 600 bool ARMBaseInstrInfo::ClobbersPredicate(MachineInstr &MI, 601 std::vector<MachineOperand> &Pred, 602 bool SkipDead) const { 603 bool Found = false; 604 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 605 const MachineOperand &MO = MI.getOperand(i); 606 if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) || 607 (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) { 608 Pred.push_back(MO); 609 Found = true; 610 } 611 } 612 613 return Found; 614 } 615 616 bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) { 617 for (const auto &MO : MI.operands()) 618 if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead()) 619 return true; 620 return false; 621 } 622 623 static bool isEligibleForITBlock(const MachineInstr *MI) { 624 switch (MI->getOpcode()) { 625 default: return true; 626 case ARM::tADC: // ADC (register) T1 627 case ARM::tADDi3: // ADD (immediate) T1 628 case ARM::tADDi8: // ADD (immediate) T2 629 case ARM::tADDrr: // ADD (register) T1 630 case ARM::tAND: // AND (register) T1 631 case ARM::tASRri: // ASR (immediate) T1 632 case ARM::tASRrr: // ASR (register) T1 633 case ARM::tBIC: // BIC (register) T1 634 case ARM::tEOR: // EOR (register) T1 635 case ARM::tLSLri: // LSL (immediate) T1 636 case ARM::tLSLrr: // LSL (register) T1 637 case ARM::tLSRri: // LSR (immediate) T1 638 case ARM::tLSRrr: // LSR (register) T1 639 case ARM::tMUL: // MUL T1 640 case ARM::tMVN: // MVN (register) T1 641 case ARM::tORR: // ORR (register) T1 642 case ARM::tROR: // ROR (register) T1 643 case ARM::tRSB: // RSB (immediate) T1 644 case ARM::tSBC: // SBC (register) T1 645 case ARM::tSUBi3: // SUB (immediate) T1 646 case ARM::tSUBi8: // SUB (immediate) T2 647 case ARM::tSUBrr: // SUB (register) T1 648 return !ARMBaseInstrInfo::isCPSRDefined(*MI); 649 } 650 } 651 652 /// isPredicable - Return true if the specified instruction can be predicated. 653 /// By default, this returns true for every instruction with a 654 /// PredicateOperand. 655 bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const { 656 if (!MI.isPredicable()) 657 return false; 658 659 if (MI.isBundle()) 660 return false; 661 662 if (!isEligibleForITBlock(&MI)) 663 return false; 664 665 const ARMFunctionInfo *AFI = 666 MI.getParent()->getParent()->getInfo<ARMFunctionInfo>(); 667 668 // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM. 669 // In their ARM encoding, they can't be encoded in a conditional form. 670 if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) 671 return false; 672 673 if (AFI->isThumb2Function()) { 674 if (getSubtarget().restrictIT()) 675 return isV8EligibleForIT(&MI); 676 } 677 678 return true; 679 } 680 681 namespace llvm { 682 683 template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) { 684 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 685 const MachineOperand &MO = MI->getOperand(i); 686 if (!MO.isReg() || MO.isUndef() || MO.isUse()) 687 continue; 688 if (MO.getReg() != ARM::CPSR) 689 continue; 690 if (!MO.isDead()) 691 return false; 692 } 693 // all definitions of CPSR are dead 694 return true; 695 } 696 697 } // end namespace llvm 698 699 /// GetInstSize - Return the size of the specified MachineInstr. 700 /// 701 unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const { 702 const MachineBasicBlock &MBB = *MI.getParent(); 703 const MachineFunction *MF = MBB.getParent(); 704 const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo(); 705 706 const MCInstrDesc &MCID = MI.getDesc(); 707 if (MCID.getSize()) 708 return MCID.getSize(); 709 710 switch (MI.getOpcode()) { 711 default: 712 // pseudo-instruction sizes are zero. 713 return 0; 714 case TargetOpcode::BUNDLE: 715 return getInstBundleLength(MI); 716 case ARM::MOVi16_ga_pcrel: 717 case ARM::MOVTi16_ga_pcrel: 718 case ARM::t2MOVi16_ga_pcrel: 719 case ARM::t2MOVTi16_ga_pcrel: 720 return 4; 721 case ARM::MOVi32imm: 722 case ARM::t2MOVi32imm: 723 return 8; 724 case ARM::CONSTPOOL_ENTRY: 725 case ARM::JUMPTABLE_INSTS: 726 case ARM::JUMPTABLE_ADDRS: 727 case ARM::JUMPTABLE_TBB: 728 case ARM::JUMPTABLE_TBH: 729 // If this machine instr is a constant pool entry, its size is recorded as 730 // operand #2. 731 return MI.getOperand(2).getImm(); 732 case ARM::Int_eh_sjlj_longjmp: 733 return 16; 734 case ARM::tInt_eh_sjlj_longjmp: 735 return 10; 736 case ARM::tInt_WIN_eh_sjlj_longjmp: 737 return 12; 738 case ARM::Int_eh_sjlj_setjmp: 739 case ARM::Int_eh_sjlj_setjmp_nofp: 740 return 20; 741 case ARM::tInt_eh_sjlj_setjmp: 742 case ARM::t2Int_eh_sjlj_setjmp: 743 case ARM::t2Int_eh_sjlj_setjmp_nofp: 744 return 12; 745 case ARM::SPACE: 746 return MI.getOperand(1).getImm(); 747 case ARM::INLINEASM: 748 case ARM::INLINEASM_BR: { 749 // If this machine instr is an inline asm, measure it. 750 unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI); 751 if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction()) 752 Size = alignTo(Size, 4); 753 return Size; 754 } 755 } 756 } 757 758 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const { 759 unsigned Size = 0; 760 MachineBasicBlock::const_instr_iterator I = MI.getIterator(); 761 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 762 while (++I != E && I->isInsideBundle()) { 763 assert(!I->isBundle() && "No nested bundle!"); 764 Size += getInstSizeInBytes(*I); 765 } 766 return Size; 767 } 768 769 void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB, 770 MachineBasicBlock::iterator I, 771 unsigned DestReg, bool KillSrc, 772 const ARMSubtarget &Subtarget) const { 773 unsigned Opc = Subtarget.isThumb() 774 ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR) 775 : ARM::MRS; 776 777 MachineInstrBuilder MIB = 778 BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg); 779 780 // There is only 1 A/R class MRS instruction, and it always refers to 781 // APSR. However, there are lots of other possibilities on M-class cores. 782 if (Subtarget.isMClass()) 783 MIB.addImm(0x800); 784 785 MIB.add(predOps(ARMCC::AL)) 786 .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc)); 787 } 788 789 void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB, 790 MachineBasicBlock::iterator I, 791 unsigned SrcReg, bool KillSrc, 792 const ARMSubtarget &Subtarget) const { 793 unsigned Opc = Subtarget.isThumb() 794 ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR) 795 : ARM::MSR; 796 797 MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc)); 798 799 if (Subtarget.isMClass()) 800 MIB.addImm(0x800); 801 else 802 MIB.addImm(8); 803 804 MIB.addReg(SrcReg, getKillRegState(KillSrc)) 805 .add(predOps(ARMCC::AL)) 806 .addReg(ARM::CPSR, RegState::Implicit | RegState::Define); 807 } 808 809 void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) { 810 MIB.addImm(ARMVCC::None); 811 MIB.addReg(0); 812 } 813 814 void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB, 815 Register DestReg) { 816 addUnpredicatedMveVpredNOp(MIB); 817 MIB.addReg(DestReg, RegState::Undef); 818 } 819 820 void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) { 821 MIB.addImm(Cond); 822 MIB.addReg(ARM::VPR, RegState::Implicit); 823 } 824 825 void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB, 826 unsigned Cond, unsigned Inactive) { 827 addPredicatedMveVpredNOp(MIB, Cond); 828 MIB.addReg(Inactive); 829 } 830 831 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB, 832 MachineBasicBlock::iterator I, 833 const DebugLoc &DL, MCRegister DestReg, 834 MCRegister SrcReg, bool KillSrc) const { 835 bool GPRDest = ARM::GPRRegClass.contains(DestReg); 836 bool GPRSrc = ARM::GPRRegClass.contains(SrcReg); 837 838 if (GPRDest && GPRSrc) { 839 BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg) 840 .addReg(SrcReg, getKillRegState(KillSrc)) 841 .add(predOps(ARMCC::AL)) 842 .add(condCodeOp()); 843 return; 844 } 845 846 bool SPRDest = ARM::SPRRegClass.contains(DestReg); 847 bool SPRSrc = ARM::SPRRegClass.contains(SrcReg); 848 849 unsigned Opc = 0; 850 if (SPRDest && SPRSrc) 851 Opc = ARM::VMOVS; 852 else if (GPRDest && SPRSrc) 853 Opc = ARM::VMOVRS; 854 else if (SPRDest && GPRSrc) 855 Opc = ARM::VMOVSR; 856 else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64()) 857 Opc = ARM::VMOVD; 858 else if (ARM::QPRRegClass.contains(DestReg, SrcReg)) 859 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR; 860 861 if (Opc) { 862 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg); 863 MIB.addReg(SrcReg, getKillRegState(KillSrc)); 864 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) 865 MIB.addReg(SrcReg, getKillRegState(KillSrc)); 866 if (Opc == ARM::MVE_VORR) 867 addUnpredicatedMveVpredROp(MIB, DestReg); 868 else 869 MIB.add(predOps(ARMCC::AL)); 870 return; 871 } 872 873 // Handle register classes that require multiple instructions. 874 unsigned BeginIdx = 0; 875 unsigned SubRegs = 0; 876 int Spacing = 1; 877 878 // Use VORRq when possible. 879 if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) { 880 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR; 881 BeginIdx = ARM::qsub_0; 882 SubRegs = 2; 883 } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) { 884 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR; 885 BeginIdx = ARM::qsub_0; 886 SubRegs = 4; 887 // Fall back to VMOVD. 888 } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) { 889 Opc = ARM::VMOVD; 890 BeginIdx = ARM::dsub_0; 891 SubRegs = 2; 892 } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) { 893 Opc = ARM::VMOVD; 894 BeginIdx = ARM::dsub_0; 895 SubRegs = 3; 896 } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) { 897 Opc = ARM::VMOVD; 898 BeginIdx = ARM::dsub_0; 899 SubRegs = 4; 900 } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) { 901 Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr; 902 BeginIdx = ARM::gsub_0; 903 SubRegs = 2; 904 } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) { 905 Opc = ARM::VMOVD; 906 BeginIdx = ARM::dsub_0; 907 SubRegs = 2; 908 Spacing = 2; 909 } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) { 910 Opc = ARM::VMOVD; 911 BeginIdx = ARM::dsub_0; 912 SubRegs = 3; 913 Spacing = 2; 914 } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) { 915 Opc = ARM::VMOVD; 916 BeginIdx = ARM::dsub_0; 917 SubRegs = 4; 918 Spacing = 2; 919 } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && 920 !Subtarget.hasFP64()) { 921 Opc = ARM::VMOVS; 922 BeginIdx = ARM::ssub_0; 923 SubRegs = 2; 924 } else if (SrcReg == ARM::CPSR) { 925 copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget); 926 return; 927 } else if (DestReg == ARM::CPSR) { 928 copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget); 929 return; 930 } else if (DestReg == ARM::VPR) { 931 assert(ARM::GPRRegClass.contains(SrcReg)); 932 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg) 933 .addReg(SrcReg, getKillRegState(KillSrc)) 934 .add(predOps(ARMCC::AL)); 935 return; 936 } else if (SrcReg == ARM::VPR) { 937 assert(ARM::GPRRegClass.contains(DestReg)); 938 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg) 939 .addReg(SrcReg, getKillRegState(KillSrc)) 940 .add(predOps(ARMCC::AL)); 941 return; 942 } else if (DestReg == ARM::FPSCR_NZCV) { 943 assert(ARM::GPRRegClass.contains(SrcReg)); 944 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg) 945 .addReg(SrcReg, getKillRegState(KillSrc)) 946 .add(predOps(ARMCC::AL)); 947 return; 948 } else if (SrcReg == ARM::FPSCR_NZCV) { 949 assert(ARM::GPRRegClass.contains(DestReg)); 950 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg) 951 .addReg(SrcReg, getKillRegState(KillSrc)) 952 .add(predOps(ARMCC::AL)); 953 return; 954 } 955 956 assert(Opc && "Impossible reg-to-reg copy"); 957 958 const TargetRegisterInfo *TRI = &getRegisterInfo(); 959 MachineInstrBuilder Mov; 960 961 // Copy register tuples backward when the first Dest reg overlaps with SrcReg. 962 if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) { 963 BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing); 964 Spacing = -Spacing; 965 } 966 #ifndef NDEBUG 967 SmallSet<unsigned, 4> DstRegs; 968 #endif 969 for (unsigned i = 0; i != SubRegs; ++i) { 970 Register Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing); 971 Register Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing); 972 assert(Dst && Src && "Bad sub-register"); 973 #ifndef NDEBUG 974 assert(!DstRegs.count(Src) && "destructive vector copy"); 975 DstRegs.insert(Dst); 976 #endif 977 Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src); 978 // VORR (NEON or MVE) takes two source operands. 979 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) { 980 Mov.addReg(Src); 981 } 982 // MVE VORR takes predicate operands in place of an ordinary condition. 983 if (Opc == ARM::MVE_VORR) 984 addUnpredicatedMveVpredROp(Mov, Dst); 985 else 986 Mov = Mov.add(predOps(ARMCC::AL)); 987 // MOVr can set CC. 988 if (Opc == ARM::MOVr) 989 Mov = Mov.add(condCodeOp()); 990 } 991 // Add implicit super-register defs and kills to the last instruction. 992 Mov->addRegisterDefined(DestReg, TRI); 993 if (KillSrc) 994 Mov->addRegisterKilled(SrcReg, TRI); 995 } 996 997 Optional<DestSourcePair> 998 ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const { 999 // VMOVRRD is also a copy instruction but it requires 1000 // special way of handling. It is more complex copy version 1001 // and since that we are not considering it. For recognition 1002 // of such instruction isExtractSubregLike MI interface fuction 1003 // could be used. 1004 // VORRq is considered as a move only if two inputs are 1005 // the same register. 1006 if (!MI.isMoveReg() || 1007 (MI.getOpcode() == ARM::VORRq && 1008 MI.getOperand(1).getReg() != MI.getOperand(2).getReg())) 1009 return None; 1010 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)}; 1011 } 1012 1013 Optional<ParamLoadedValue> 1014 ARMBaseInstrInfo::describeLoadedValue(const MachineInstr &MI, 1015 Register Reg) const { 1016 if (auto DstSrcPair = isCopyInstrImpl(MI)) { 1017 Register DstReg = DstSrcPair->Destination->getReg(); 1018 1019 // TODO: We don't handle cases where the forwarding reg is narrower/wider 1020 // than the copy registers. Consider for example: 1021 // 1022 // s16 = VMOVS s0 1023 // s17 = VMOVS s1 1024 // call @callee(d0) 1025 // 1026 // We'd like to describe the call site value of d0 as d8, but this requires 1027 // gathering and merging the descriptions for the two VMOVS instructions. 1028 // 1029 // We also don't handle the reverse situation, where the forwarding reg is 1030 // narrower than the copy destination: 1031 // 1032 // d8 = VMOVD d0 1033 // call @callee(s1) 1034 // 1035 // We need to produce a fragment description (the call site value of s1 is 1036 // /not/ just d8). 1037 if (DstReg != Reg) 1038 return None; 1039 } 1040 return TargetInstrInfo::describeLoadedValue(MI, Reg); 1041 } 1042 1043 const MachineInstrBuilder & 1044 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg, 1045 unsigned SubIdx, unsigned State, 1046 const TargetRegisterInfo *TRI) const { 1047 if (!SubIdx) 1048 return MIB.addReg(Reg, State); 1049 1050 if (Register::isPhysicalRegister(Reg)) 1051 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State); 1052 return MIB.addReg(Reg, State, SubIdx); 1053 } 1054 1055 void ARMBaseInstrInfo:: 1056 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, 1057 Register SrcReg, bool isKill, int FI, 1058 const TargetRegisterClass *RC, 1059 const TargetRegisterInfo *TRI) const { 1060 MachineFunction &MF = *MBB.getParent(); 1061 MachineFrameInfo &MFI = MF.getFrameInfo(); 1062 Align Alignment = MFI.getObjectAlign(FI); 1063 1064 MachineMemOperand *MMO = MF.getMachineMemOperand( 1065 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore, 1066 MFI.getObjectSize(FI), Alignment); 1067 1068 switch (TRI->getSpillSize(*RC)) { 1069 case 2: 1070 if (ARM::HPRRegClass.hasSubClassEq(RC)) { 1071 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH)) 1072 .addReg(SrcReg, getKillRegState(isKill)) 1073 .addFrameIndex(FI) 1074 .addImm(0) 1075 .addMemOperand(MMO) 1076 .add(predOps(ARMCC::AL)); 1077 } else 1078 llvm_unreachable("Unknown reg class!"); 1079 break; 1080 case 4: 1081 if (ARM::GPRRegClass.hasSubClassEq(RC)) { 1082 BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12)) 1083 .addReg(SrcReg, getKillRegState(isKill)) 1084 .addFrameIndex(FI) 1085 .addImm(0) 1086 .addMemOperand(MMO) 1087 .add(predOps(ARMCC::AL)); 1088 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) { 1089 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS)) 1090 .addReg(SrcReg, getKillRegState(isKill)) 1091 .addFrameIndex(FI) 1092 .addImm(0) 1093 .addMemOperand(MMO) 1094 .add(predOps(ARMCC::AL)); 1095 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) { 1096 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off)) 1097 .addReg(SrcReg, getKillRegState(isKill)) 1098 .addFrameIndex(FI) 1099 .addImm(0) 1100 .addMemOperand(MMO) 1101 .add(predOps(ARMCC::AL)); 1102 } else 1103 llvm_unreachable("Unknown reg class!"); 1104 break; 1105 case 8: 1106 if (ARM::DPRRegClass.hasSubClassEq(RC)) { 1107 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD)) 1108 .addReg(SrcReg, getKillRegState(isKill)) 1109 .addFrameIndex(FI) 1110 .addImm(0) 1111 .addMemOperand(MMO) 1112 .add(predOps(ARMCC::AL)); 1113 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) { 1114 if (Subtarget.hasV5TEOps()) { 1115 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD)); 1116 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI); 1117 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI); 1118 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO) 1119 .add(predOps(ARMCC::AL)); 1120 } else { 1121 // Fallback to STM instruction, which has existed since the dawn of 1122 // time. 1123 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA)) 1124 .addFrameIndex(FI) 1125 .addMemOperand(MMO) 1126 .add(predOps(ARMCC::AL)); 1127 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI); 1128 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI); 1129 } 1130 } else 1131 llvm_unreachable("Unknown reg class!"); 1132 break; 1133 case 16: 1134 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) { 1135 // Use aligned spills if the stack can be realigned. 1136 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) { 1137 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64)) 1138 .addFrameIndex(FI) 1139 .addImm(16) 1140 .addReg(SrcReg, getKillRegState(isKill)) 1141 .addMemOperand(MMO) 1142 .add(predOps(ARMCC::AL)); 1143 } else { 1144 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA)) 1145 .addReg(SrcReg, getKillRegState(isKill)) 1146 .addFrameIndex(FI) 1147 .addMemOperand(MMO) 1148 .add(predOps(ARMCC::AL)); 1149 } 1150 } else if (ARM::QPRRegClass.hasSubClassEq(RC) && 1151 Subtarget.hasMVEIntegerOps()) { 1152 auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32)); 1153 MIB.addReg(SrcReg, getKillRegState(isKill)) 1154 .addFrameIndex(FI) 1155 .addImm(0) 1156 .addMemOperand(MMO); 1157 addUnpredicatedMveVpredNOp(MIB); 1158 } else 1159 llvm_unreachable("Unknown reg class!"); 1160 break; 1161 case 24: 1162 if (ARM::DTripleRegClass.hasSubClassEq(RC)) { 1163 // Use aligned spills if the stack can be realigned. 1164 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1165 Subtarget.hasNEON()) { 1166 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo)) 1167 .addFrameIndex(FI) 1168 .addImm(16) 1169 .addReg(SrcReg, getKillRegState(isKill)) 1170 .addMemOperand(MMO) 1171 .add(predOps(ARMCC::AL)); 1172 } else { 1173 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), 1174 get(ARM::VSTMDIA)) 1175 .addFrameIndex(FI) 1176 .add(predOps(ARMCC::AL)) 1177 .addMemOperand(MMO); 1178 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); 1179 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); 1180 AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); 1181 } 1182 } else 1183 llvm_unreachable("Unknown reg class!"); 1184 break; 1185 case 32: 1186 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) { 1187 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1188 Subtarget.hasNEON()) { 1189 // FIXME: It's possible to only store part of the QQ register if the 1190 // spilled def has a sub-register index. 1191 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo)) 1192 .addFrameIndex(FI) 1193 .addImm(16) 1194 .addReg(SrcReg, getKillRegState(isKill)) 1195 .addMemOperand(MMO) 1196 .add(predOps(ARMCC::AL)); 1197 } else { 1198 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), 1199 get(ARM::VSTMDIA)) 1200 .addFrameIndex(FI) 1201 .add(predOps(ARMCC::AL)) 1202 .addMemOperand(MMO); 1203 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); 1204 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); 1205 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); 1206 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI); 1207 } 1208 } else 1209 llvm_unreachable("Unknown reg class!"); 1210 break; 1211 case 64: 1212 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) { 1213 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA)) 1214 .addFrameIndex(FI) 1215 .add(predOps(ARMCC::AL)) 1216 .addMemOperand(MMO); 1217 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI); 1218 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI); 1219 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI); 1220 MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI); 1221 MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI); 1222 MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI); 1223 MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI); 1224 AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI); 1225 } else 1226 llvm_unreachable("Unknown reg class!"); 1227 break; 1228 default: 1229 llvm_unreachable("Unknown reg class!"); 1230 } 1231 } 1232 1233 unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI, 1234 int &FrameIndex) const { 1235 switch (MI.getOpcode()) { 1236 default: break; 1237 case ARM::STRrs: 1238 case ARM::t2STRs: // FIXME: don't use t2STRs to access frame. 1239 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() && 1240 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 && 1241 MI.getOperand(3).getImm() == 0) { 1242 FrameIndex = MI.getOperand(1).getIndex(); 1243 return MI.getOperand(0).getReg(); 1244 } 1245 break; 1246 case ARM::STRi12: 1247 case ARM::t2STRi12: 1248 case ARM::tSTRspi: 1249 case ARM::VSTRD: 1250 case ARM::VSTRS: 1251 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() && 1252 MI.getOperand(2).getImm() == 0) { 1253 FrameIndex = MI.getOperand(1).getIndex(); 1254 return MI.getOperand(0).getReg(); 1255 } 1256 break; 1257 case ARM::VSTR_P0_off: 1258 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() && 1259 MI.getOperand(1).getImm() == 0) { 1260 FrameIndex = MI.getOperand(0).getIndex(); 1261 return ARM::P0; 1262 } 1263 break; 1264 case ARM::VST1q64: 1265 case ARM::VST1d64TPseudo: 1266 case ARM::VST1d64QPseudo: 1267 if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) { 1268 FrameIndex = MI.getOperand(0).getIndex(); 1269 return MI.getOperand(2).getReg(); 1270 } 1271 break; 1272 case ARM::VSTMQIA: 1273 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) { 1274 FrameIndex = MI.getOperand(1).getIndex(); 1275 return MI.getOperand(0).getReg(); 1276 } 1277 break; 1278 } 1279 1280 return 0; 1281 } 1282 1283 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI, 1284 int &FrameIndex) const { 1285 SmallVector<const MachineMemOperand *, 1> Accesses; 1286 if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) && 1287 Accesses.size() == 1) { 1288 FrameIndex = 1289 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue()) 1290 ->getFrameIndex(); 1291 return true; 1292 } 1293 return false; 1294 } 1295 1296 void ARMBaseInstrInfo:: 1297 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, 1298 Register DestReg, int FI, 1299 const TargetRegisterClass *RC, 1300 const TargetRegisterInfo *TRI) const { 1301 DebugLoc DL; 1302 if (I != MBB.end()) DL = I->getDebugLoc(); 1303 MachineFunction &MF = *MBB.getParent(); 1304 MachineFrameInfo &MFI = MF.getFrameInfo(); 1305 const Align Alignment = MFI.getObjectAlign(FI); 1306 MachineMemOperand *MMO = MF.getMachineMemOperand( 1307 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad, 1308 MFI.getObjectSize(FI), Alignment); 1309 1310 switch (TRI->getSpillSize(*RC)) { 1311 case 2: 1312 if (ARM::HPRRegClass.hasSubClassEq(RC)) { 1313 BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg) 1314 .addFrameIndex(FI) 1315 .addImm(0) 1316 .addMemOperand(MMO) 1317 .add(predOps(ARMCC::AL)); 1318 } else 1319 llvm_unreachable("Unknown reg class!"); 1320 break; 1321 case 4: 1322 if (ARM::GPRRegClass.hasSubClassEq(RC)) { 1323 BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg) 1324 .addFrameIndex(FI) 1325 .addImm(0) 1326 .addMemOperand(MMO) 1327 .add(predOps(ARMCC::AL)); 1328 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) { 1329 BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg) 1330 .addFrameIndex(FI) 1331 .addImm(0) 1332 .addMemOperand(MMO) 1333 .add(predOps(ARMCC::AL)); 1334 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) { 1335 BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg) 1336 .addFrameIndex(FI) 1337 .addImm(0) 1338 .addMemOperand(MMO) 1339 .add(predOps(ARMCC::AL)); 1340 } else 1341 llvm_unreachable("Unknown reg class!"); 1342 break; 1343 case 8: 1344 if (ARM::DPRRegClass.hasSubClassEq(RC)) { 1345 BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg) 1346 .addFrameIndex(FI) 1347 .addImm(0) 1348 .addMemOperand(MMO) 1349 .add(predOps(ARMCC::AL)); 1350 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) { 1351 MachineInstrBuilder MIB; 1352 1353 if (Subtarget.hasV5TEOps()) { 1354 MIB = BuildMI(MBB, I, DL, get(ARM::LDRD)); 1355 AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI); 1356 AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI); 1357 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO) 1358 .add(predOps(ARMCC::AL)); 1359 } else { 1360 // Fallback to LDM instruction, which has existed since the dawn of 1361 // time. 1362 MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA)) 1363 .addFrameIndex(FI) 1364 .addMemOperand(MMO) 1365 .add(predOps(ARMCC::AL)); 1366 MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI); 1367 MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI); 1368 } 1369 1370 if (Register::isPhysicalRegister(DestReg)) 1371 MIB.addReg(DestReg, RegState::ImplicitDefine); 1372 } else 1373 llvm_unreachable("Unknown reg class!"); 1374 break; 1375 case 16: 1376 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) { 1377 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) { 1378 BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg) 1379 .addFrameIndex(FI) 1380 .addImm(16) 1381 .addMemOperand(MMO) 1382 .add(predOps(ARMCC::AL)); 1383 } else { 1384 BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg) 1385 .addFrameIndex(FI) 1386 .addMemOperand(MMO) 1387 .add(predOps(ARMCC::AL)); 1388 } 1389 } else if (ARM::QPRRegClass.hasSubClassEq(RC) && 1390 Subtarget.hasMVEIntegerOps()) { 1391 auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg); 1392 MIB.addFrameIndex(FI) 1393 .addImm(0) 1394 .addMemOperand(MMO); 1395 addUnpredicatedMveVpredNOp(MIB); 1396 } else 1397 llvm_unreachable("Unknown reg class!"); 1398 break; 1399 case 24: 1400 if (ARM::DTripleRegClass.hasSubClassEq(RC)) { 1401 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1402 Subtarget.hasNEON()) { 1403 BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg) 1404 .addFrameIndex(FI) 1405 .addImm(16) 1406 .addMemOperand(MMO) 1407 .add(predOps(ARMCC::AL)); 1408 } else { 1409 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) 1410 .addFrameIndex(FI) 1411 .addMemOperand(MMO) 1412 .add(predOps(ARMCC::AL)); 1413 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); 1414 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); 1415 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); 1416 if (Register::isPhysicalRegister(DestReg)) 1417 MIB.addReg(DestReg, RegState::ImplicitDefine); 1418 } 1419 } else 1420 llvm_unreachable("Unknown reg class!"); 1421 break; 1422 case 32: 1423 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) { 1424 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) && 1425 Subtarget.hasNEON()) { 1426 BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg) 1427 .addFrameIndex(FI) 1428 .addImm(16) 1429 .addMemOperand(MMO) 1430 .add(predOps(ARMCC::AL)); 1431 } else { 1432 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) 1433 .addFrameIndex(FI) 1434 .add(predOps(ARMCC::AL)) 1435 .addMemOperand(MMO); 1436 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); 1437 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); 1438 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); 1439 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI); 1440 if (Register::isPhysicalRegister(DestReg)) 1441 MIB.addReg(DestReg, RegState::ImplicitDefine); 1442 } 1443 } else 1444 llvm_unreachable("Unknown reg class!"); 1445 break; 1446 case 64: 1447 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) { 1448 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA)) 1449 .addFrameIndex(FI) 1450 .add(predOps(ARMCC::AL)) 1451 .addMemOperand(MMO); 1452 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI); 1453 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI); 1454 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI); 1455 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI); 1456 MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI); 1457 MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI); 1458 MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI); 1459 MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI); 1460 if (Register::isPhysicalRegister(DestReg)) 1461 MIB.addReg(DestReg, RegState::ImplicitDefine); 1462 } else 1463 llvm_unreachable("Unknown reg class!"); 1464 break; 1465 default: 1466 llvm_unreachable("Unknown regclass!"); 1467 } 1468 } 1469 1470 unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI, 1471 int &FrameIndex) const { 1472 switch (MI.getOpcode()) { 1473 default: break; 1474 case ARM::LDRrs: 1475 case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame. 1476 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() && 1477 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 && 1478 MI.getOperand(3).getImm() == 0) { 1479 FrameIndex = MI.getOperand(1).getIndex(); 1480 return MI.getOperand(0).getReg(); 1481 } 1482 break; 1483 case ARM::LDRi12: 1484 case ARM::t2LDRi12: 1485 case ARM::tLDRspi: 1486 case ARM::VLDRD: 1487 case ARM::VLDRS: 1488 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() && 1489 MI.getOperand(2).getImm() == 0) { 1490 FrameIndex = MI.getOperand(1).getIndex(); 1491 return MI.getOperand(0).getReg(); 1492 } 1493 break; 1494 case ARM::VLDR_P0_off: 1495 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() && 1496 MI.getOperand(1).getImm() == 0) { 1497 FrameIndex = MI.getOperand(0).getIndex(); 1498 return ARM::P0; 1499 } 1500 break; 1501 case ARM::VLD1q64: 1502 case ARM::VLD1d8TPseudo: 1503 case ARM::VLD1d16TPseudo: 1504 case ARM::VLD1d32TPseudo: 1505 case ARM::VLD1d64TPseudo: 1506 case ARM::VLD1d8QPseudo: 1507 case ARM::VLD1d16QPseudo: 1508 case ARM::VLD1d32QPseudo: 1509 case ARM::VLD1d64QPseudo: 1510 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) { 1511 FrameIndex = MI.getOperand(1).getIndex(); 1512 return MI.getOperand(0).getReg(); 1513 } 1514 break; 1515 case ARM::VLDMQIA: 1516 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) { 1517 FrameIndex = MI.getOperand(1).getIndex(); 1518 return MI.getOperand(0).getReg(); 1519 } 1520 break; 1521 } 1522 1523 return 0; 1524 } 1525 1526 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI, 1527 int &FrameIndex) const { 1528 SmallVector<const MachineMemOperand *, 1> Accesses; 1529 if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) && 1530 Accesses.size() == 1) { 1531 FrameIndex = 1532 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue()) 1533 ->getFrameIndex(); 1534 return true; 1535 } 1536 return false; 1537 } 1538 1539 /// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD 1540 /// depending on whether the result is used. 1541 void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const { 1542 bool isThumb1 = Subtarget.isThumb1Only(); 1543 bool isThumb2 = Subtarget.isThumb2(); 1544 const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo(); 1545 1546 DebugLoc dl = MI->getDebugLoc(); 1547 MachineBasicBlock *BB = MI->getParent(); 1548 1549 MachineInstrBuilder LDM, STM; 1550 if (isThumb1 || !MI->getOperand(1).isDead()) { 1551 MachineOperand LDWb(MI->getOperand(1)); 1552 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD 1553 : isThumb1 ? ARM::tLDMIA_UPD 1554 : ARM::LDMIA_UPD)) 1555 .add(LDWb); 1556 } else { 1557 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA)); 1558 } 1559 1560 if (isThumb1 || !MI->getOperand(0).isDead()) { 1561 MachineOperand STWb(MI->getOperand(0)); 1562 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD 1563 : isThumb1 ? ARM::tSTMIA_UPD 1564 : ARM::STMIA_UPD)) 1565 .add(STWb); 1566 } else { 1567 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA)); 1568 } 1569 1570 MachineOperand LDBase(MI->getOperand(3)); 1571 LDM.add(LDBase).add(predOps(ARMCC::AL)); 1572 1573 MachineOperand STBase(MI->getOperand(2)); 1574 STM.add(STBase).add(predOps(ARMCC::AL)); 1575 1576 // Sort the scratch registers into ascending order. 1577 const TargetRegisterInfo &TRI = getRegisterInfo(); 1578 SmallVector<unsigned, 6> ScratchRegs; 1579 for(unsigned I = 5; I < MI->getNumOperands(); ++I) 1580 ScratchRegs.push_back(MI->getOperand(I).getReg()); 1581 llvm::sort(ScratchRegs, 1582 [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool { 1583 return TRI.getEncodingValue(Reg1) < 1584 TRI.getEncodingValue(Reg2); 1585 }); 1586 1587 for (const auto &Reg : ScratchRegs) { 1588 LDM.addReg(Reg, RegState::Define); 1589 STM.addReg(Reg, RegState::Kill); 1590 } 1591 1592 BB->erase(MI); 1593 } 1594 1595 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const { 1596 if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) { 1597 assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() && 1598 "LOAD_STACK_GUARD currently supported only for MachO."); 1599 expandLoadStackGuard(MI); 1600 MI.getParent()->erase(MI); 1601 return true; 1602 } 1603 1604 if (MI.getOpcode() == ARM::MEMCPY) { 1605 expandMEMCPY(MI); 1606 return true; 1607 } 1608 1609 // This hook gets to expand COPY instructions before they become 1610 // copyPhysReg() calls. Look for VMOVS instructions that can legally be 1611 // widened to VMOVD. We prefer the VMOVD when possible because it may be 1612 // changed into a VORR that can go down the NEON pipeline. 1613 if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64()) 1614 return false; 1615 1616 // Look for a copy between even S-registers. That is where we keep floats 1617 // when using NEON v2f32 instructions for f32 arithmetic. 1618 Register DstRegS = MI.getOperand(0).getReg(); 1619 Register SrcRegS = MI.getOperand(1).getReg(); 1620 if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS)) 1621 return false; 1622 1623 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1624 unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0, 1625 &ARM::DPRRegClass); 1626 unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0, 1627 &ARM::DPRRegClass); 1628 if (!DstRegD || !SrcRegD) 1629 return false; 1630 1631 // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only 1632 // legal if the COPY already defines the full DstRegD, and it isn't a 1633 // sub-register insertion. 1634 if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI)) 1635 return false; 1636 1637 // A dead copy shouldn't show up here, but reject it just in case. 1638 if (MI.getOperand(0).isDead()) 1639 return false; 1640 1641 // All clear, widen the COPY. 1642 LLVM_DEBUG(dbgs() << "widening: " << MI); 1643 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI); 1644 1645 // Get rid of the old implicit-def of DstRegD. Leave it if it defines a Q-reg 1646 // or some other super-register. 1647 int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD); 1648 if (ImpDefIdx != -1) 1649 MI.RemoveOperand(ImpDefIdx); 1650 1651 // Change the opcode and operands. 1652 MI.setDesc(get(ARM::VMOVD)); 1653 MI.getOperand(0).setReg(DstRegD); 1654 MI.getOperand(1).setReg(SrcRegD); 1655 MIB.add(predOps(ARMCC::AL)); 1656 1657 // We are now reading SrcRegD instead of SrcRegS. This may upset the 1658 // register scavenger and machine verifier, so we need to indicate that we 1659 // are reading an undefined value from SrcRegD, but a proper value from 1660 // SrcRegS. 1661 MI.getOperand(1).setIsUndef(); 1662 MIB.addReg(SrcRegS, RegState::Implicit); 1663 1664 // SrcRegD may actually contain an unrelated value in the ssub_1 1665 // sub-register. Don't kill it. Only kill the ssub_0 sub-register. 1666 if (MI.getOperand(1).isKill()) { 1667 MI.getOperand(1).setIsKill(false); 1668 MI.addRegisterKilled(SrcRegS, TRI, true); 1669 } 1670 1671 LLVM_DEBUG(dbgs() << "replaced by: " << MI); 1672 return true; 1673 } 1674 1675 /// Create a copy of a const pool value. Update CPI to the new index and return 1676 /// the label UID. 1677 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) { 1678 MachineConstantPool *MCP = MF.getConstantPool(); 1679 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1680 1681 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI]; 1682 assert(MCPE.isMachineConstantPoolEntry() && 1683 "Expecting a machine constantpool entry!"); 1684 ARMConstantPoolValue *ACPV = 1685 static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal); 1686 1687 unsigned PCLabelId = AFI->createPICLabelUId(); 1688 ARMConstantPoolValue *NewCPV = nullptr; 1689 1690 // FIXME: The below assumes PIC relocation model and that the function 1691 // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and 1692 // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR 1693 // instructions, so that's probably OK, but is PIC always correct when 1694 // we get here? 1695 if (ACPV->isGlobalValue()) 1696 NewCPV = ARMConstantPoolConstant::Create( 1697 cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue, 1698 4, ACPV->getModifier(), ACPV->mustAddCurrentAddress()); 1699 else if (ACPV->isExtSymbol()) 1700 NewCPV = ARMConstantPoolSymbol:: 1701 Create(MF.getFunction().getContext(), 1702 cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4); 1703 else if (ACPV->isBlockAddress()) 1704 NewCPV = ARMConstantPoolConstant:: 1705 Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId, 1706 ARMCP::CPBlockAddress, 4); 1707 else if (ACPV->isLSDA()) 1708 NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId, 1709 ARMCP::CPLSDA, 4); 1710 else if (ACPV->isMachineBasicBlock()) 1711 NewCPV = ARMConstantPoolMBB:: 1712 Create(MF.getFunction().getContext(), 1713 cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4); 1714 else 1715 llvm_unreachable("Unexpected ARM constantpool value type!!"); 1716 CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlign()); 1717 return PCLabelId; 1718 } 1719 1720 void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB, 1721 MachineBasicBlock::iterator I, 1722 Register DestReg, unsigned SubIdx, 1723 const MachineInstr &Orig, 1724 const TargetRegisterInfo &TRI) const { 1725 unsigned Opcode = Orig.getOpcode(); 1726 switch (Opcode) { 1727 default: { 1728 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig); 1729 MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI); 1730 MBB.insert(I, MI); 1731 break; 1732 } 1733 case ARM::tLDRpci_pic: 1734 case ARM::t2LDRpci_pic: { 1735 MachineFunction &MF = *MBB.getParent(); 1736 unsigned CPI = Orig.getOperand(1).getIndex(); 1737 unsigned PCLabelId = duplicateCPV(MF, CPI); 1738 BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg) 1739 .addConstantPoolIndex(CPI) 1740 .addImm(PCLabelId) 1741 .cloneMemRefs(Orig); 1742 break; 1743 } 1744 } 1745 } 1746 1747 MachineInstr & 1748 ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB, 1749 MachineBasicBlock::iterator InsertBefore, 1750 const MachineInstr &Orig) const { 1751 MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig); 1752 MachineBasicBlock::instr_iterator I = Cloned.getIterator(); 1753 for (;;) { 1754 switch (I->getOpcode()) { 1755 case ARM::tLDRpci_pic: 1756 case ARM::t2LDRpci_pic: { 1757 MachineFunction &MF = *MBB.getParent(); 1758 unsigned CPI = I->getOperand(1).getIndex(); 1759 unsigned PCLabelId = duplicateCPV(MF, CPI); 1760 I->getOperand(1).setIndex(CPI); 1761 I->getOperand(2).setImm(PCLabelId); 1762 break; 1763 } 1764 } 1765 if (!I->isBundledWithSucc()) 1766 break; 1767 ++I; 1768 } 1769 return Cloned; 1770 } 1771 1772 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0, 1773 const MachineInstr &MI1, 1774 const MachineRegisterInfo *MRI) const { 1775 unsigned Opcode = MI0.getOpcode(); 1776 if (Opcode == ARM::t2LDRpci || 1777 Opcode == ARM::t2LDRpci_pic || 1778 Opcode == ARM::tLDRpci || 1779 Opcode == ARM::tLDRpci_pic || 1780 Opcode == ARM::LDRLIT_ga_pcrel || 1781 Opcode == ARM::LDRLIT_ga_pcrel_ldr || 1782 Opcode == ARM::tLDRLIT_ga_pcrel || 1783 Opcode == ARM::MOV_ga_pcrel || 1784 Opcode == ARM::MOV_ga_pcrel_ldr || 1785 Opcode == ARM::t2MOV_ga_pcrel) { 1786 if (MI1.getOpcode() != Opcode) 1787 return false; 1788 if (MI0.getNumOperands() != MI1.getNumOperands()) 1789 return false; 1790 1791 const MachineOperand &MO0 = MI0.getOperand(1); 1792 const MachineOperand &MO1 = MI1.getOperand(1); 1793 if (MO0.getOffset() != MO1.getOffset()) 1794 return false; 1795 1796 if (Opcode == ARM::LDRLIT_ga_pcrel || 1797 Opcode == ARM::LDRLIT_ga_pcrel_ldr || 1798 Opcode == ARM::tLDRLIT_ga_pcrel || 1799 Opcode == ARM::MOV_ga_pcrel || 1800 Opcode == ARM::MOV_ga_pcrel_ldr || 1801 Opcode == ARM::t2MOV_ga_pcrel) 1802 // Ignore the PC labels. 1803 return MO0.getGlobal() == MO1.getGlobal(); 1804 1805 const MachineFunction *MF = MI0.getParent()->getParent(); 1806 const MachineConstantPool *MCP = MF->getConstantPool(); 1807 int CPI0 = MO0.getIndex(); 1808 int CPI1 = MO1.getIndex(); 1809 const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0]; 1810 const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1]; 1811 bool isARMCP0 = MCPE0.isMachineConstantPoolEntry(); 1812 bool isARMCP1 = MCPE1.isMachineConstantPoolEntry(); 1813 if (isARMCP0 && isARMCP1) { 1814 ARMConstantPoolValue *ACPV0 = 1815 static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal); 1816 ARMConstantPoolValue *ACPV1 = 1817 static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal); 1818 return ACPV0->hasSameValue(ACPV1); 1819 } else if (!isARMCP0 && !isARMCP1) { 1820 return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal; 1821 } 1822 return false; 1823 } else if (Opcode == ARM::PICLDR) { 1824 if (MI1.getOpcode() != Opcode) 1825 return false; 1826 if (MI0.getNumOperands() != MI1.getNumOperands()) 1827 return false; 1828 1829 Register Addr0 = MI0.getOperand(1).getReg(); 1830 Register Addr1 = MI1.getOperand(1).getReg(); 1831 if (Addr0 != Addr1) { 1832 if (!MRI || !Register::isVirtualRegister(Addr0) || 1833 !Register::isVirtualRegister(Addr1)) 1834 return false; 1835 1836 // This assumes SSA form. 1837 MachineInstr *Def0 = MRI->getVRegDef(Addr0); 1838 MachineInstr *Def1 = MRI->getVRegDef(Addr1); 1839 // Check if the loaded value, e.g. a constantpool of a global address, are 1840 // the same. 1841 if (!produceSameValue(*Def0, *Def1, MRI)) 1842 return false; 1843 } 1844 1845 for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) { 1846 // %12 = PICLDR %11, 0, 14, %noreg 1847 const MachineOperand &MO0 = MI0.getOperand(i); 1848 const MachineOperand &MO1 = MI1.getOperand(i); 1849 if (!MO0.isIdenticalTo(MO1)) 1850 return false; 1851 } 1852 return true; 1853 } 1854 1855 return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs); 1856 } 1857 1858 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to 1859 /// determine if two loads are loading from the same base address. It should 1860 /// only return true if the base pointers are the same and the only differences 1861 /// between the two addresses is the offset. It also returns the offsets by 1862 /// reference. 1863 /// 1864 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched 1865 /// is permanently disabled. 1866 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, 1867 int64_t &Offset1, 1868 int64_t &Offset2) const { 1869 // Don't worry about Thumb: just ARM and Thumb2. 1870 if (Subtarget.isThumb1Only()) return false; 1871 1872 if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode()) 1873 return false; 1874 1875 switch (Load1->getMachineOpcode()) { 1876 default: 1877 return false; 1878 case ARM::LDRi12: 1879 case ARM::LDRBi12: 1880 case ARM::LDRD: 1881 case ARM::LDRH: 1882 case ARM::LDRSB: 1883 case ARM::LDRSH: 1884 case ARM::VLDRD: 1885 case ARM::VLDRS: 1886 case ARM::t2LDRi8: 1887 case ARM::t2LDRBi8: 1888 case ARM::t2LDRDi8: 1889 case ARM::t2LDRSHi8: 1890 case ARM::t2LDRi12: 1891 case ARM::t2LDRBi12: 1892 case ARM::t2LDRSHi12: 1893 break; 1894 } 1895 1896 switch (Load2->getMachineOpcode()) { 1897 default: 1898 return false; 1899 case ARM::LDRi12: 1900 case ARM::LDRBi12: 1901 case ARM::LDRD: 1902 case ARM::LDRH: 1903 case ARM::LDRSB: 1904 case ARM::LDRSH: 1905 case ARM::VLDRD: 1906 case ARM::VLDRS: 1907 case ARM::t2LDRi8: 1908 case ARM::t2LDRBi8: 1909 case ARM::t2LDRSHi8: 1910 case ARM::t2LDRi12: 1911 case ARM::t2LDRBi12: 1912 case ARM::t2LDRSHi12: 1913 break; 1914 } 1915 1916 // Check if base addresses and chain operands match. 1917 if (Load1->getOperand(0) != Load2->getOperand(0) || 1918 Load1->getOperand(4) != Load2->getOperand(4)) 1919 return false; 1920 1921 // Index should be Reg0. 1922 if (Load1->getOperand(3) != Load2->getOperand(3)) 1923 return false; 1924 1925 // Determine the offsets. 1926 if (isa<ConstantSDNode>(Load1->getOperand(1)) && 1927 isa<ConstantSDNode>(Load2->getOperand(1))) { 1928 Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue(); 1929 Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue(); 1930 return true; 1931 } 1932 1933 return false; 1934 } 1935 1936 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to 1937 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should 1938 /// be scheduled togther. On some targets if two loads are loading from 1939 /// addresses in the same cache line, it's better if they are scheduled 1940 /// together. This function takes two integers that represent the load offsets 1941 /// from the common base address. It returns true if it decides it's desirable 1942 /// to schedule the two loads together. "NumLoads" is the number of loads that 1943 /// have already been scheduled after Load1. 1944 /// 1945 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched 1946 /// is permanently disabled. 1947 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2, 1948 int64_t Offset1, int64_t Offset2, 1949 unsigned NumLoads) const { 1950 // Don't worry about Thumb: just ARM and Thumb2. 1951 if (Subtarget.isThumb1Only()) return false; 1952 1953 assert(Offset2 > Offset1); 1954 1955 if ((Offset2 - Offset1) / 8 > 64) 1956 return false; 1957 1958 // Check if the machine opcodes are different. If they are different 1959 // then we consider them to not be of the same base address, 1960 // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12. 1961 // In this case, they are considered to be the same because they are different 1962 // encoding forms of the same basic instruction. 1963 if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) && 1964 !((Load1->getMachineOpcode() == ARM::t2LDRBi8 && 1965 Load2->getMachineOpcode() == ARM::t2LDRBi12) || 1966 (Load1->getMachineOpcode() == ARM::t2LDRBi12 && 1967 Load2->getMachineOpcode() == ARM::t2LDRBi8))) 1968 return false; // FIXME: overly conservative? 1969 1970 // Four loads in a row should be sufficient. 1971 if (NumLoads >= 3) 1972 return false; 1973 1974 return true; 1975 } 1976 1977 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI, 1978 const MachineBasicBlock *MBB, 1979 const MachineFunction &MF) const { 1980 // Debug info is never a scheduling boundary. It's necessary to be explicit 1981 // due to the special treatment of IT instructions below, otherwise a 1982 // dbg_value followed by an IT will result in the IT instruction being 1983 // considered a scheduling hazard, which is wrong. It should be the actual 1984 // instruction preceding the dbg_value instruction(s), just like it is 1985 // when debug info is not present. 1986 if (MI.isDebugInstr()) 1987 return false; 1988 1989 // Terminators and labels can't be scheduled around. 1990 if (MI.isTerminator() || MI.isPosition()) 1991 return true; 1992 1993 // INLINEASM_BR can jump to another block 1994 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) 1995 return true; 1996 1997 // Treat the start of the IT block as a scheduling boundary, but schedule 1998 // t2IT along with all instructions following it. 1999 // FIXME: This is a big hammer. But the alternative is to add all potential 2000 // true and anti dependencies to IT block instructions as implicit operands 2001 // to the t2IT instruction. The added compile time and complexity does not 2002 // seem worth it. 2003 MachineBasicBlock::const_iterator I = MI; 2004 // Make sure to skip any debug instructions 2005 while (++I != MBB->end() && I->isDebugInstr()) 2006 ; 2007 if (I != MBB->end() && I->getOpcode() == ARM::t2IT) 2008 return true; 2009 2010 // Don't attempt to schedule around any instruction that defines 2011 // a stack-oriented pointer, as it's unlikely to be profitable. This 2012 // saves compile time, because it doesn't require every single 2013 // stack slot reference to depend on the instruction that does the 2014 // modification. 2015 // Calls don't actually change the stack pointer, even if they have imp-defs. 2016 // No ARM calling conventions change the stack pointer. (X86 calling 2017 // conventions sometimes do). 2018 if (!MI.isCall() && MI.definesRegister(ARM::SP)) 2019 return true; 2020 2021 return false; 2022 } 2023 2024 bool ARMBaseInstrInfo:: 2025 isProfitableToIfCvt(MachineBasicBlock &MBB, 2026 unsigned NumCycles, unsigned ExtraPredCycles, 2027 BranchProbability Probability) const { 2028 if (!NumCycles) 2029 return false; 2030 2031 // If we are optimizing for size, see if the branch in the predecessor can be 2032 // lowered to cbn?z by the constant island lowering pass, and return false if 2033 // so. This results in a shorter instruction sequence. 2034 if (MBB.getParent()->getFunction().hasOptSize()) { 2035 MachineBasicBlock *Pred = *MBB.pred_begin(); 2036 if (!Pred->empty()) { 2037 MachineInstr *LastMI = &*Pred->rbegin(); 2038 if (LastMI->getOpcode() == ARM::t2Bcc) { 2039 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2040 MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI); 2041 if (CmpMI) 2042 return false; 2043 } 2044 } 2045 } 2046 return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles, 2047 MBB, 0, 0, Probability); 2048 } 2049 2050 bool ARMBaseInstrInfo:: 2051 isProfitableToIfCvt(MachineBasicBlock &TBB, 2052 unsigned TCycles, unsigned TExtra, 2053 MachineBasicBlock &FBB, 2054 unsigned FCycles, unsigned FExtra, 2055 BranchProbability Probability) const { 2056 if (!TCycles) 2057 return false; 2058 2059 // In thumb code we often end up trading one branch for a IT block, and 2060 // if we are cloning the instruction can increase code size. Prevent 2061 // blocks with multiple predecesors from being ifcvted to prevent this 2062 // cloning. 2063 if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) { 2064 if (TBB.pred_size() != 1 || FBB.pred_size() != 1) 2065 return false; 2066 } 2067 2068 // Attempt to estimate the relative costs of predication versus branching. 2069 // Here we scale up each component of UnpredCost to avoid precision issue when 2070 // scaling TCycles/FCycles by Probability. 2071 const unsigned ScalingUpFactor = 1024; 2072 2073 unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor; 2074 unsigned UnpredCost; 2075 if (!Subtarget.hasBranchPredictor()) { 2076 // When we don't have a branch predictor it's always cheaper to not take a 2077 // branch than take it, so we have to take that into account. 2078 unsigned NotTakenBranchCost = 1; 2079 unsigned TakenBranchCost = Subtarget.getMispredictionPenalty(); 2080 unsigned TUnpredCycles, FUnpredCycles; 2081 if (!FCycles) { 2082 // Triangle: TBB is the fallthrough 2083 TUnpredCycles = TCycles + NotTakenBranchCost; 2084 FUnpredCycles = TakenBranchCost; 2085 } else { 2086 // Diamond: TBB is the block that is branched to, FBB is the fallthrough 2087 TUnpredCycles = TCycles + TakenBranchCost; 2088 FUnpredCycles = FCycles + NotTakenBranchCost; 2089 // The branch at the end of FBB will disappear when it's predicated, so 2090 // discount it from PredCost. 2091 PredCost -= 1 * ScalingUpFactor; 2092 } 2093 // The total cost is the cost of each path scaled by their probabilites 2094 unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor); 2095 unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor); 2096 UnpredCost = TUnpredCost + FUnpredCost; 2097 // When predicating assume that the first IT can be folded away but later 2098 // ones cost one cycle each 2099 if (Subtarget.isThumb2() && TCycles + FCycles > 4) { 2100 PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor; 2101 } 2102 } else { 2103 unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor); 2104 unsigned FUnpredCost = 2105 Probability.getCompl().scale(FCycles * ScalingUpFactor); 2106 UnpredCost = TUnpredCost + FUnpredCost; 2107 UnpredCost += 1 * ScalingUpFactor; // The branch itself 2108 UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10; 2109 } 2110 2111 return PredCost <= UnpredCost; 2112 } 2113 2114 unsigned 2115 ARMBaseInstrInfo::extraSizeToPredicateInstructions(const MachineFunction &MF, 2116 unsigned NumInsts) const { 2117 // Thumb2 needs a 2-byte IT instruction to predicate up to 4 instructions. 2118 // ARM has a condition code field in every predicable instruction, using it 2119 // doesn't change code size. 2120 if (!Subtarget.isThumb2()) 2121 return 0; 2122 2123 // It's possible that the size of the IT is restricted to a single block. 2124 unsigned MaxInsts = Subtarget.restrictIT() ? 1 : 4; 2125 return divideCeil(NumInsts, MaxInsts) * 2; 2126 } 2127 2128 unsigned 2129 ARMBaseInstrInfo::predictBranchSizeForIfCvt(MachineInstr &MI) const { 2130 // If this branch is likely to be folded into the comparison to form a 2131 // CB(N)Z, then removing it won't reduce code size at all, because that will 2132 // just replace the CB(N)Z with a CMP. 2133 if (MI.getOpcode() == ARM::t2Bcc && 2134 findCMPToFoldIntoCBZ(&MI, &getRegisterInfo())) 2135 return 0; 2136 2137 unsigned Size = getInstSizeInBytes(MI); 2138 2139 // For Thumb2, all branches are 32-bit instructions during the if conversion 2140 // pass, but may be replaced with 16-bit instructions during size reduction. 2141 // Since the branches considered by if conversion tend to be forward branches 2142 // over small basic blocks, they are very likely to be in range for the 2143 // narrow instructions, so we assume the final code size will be half what it 2144 // currently is. 2145 if (Subtarget.isThumb2()) 2146 Size /= 2; 2147 2148 return Size; 2149 } 2150 2151 bool 2152 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB, 2153 MachineBasicBlock &FMBB) const { 2154 // Reduce false anti-dependencies to let the target's out-of-order execution 2155 // engine do its thing. 2156 return Subtarget.isProfitableToUnpredicate(); 2157 } 2158 2159 /// getInstrPredicate - If instruction is predicated, returns its predicate 2160 /// condition, otherwise returns AL. It also returns the condition code 2161 /// register by reference. 2162 ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI, 2163 Register &PredReg) { 2164 int PIdx = MI.findFirstPredOperandIdx(); 2165 if (PIdx == -1) { 2166 PredReg = 0; 2167 return ARMCC::AL; 2168 } 2169 2170 PredReg = MI.getOperand(PIdx+1).getReg(); 2171 return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm(); 2172 } 2173 2174 unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) { 2175 if (Opc == ARM::B) 2176 return ARM::Bcc; 2177 if (Opc == ARM::tB) 2178 return ARM::tBcc; 2179 if (Opc == ARM::t2B) 2180 return ARM::t2Bcc; 2181 2182 llvm_unreachable("Unknown unconditional branch opcode!"); 2183 } 2184 2185 MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI, 2186 bool NewMI, 2187 unsigned OpIdx1, 2188 unsigned OpIdx2) const { 2189 switch (MI.getOpcode()) { 2190 case ARM::MOVCCr: 2191 case ARM::t2MOVCCr: { 2192 // MOVCC can be commuted by inverting the condition. 2193 Register PredReg; 2194 ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg); 2195 // MOVCC AL can't be inverted. Shouldn't happen. 2196 if (CC == ARMCC::AL || PredReg != ARM::CPSR) 2197 return nullptr; 2198 MachineInstr *CommutedMI = 2199 TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 2200 if (!CommutedMI) 2201 return nullptr; 2202 // After swapping the MOVCC operands, also invert the condition. 2203 CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx()) 2204 .setImm(ARMCC::getOppositeCondition(CC)); 2205 return CommutedMI; 2206 } 2207 } 2208 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 2209 } 2210 2211 /// Identify instructions that can be folded into a MOVCC instruction, and 2212 /// return the defining instruction. 2213 MachineInstr * 2214 ARMBaseInstrInfo::canFoldIntoMOVCC(Register Reg, const MachineRegisterInfo &MRI, 2215 const TargetInstrInfo *TII) const { 2216 if (!Reg.isVirtual()) 2217 return nullptr; 2218 if (!MRI.hasOneNonDBGUse(Reg)) 2219 return nullptr; 2220 MachineInstr *MI = MRI.getVRegDef(Reg); 2221 if (!MI) 2222 return nullptr; 2223 // Check if MI can be predicated and folded into the MOVCC. 2224 if (!isPredicable(*MI)) 2225 return nullptr; 2226 // Check if MI has any non-dead defs or physreg uses. This also detects 2227 // predicated instructions which will be reading CPSR. 2228 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) { 2229 const MachineOperand &MO = MI->getOperand(i); 2230 // Reject frame index operands, PEI can't handle the predicated pseudos. 2231 if (MO.isFI() || MO.isCPI() || MO.isJTI()) 2232 return nullptr; 2233 if (!MO.isReg()) 2234 continue; 2235 // MI can't have any tied operands, that would conflict with predication. 2236 if (MO.isTied()) 2237 return nullptr; 2238 if (Register::isPhysicalRegister(MO.getReg())) 2239 return nullptr; 2240 if (MO.isDef() && !MO.isDead()) 2241 return nullptr; 2242 } 2243 bool DontMoveAcrossStores = true; 2244 if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores)) 2245 return nullptr; 2246 return MI; 2247 } 2248 2249 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI, 2250 SmallVectorImpl<MachineOperand> &Cond, 2251 unsigned &TrueOp, unsigned &FalseOp, 2252 bool &Optimizable) const { 2253 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) && 2254 "Unknown select instruction"); 2255 // MOVCC operands: 2256 // 0: Def. 2257 // 1: True use. 2258 // 2: False use. 2259 // 3: Condition code. 2260 // 4: CPSR use. 2261 TrueOp = 1; 2262 FalseOp = 2; 2263 Cond.push_back(MI.getOperand(3)); 2264 Cond.push_back(MI.getOperand(4)); 2265 // We can always fold a def. 2266 Optimizable = true; 2267 return false; 2268 } 2269 2270 MachineInstr * 2271 ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI, 2272 SmallPtrSetImpl<MachineInstr *> &SeenMIs, 2273 bool PreferFalse) const { 2274 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) && 2275 "Unknown select instruction"); 2276 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 2277 MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this); 2278 bool Invert = !DefMI; 2279 if (!DefMI) 2280 DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this); 2281 if (!DefMI) 2282 return nullptr; 2283 2284 // Find new register class to use. 2285 MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1); 2286 Register DestReg = MI.getOperand(0).getReg(); 2287 const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg()); 2288 if (!MRI.constrainRegClass(DestReg, PreviousClass)) 2289 return nullptr; 2290 2291 // Create a new predicated version of DefMI. 2292 // Rfalse is the first use. 2293 MachineInstrBuilder NewMI = 2294 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg); 2295 2296 // Copy all the DefMI operands, excluding its (null) predicate. 2297 const MCInstrDesc &DefDesc = DefMI->getDesc(); 2298 for (unsigned i = 1, e = DefDesc.getNumOperands(); 2299 i != e && !DefDesc.OpInfo[i].isPredicate(); ++i) 2300 NewMI.add(DefMI->getOperand(i)); 2301 2302 unsigned CondCode = MI.getOperand(3).getImm(); 2303 if (Invert) 2304 NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode))); 2305 else 2306 NewMI.addImm(CondCode); 2307 NewMI.add(MI.getOperand(4)); 2308 2309 // DefMI is not the -S version that sets CPSR, so add an optional %noreg. 2310 if (NewMI->hasOptionalDef()) 2311 NewMI.add(condCodeOp()); 2312 2313 // The output register value when the predicate is false is an implicit 2314 // register operand tied to the first def. 2315 // The tie makes the register allocator ensure the FalseReg is allocated the 2316 // same register as operand 0. 2317 FalseReg.setImplicit(); 2318 NewMI.add(FalseReg); 2319 NewMI->tieOperands(0, NewMI->getNumOperands() - 1); 2320 2321 // Update SeenMIs set: register newly created MI and erase removed DefMI. 2322 SeenMIs.insert(NewMI); 2323 SeenMIs.erase(DefMI); 2324 2325 // If MI is inside a loop, and DefMI is outside the loop, then kill flags on 2326 // DefMI would be invalid when tranferred inside the loop. Checking for a 2327 // loop is expensive, but at least remove kill flags if they are in different 2328 // BBs. 2329 if (DefMI->getParent() != MI.getParent()) 2330 NewMI->clearKillInfo(); 2331 2332 // The caller will erase MI, but not DefMI. 2333 DefMI->eraseFromParent(); 2334 return NewMI; 2335 } 2336 2337 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the 2338 /// instruction is encoded with an 'S' bit is determined by the optional CPSR 2339 /// def operand. 2340 /// 2341 /// This will go away once we can teach tblgen how to set the optional CPSR def 2342 /// operand itself. 2343 struct AddSubFlagsOpcodePair { 2344 uint16_t PseudoOpc; 2345 uint16_t MachineOpc; 2346 }; 2347 2348 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = { 2349 {ARM::ADDSri, ARM::ADDri}, 2350 {ARM::ADDSrr, ARM::ADDrr}, 2351 {ARM::ADDSrsi, ARM::ADDrsi}, 2352 {ARM::ADDSrsr, ARM::ADDrsr}, 2353 2354 {ARM::SUBSri, ARM::SUBri}, 2355 {ARM::SUBSrr, ARM::SUBrr}, 2356 {ARM::SUBSrsi, ARM::SUBrsi}, 2357 {ARM::SUBSrsr, ARM::SUBrsr}, 2358 2359 {ARM::RSBSri, ARM::RSBri}, 2360 {ARM::RSBSrsi, ARM::RSBrsi}, 2361 {ARM::RSBSrsr, ARM::RSBrsr}, 2362 2363 {ARM::tADDSi3, ARM::tADDi3}, 2364 {ARM::tADDSi8, ARM::tADDi8}, 2365 {ARM::tADDSrr, ARM::tADDrr}, 2366 {ARM::tADCS, ARM::tADC}, 2367 2368 {ARM::tSUBSi3, ARM::tSUBi3}, 2369 {ARM::tSUBSi8, ARM::tSUBi8}, 2370 {ARM::tSUBSrr, ARM::tSUBrr}, 2371 {ARM::tSBCS, ARM::tSBC}, 2372 {ARM::tRSBS, ARM::tRSB}, 2373 {ARM::tLSLSri, ARM::tLSLri}, 2374 2375 {ARM::t2ADDSri, ARM::t2ADDri}, 2376 {ARM::t2ADDSrr, ARM::t2ADDrr}, 2377 {ARM::t2ADDSrs, ARM::t2ADDrs}, 2378 2379 {ARM::t2SUBSri, ARM::t2SUBri}, 2380 {ARM::t2SUBSrr, ARM::t2SUBrr}, 2381 {ARM::t2SUBSrs, ARM::t2SUBrs}, 2382 2383 {ARM::t2RSBSri, ARM::t2RSBri}, 2384 {ARM::t2RSBSrs, ARM::t2RSBrs}, 2385 }; 2386 2387 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) { 2388 for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i) 2389 if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc) 2390 return AddSubFlagsOpcodeMap[i].MachineOpc; 2391 return 0; 2392 } 2393 2394 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB, 2395 MachineBasicBlock::iterator &MBBI, 2396 const DebugLoc &dl, Register DestReg, 2397 Register BaseReg, int NumBytes, 2398 ARMCC::CondCodes Pred, Register PredReg, 2399 const ARMBaseInstrInfo &TII, 2400 unsigned MIFlags) { 2401 if (NumBytes == 0 && DestReg != BaseReg) { 2402 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg) 2403 .addReg(BaseReg, RegState::Kill) 2404 .add(predOps(Pred, PredReg)) 2405 .add(condCodeOp()) 2406 .setMIFlags(MIFlags); 2407 return; 2408 } 2409 2410 bool isSub = NumBytes < 0; 2411 if (isSub) NumBytes = -NumBytes; 2412 2413 while (NumBytes) { 2414 unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes); 2415 unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt); 2416 assert(ThisVal && "Didn't extract field correctly"); 2417 2418 // We will handle these bits from offset, clear them. 2419 NumBytes &= ~ThisVal; 2420 2421 assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?"); 2422 2423 // Build the new ADD / SUB. 2424 unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri; 2425 BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg) 2426 .addReg(BaseReg, RegState::Kill) 2427 .addImm(ThisVal) 2428 .add(predOps(Pred, PredReg)) 2429 .add(condCodeOp()) 2430 .setMIFlags(MIFlags); 2431 BaseReg = DestReg; 2432 } 2433 } 2434 2435 bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget, 2436 MachineFunction &MF, MachineInstr *MI, 2437 unsigned NumBytes) { 2438 // This optimisation potentially adds lots of load and store 2439 // micro-operations, it's only really a great benefit to code-size. 2440 if (!Subtarget.hasMinSize()) 2441 return false; 2442 2443 // If only one register is pushed/popped, LLVM can use an LDR/STR 2444 // instead. We can't modify those so make sure we're dealing with an 2445 // instruction we understand. 2446 bool IsPop = isPopOpcode(MI->getOpcode()); 2447 bool IsPush = isPushOpcode(MI->getOpcode()); 2448 if (!IsPush && !IsPop) 2449 return false; 2450 2451 bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD || 2452 MI->getOpcode() == ARM::VLDMDIA_UPD; 2453 bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH || 2454 MI->getOpcode() == ARM::tPOP || 2455 MI->getOpcode() == ARM::tPOP_RET; 2456 2457 assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP && 2458 MI->getOperand(1).getReg() == ARM::SP)) && 2459 "trying to fold sp update into non-sp-updating push/pop"); 2460 2461 // The VFP push & pop act on D-registers, so we can only fold an adjustment 2462 // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try 2463 // if this is violated. 2464 if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0) 2465 return false; 2466 2467 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+ 2468 // pred) so the list starts at 4. Thumb1 starts after the predicate. 2469 int RegListIdx = IsT1PushPop ? 2 : 4; 2470 2471 // Calculate the space we'll need in terms of registers. 2472 unsigned RegsNeeded; 2473 const TargetRegisterClass *RegClass; 2474 if (IsVFPPushPop) { 2475 RegsNeeded = NumBytes / 8; 2476 RegClass = &ARM::DPRRegClass; 2477 } else { 2478 RegsNeeded = NumBytes / 4; 2479 RegClass = &ARM::GPRRegClass; 2480 } 2481 2482 // We're going to have to strip all list operands off before 2483 // re-adding them since the order matters, so save the existing ones 2484 // for later. 2485 SmallVector<MachineOperand, 4> RegList; 2486 2487 // We're also going to need the first register transferred by this 2488 // instruction, which won't necessarily be the first register in the list. 2489 unsigned FirstRegEnc = -1; 2490 2491 const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo(); 2492 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) { 2493 MachineOperand &MO = MI->getOperand(i); 2494 RegList.push_back(MO); 2495 2496 if (MO.isReg() && !MO.isImplicit() && 2497 TRI->getEncodingValue(MO.getReg()) < FirstRegEnc) 2498 FirstRegEnc = TRI->getEncodingValue(MO.getReg()); 2499 } 2500 2501 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF); 2502 2503 // Now try to find enough space in the reglist to allocate NumBytes. 2504 for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded; 2505 --CurRegEnc) { 2506 unsigned CurReg = RegClass->getRegister(CurRegEnc); 2507 if (IsT1PushPop && CurRegEnc > TRI->getEncodingValue(ARM::R7)) 2508 continue; 2509 if (!IsPop) { 2510 // Pushing any register is completely harmless, mark the register involved 2511 // as undef since we don't care about its value and must not restore it 2512 // during stack unwinding. 2513 RegList.push_back(MachineOperand::CreateReg(CurReg, false, false, 2514 false, false, true)); 2515 --RegsNeeded; 2516 continue; 2517 } 2518 2519 // However, we can only pop an extra register if it's not live. For 2520 // registers live within the function we might clobber a return value 2521 // register; the other way a register can be live here is if it's 2522 // callee-saved. 2523 if (isCalleeSavedRegister(CurReg, CSRegs) || 2524 MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) != 2525 MachineBasicBlock::LQR_Dead) { 2526 // VFP pops don't allow holes in the register list, so any skip is fatal 2527 // for our transformation. GPR pops do, so we should just keep looking. 2528 if (IsVFPPushPop) 2529 return false; 2530 else 2531 continue; 2532 } 2533 2534 // Mark the unimportant registers as <def,dead> in the POP. 2535 RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false, 2536 true)); 2537 --RegsNeeded; 2538 } 2539 2540 if (RegsNeeded > 0) 2541 return false; 2542 2543 // Finally we know we can profitably perform the optimisation so go 2544 // ahead: strip all existing registers off and add them back again 2545 // in the right order. 2546 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) 2547 MI->RemoveOperand(i); 2548 2549 // Add the complete list back in. 2550 MachineInstrBuilder MIB(MF, &*MI); 2551 for (int i = RegList.size() - 1; i >= 0; --i) 2552 MIB.add(RegList[i]); 2553 2554 return true; 2555 } 2556 2557 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx, 2558 Register FrameReg, int &Offset, 2559 const ARMBaseInstrInfo &TII) { 2560 unsigned Opcode = MI.getOpcode(); 2561 const MCInstrDesc &Desc = MI.getDesc(); 2562 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask); 2563 bool isSub = false; 2564 2565 // Memory operands in inline assembly always use AddrMode2. 2566 if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR) 2567 AddrMode = ARMII::AddrMode2; 2568 2569 if (Opcode == ARM::ADDri) { 2570 Offset += MI.getOperand(FrameRegIdx+1).getImm(); 2571 if (Offset == 0) { 2572 // Turn it into a move. 2573 MI.setDesc(TII.get(ARM::MOVr)); 2574 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); 2575 MI.RemoveOperand(FrameRegIdx+1); 2576 Offset = 0; 2577 return true; 2578 } else if (Offset < 0) { 2579 Offset = -Offset; 2580 isSub = true; 2581 MI.setDesc(TII.get(ARM::SUBri)); 2582 } 2583 2584 // Common case: small offset, fits into instruction. 2585 if (ARM_AM::getSOImmVal(Offset) != -1) { 2586 // Replace the FrameIndex with sp / fp 2587 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); 2588 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset); 2589 Offset = 0; 2590 return true; 2591 } 2592 2593 // Otherwise, pull as much of the immedidate into this ADDri/SUBri 2594 // as possible. 2595 unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset); 2596 unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt); 2597 2598 // We will handle these bits from offset, clear them. 2599 Offset &= ~ThisImmVal; 2600 2601 // Get the properly encoded SOImmVal field. 2602 assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 && 2603 "Bit extraction didn't work?"); 2604 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal); 2605 } else { 2606 unsigned ImmIdx = 0; 2607 int InstrOffs = 0; 2608 unsigned NumBits = 0; 2609 unsigned Scale = 1; 2610 switch (AddrMode) { 2611 case ARMII::AddrMode_i12: 2612 ImmIdx = FrameRegIdx + 1; 2613 InstrOffs = MI.getOperand(ImmIdx).getImm(); 2614 NumBits = 12; 2615 break; 2616 case ARMII::AddrMode2: 2617 ImmIdx = FrameRegIdx+2; 2618 InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm()); 2619 if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2620 InstrOffs *= -1; 2621 NumBits = 12; 2622 break; 2623 case ARMII::AddrMode3: 2624 ImmIdx = FrameRegIdx+2; 2625 InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm()); 2626 if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2627 InstrOffs *= -1; 2628 NumBits = 8; 2629 break; 2630 case ARMII::AddrMode4: 2631 case ARMII::AddrMode6: 2632 // Can't fold any offset even if it's zero. 2633 return false; 2634 case ARMII::AddrMode5: 2635 ImmIdx = FrameRegIdx+1; 2636 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm()); 2637 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2638 InstrOffs *= -1; 2639 NumBits = 8; 2640 Scale = 4; 2641 break; 2642 case ARMII::AddrMode5FP16: 2643 ImmIdx = FrameRegIdx+1; 2644 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm()); 2645 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub) 2646 InstrOffs *= -1; 2647 NumBits = 8; 2648 Scale = 2; 2649 break; 2650 case ARMII::AddrModeT2_i7: 2651 case ARMII::AddrModeT2_i7s2: 2652 case ARMII::AddrModeT2_i7s4: 2653 ImmIdx = FrameRegIdx+1; 2654 InstrOffs = MI.getOperand(ImmIdx).getImm(); 2655 NumBits = 7; 2656 Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 : 2657 AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1); 2658 break; 2659 default: 2660 llvm_unreachable("Unsupported addressing mode!"); 2661 } 2662 2663 Offset += InstrOffs * Scale; 2664 assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!"); 2665 if (Offset < 0) { 2666 Offset = -Offset; 2667 isSub = true; 2668 } 2669 2670 // Attempt to fold address comp. if opcode has offset bits 2671 if (NumBits > 0) { 2672 // Common case: small offset, fits into instruction. 2673 MachineOperand &ImmOp = MI.getOperand(ImmIdx); 2674 int ImmedOffset = Offset / Scale; 2675 unsigned Mask = (1 << NumBits) - 1; 2676 if ((unsigned)Offset <= Mask * Scale) { 2677 // Replace the FrameIndex with sp 2678 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); 2679 // FIXME: When addrmode2 goes away, this will simplify (like the 2680 // T2 version), as the LDR.i12 versions don't need the encoding 2681 // tricks for the offset value. 2682 if (isSub) { 2683 if (AddrMode == ARMII::AddrMode_i12) 2684 ImmedOffset = -ImmedOffset; 2685 else 2686 ImmedOffset |= 1 << NumBits; 2687 } 2688 ImmOp.ChangeToImmediate(ImmedOffset); 2689 Offset = 0; 2690 return true; 2691 } 2692 2693 // Otherwise, it didn't fit. Pull in what we can to simplify the immed. 2694 ImmedOffset = ImmedOffset & Mask; 2695 if (isSub) { 2696 if (AddrMode == ARMII::AddrMode_i12) 2697 ImmedOffset = -ImmedOffset; 2698 else 2699 ImmedOffset |= 1 << NumBits; 2700 } 2701 ImmOp.ChangeToImmediate(ImmedOffset); 2702 Offset &= ~(Mask*Scale); 2703 } 2704 } 2705 2706 Offset = (isSub) ? -Offset : Offset; 2707 return Offset == 0; 2708 } 2709 2710 /// analyzeCompare - For a comparison instruction, return the source registers 2711 /// in SrcReg and SrcReg2 if having two register operands, and the value it 2712 /// compares against in CmpValue. Return true if the comparison instruction 2713 /// can be analyzed. 2714 bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg, 2715 Register &SrcReg2, int &CmpMask, 2716 int &CmpValue) const { 2717 switch (MI.getOpcode()) { 2718 default: break; 2719 case ARM::CMPri: 2720 case ARM::t2CMPri: 2721 case ARM::tCMPi8: 2722 SrcReg = MI.getOperand(0).getReg(); 2723 SrcReg2 = 0; 2724 CmpMask = ~0; 2725 CmpValue = MI.getOperand(1).getImm(); 2726 return true; 2727 case ARM::CMPrr: 2728 case ARM::t2CMPrr: 2729 case ARM::tCMPr: 2730 SrcReg = MI.getOperand(0).getReg(); 2731 SrcReg2 = MI.getOperand(1).getReg(); 2732 CmpMask = ~0; 2733 CmpValue = 0; 2734 return true; 2735 case ARM::TSTri: 2736 case ARM::t2TSTri: 2737 SrcReg = MI.getOperand(0).getReg(); 2738 SrcReg2 = 0; 2739 CmpMask = MI.getOperand(1).getImm(); 2740 CmpValue = 0; 2741 return true; 2742 } 2743 2744 return false; 2745 } 2746 2747 /// isSuitableForMask - Identify a suitable 'and' instruction that 2748 /// operates on the given source register and applies the same mask 2749 /// as a 'tst' instruction. Provide a limited look-through for copies. 2750 /// When successful, MI will hold the found instruction. 2751 static bool isSuitableForMask(MachineInstr *&MI, Register SrcReg, 2752 int CmpMask, bool CommonUse) { 2753 switch (MI->getOpcode()) { 2754 case ARM::ANDri: 2755 case ARM::t2ANDri: 2756 if (CmpMask != MI->getOperand(2).getImm()) 2757 return false; 2758 if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg()) 2759 return true; 2760 break; 2761 } 2762 2763 return false; 2764 } 2765 2766 /// getCmpToAddCondition - assume the flags are set by CMP(a,b), return 2767 /// the condition code if we modify the instructions such that flags are 2768 /// set by ADD(a,b,X). 2769 inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) { 2770 switch (CC) { 2771 default: return ARMCC::AL; 2772 case ARMCC::HS: return ARMCC::LO; 2773 case ARMCC::LO: return ARMCC::HS; 2774 case ARMCC::VS: return ARMCC::VS; 2775 case ARMCC::VC: return ARMCC::VC; 2776 } 2777 } 2778 2779 /// isRedundantFlagInstr - check whether the first instruction, whose only 2780 /// purpose is to update flags, can be made redundant. 2781 /// CMPrr can be made redundant by SUBrr if the operands are the same. 2782 /// CMPri can be made redundant by SUBri if the operands are the same. 2783 /// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X). 2784 /// This function can be extended later on. 2785 inline static bool isRedundantFlagInstr(const MachineInstr *CmpI, 2786 Register SrcReg, Register SrcReg2, 2787 int ImmValue, const MachineInstr *OI, 2788 bool &IsThumb1) { 2789 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) && 2790 (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) && 2791 ((OI->getOperand(1).getReg() == SrcReg && 2792 OI->getOperand(2).getReg() == SrcReg2) || 2793 (OI->getOperand(1).getReg() == SrcReg2 && 2794 OI->getOperand(2).getReg() == SrcReg))) { 2795 IsThumb1 = false; 2796 return true; 2797 } 2798 2799 if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr && 2800 ((OI->getOperand(2).getReg() == SrcReg && 2801 OI->getOperand(3).getReg() == SrcReg2) || 2802 (OI->getOperand(2).getReg() == SrcReg2 && 2803 OI->getOperand(3).getReg() == SrcReg))) { 2804 IsThumb1 = true; 2805 return true; 2806 } 2807 2808 if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) && 2809 (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) && 2810 OI->getOperand(1).getReg() == SrcReg && 2811 OI->getOperand(2).getImm() == ImmValue) { 2812 IsThumb1 = false; 2813 return true; 2814 } 2815 2816 if (CmpI->getOpcode() == ARM::tCMPi8 && 2817 (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) && 2818 OI->getOperand(2).getReg() == SrcReg && 2819 OI->getOperand(3).getImm() == ImmValue) { 2820 IsThumb1 = true; 2821 return true; 2822 } 2823 2824 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) && 2825 (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr || 2826 OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) && 2827 OI->getOperand(0).isReg() && OI->getOperand(1).isReg() && 2828 OI->getOperand(0).getReg() == SrcReg && 2829 OI->getOperand(1).getReg() == SrcReg2) { 2830 IsThumb1 = false; 2831 return true; 2832 } 2833 2834 if (CmpI->getOpcode() == ARM::tCMPr && 2835 (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 || 2836 OI->getOpcode() == ARM::tADDrr) && 2837 OI->getOperand(0).getReg() == SrcReg && 2838 OI->getOperand(2).getReg() == SrcReg2) { 2839 IsThumb1 = true; 2840 return true; 2841 } 2842 2843 return false; 2844 } 2845 2846 static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) { 2847 switch (MI->getOpcode()) { 2848 default: return false; 2849 case ARM::tLSLri: 2850 case ARM::tLSRri: 2851 case ARM::tLSLrr: 2852 case ARM::tLSRrr: 2853 case ARM::tSUBrr: 2854 case ARM::tADDrr: 2855 case ARM::tADDi3: 2856 case ARM::tADDi8: 2857 case ARM::tSUBi3: 2858 case ARM::tSUBi8: 2859 case ARM::tMUL: 2860 case ARM::tADC: 2861 case ARM::tSBC: 2862 case ARM::tRSB: 2863 case ARM::tAND: 2864 case ARM::tORR: 2865 case ARM::tEOR: 2866 case ARM::tBIC: 2867 case ARM::tMVN: 2868 case ARM::tASRri: 2869 case ARM::tASRrr: 2870 case ARM::tROR: 2871 IsThumb1 = true; 2872 LLVM_FALLTHROUGH; 2873 case ARM::RSBrr: 2874 case ARM::RSBri: 2875 case ARM::RSCrr: 2876 case ARM::RSCri: 2877 case ARM::ADDrr: 2878 case ARM::ADDri: 2879 case ARM::ADCrr: 2880 case ARM::ADCri: 2881 case ARM::SUBrr: 2882 case ARM::SUBri: 2883 case ARM::SBCrr: 2884 case ARM::SBCri: 2885 case ARM::t2RSBri: 2886 case ARM::t2ADDrr: 2887 case ARM::t2ADDri: 2888 case ARM::t2ADCrr: 2889 case ARM::t2ADCri: 2890 case ARM::t2SUBrr: 2891 case ARM::t2SUBri: 2892 case ARM::t2SBCrr: 2893 case ARM::t2SBCri: 2894 case ARM::ANDrr: 2895 case ARM::ANDri: 2896 case ARM::t2ANDrr: 2897 case ARM::t2ANDri: 2898 case ARM::ORRrr: 2899 case ARM::ORRri: 2900 case ARM::t2ORRrr: 2901 case ARM::t2ORRri: 2902 case ARM::EORrr: 2903 case ARM::EORri: 2904 case ARM::t2EORrr: 2905 case ARM::t2EORri: 2906 case ARM::t2LSRri: 2907 case ARM::t2LSRrr: 2908 case ARM::t2LSLri: 2909 case ARM::t2LSLrr: 2910 return true; 2911 } 2912 } 2913 2914 /// optimizeCompareInstr - Convert the instruction supplying the argument to the 2915 /// comparison into one that sets the zero bit in the flags register; 2916 /// Remove a redundant Compare instruction if an earlier instruction can set the 2917 /// flags in the same way as Compare. 2918 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two 2919 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the 2920 /// condition code of instructions which use the flags. 2921 bool ARMBaseInstrInfo::optimizeCompareInstr( 2922 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int CmpMask, 2923 int CmpValue, const MachineRegisterInfo *MRI) const { 2924 // Get the unique definition of SrcReg. 2925 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg); 2926 if (!MI) return false; 2927 2928 // Masked compares sometimes use the same register as the corresponding 'and'. 2929 if (CmpMask != ~0) { 2930 if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) { 2931 MI = nullptr; 2932 for (MachineRegisterInfo::use_instr_iterator 2933 UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end(); 2934 UI != UE; ++UI) { 2935 if (UI->getParent() != CmpInstr.getParent()) 2936 continue; 2937 MachineInstr *PotentialAND = &*UI; 2938 if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) || 2939 isPredicated(*PotentialAND)) 2940 continue; 2941 MI = PotentialAND; 2942 break; 2943 } 2944 if (!MI) return false; 2945 } 2946 } 2947 2948 // Get ready to iterate backward from CmpInstr. 2949 MachineBasicBlock::iterator I = CmpInstr, E = MI, 2950 B = CmpInstr.getParent()->begin(); 2951 2952 // Early exit if CmpInstr is at the beginning of the BB. 2953 if (I == B) return false; 2954 2955 // There are two possible candidates which can be changed to set CPSR: 2956 // One is MI, the other is a SUB or ADD instruction. 2957 // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or 2958 // ADDr[ri](r1, r2, X). 2959 // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue). 2960 MachineInstr *SubAdd = nullptr; 2961 if (SrcReg2 != 0) 2962 // MI is not a candidate for CMPrr. 2963 MI = nullptr; 2964 else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) { 2965 // Conservatively refuse to convert an instruction which isn't in the same 2966 // BB as the comparison. 2967 // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate. 2968 // Thus we cannot return here. 2969 if (CmpInstr.getOpcode() == ARM::CMPri || 2970 CmpInstr.getOpcode() == ARM::t2CMPri || 2971 CmpInstr.getOpcode() == ARM::tCMPi8) 2972 MI = nullptr; 2973 else 2974 return false; 2975 } 2976 2977 bool IsThumb1 = false; 2978 if (MI && !isOptimizeCompareCandidate(MI, IsThumb1)) 2979 return false; 2980 2981 // We also want to do this peephole for cases like this: if (a*b == 0), 2982 // and optimise away the CMP instruction from the generated code sequence: 2983 // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values 2984 // resulting from the select instruction, but these MOVS instructions for 2985 // Thumb1 (V6M) are flag setting and are thus preventing this optimisation. 2986 // However, if we only have MOVS instructions in between the CMP and the 2987 // other instruction (the MULS in this example), then the CPSR is dead so we 2988 // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this 2989 // reordering and then continue the analysis hoping we can eliminate the 2990 // CMP. This peephole works on the vregs, so is still in SSA form. As a 2991 // consequence, the movs won't redefine/kill the MUL operands which would 2992 // make this reordering illegal. 2993 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2994 if (MI && IsThumb1) { 2995 --I; 2996 if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) { 2997 bool CanReorder = true; 2998 for (; I != E; --I) { 2999 if (I->getOpcode() != ARM::tMOVi8) { 3000 CanReorder = false; 3001 break; 3002 } 3003 } 3004 if (CanReorder) { 3005 MI = MI->removeFromParent(); 3006 E = CmpInstr; 3007 CmpInstr.getParent()->insert(E, MI); 3008 } 3009 } 3010 I = CmpInstr; 3011 E = MI; 3012 } 3013 3014 // Check that CPSR isn't set between the comparison instruction and the one we 3015 // want to change. At the same time, search for SubAdd. 3016 bool SubAddIsThumb1 = false; 3017 do { 3018 const MachineInstr &Instr = *--I; 3019 3020 // Check whether CmpInstr can be made redundant by the current instruction. 3021 if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr, 3022 SubAddIsThumb1)) { 3023 SubAdd = &*I; 3024 break; 3025 } 3026 3027 // Allow E (which was initially MI) to be SubAdd but do not search before E. 3028 if (I == E) 3029 break; 3030 3031 if (Instr.modifiesRegister(ARM::CPSR, TRI) || 3032 Instr.readsRegister(ARM::CPSR, TRI)) 3033 // This instruction modifies or uses CPSR after the one we want to 3034 // change. We can't do this transformation. 3035 return false; 3036 3037 if (I == B) { 3038 // In some cases, we scan the use-list of an instruction for an AND; 3039 // that AND is in the same BB, but may not be scheduled before the 3040 // corresponding TST. In that case, bail out. 3041 // 3042 // FIXME: We could try to reschedule the AND. 3043 return false; 3044 } 3045 } while (true); 3046 3047 // Return false if no candidates exist. 3048 if (!MI && !SubAdd) 3049 return false; 3050 3051 // If we found a SubAdd, use it as it will be closer to the CMP 3052 if (SubAdd) { 3053 MI = SubAdd; 3054 IsThumb1 = SubAddIsThumb1; 3055 } 3056 3057 // We can't use a predicated instruction - it doesn't always write the flags. 3058 if (isPredicated(*MI)) 3059 return false; 3060 3061 // Scan forward for the use of CPSR 3062 // When checking against MI: if it's a conditional code that requires 3063 // checking of the V bit or C bit, then this is not safe to do. 3064 // It is safe to remove CmpInstr if CPSR is redefined or killed. 3065 // If we are done with the basic block, we need to check whether CPSR is 3066 // live-out. 3067 SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4> 3068 OperandsToUpdate; 3069 bool isSafe = false; 3070 I = CmpInstr; 3071 E = CmpInstr.getParent()->end(); 3072 while (!isSafe && ++I != E) { 3073 const MachineInstr &Instr = *I; 3074 for (unsigned IO = 0, EO = Instr.getNumOperands(); 3075 !isSafe && IO != EO; ++IO) { 3076 const MachineOperand &MO = Instr.getOperand(IO); 3077 if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) { 3078 isSafe = true; 3079 break; 3080 } 3081 if (!MO.isReg() || MO.getReg() != ARM::CPSR) 3082 continue; 3083 if (MO.isDef()) { 3084 isSafe = true; 3085 break; 3086 } 3087 // Condition code is after the operand before CPSR except for VSELs. 3088 ARMCC::CondCodes CC; 3089 bool IsInstrVSel = true; 3090 switch (Instr.getOpcode()) { 3091 default: 3092 IsInstrVSel = false; 3093 CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm(); 3094 break; 3095 case ARM::VSELEQD: 3096 case ARM::VSELEQS: 3097 case ARM::VSELEQH: 3098 CC = ARMCC::EQ; 3099 break; 3100 case ARM::VSELGTD: 3101 case ARM::VSELGTS: 3102 case ARM::VSELGTH: 3103 CC = ARMCC::GT; 3104 break; 3105 case ARM::VSELGED: 3106 case ARM::VSELGES: 3107 case ARM::VSELGEH: 3108 CC = ARMCC::GE; 3109 break; 3110 case ARM::VSELVSD: 3111 case ARM::VSELVSS: 3112 case ARM::VSELVSH: 3113 CC = ARMCC::VS; 3114 break; 3115 } 3116 3117 if (SubAdd) { 3118 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based 3119 // on CMP needs to be updated to be based on SUB. 3120 // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also 3121 // needs to be modified. 3122 // Push the condition code operands to OperandsToUpdate. 3123 // If it is safe to remove CmpInstr, the condition code of these 3124 // operands will be modified. 3125 unsigned Opc = SubAdd->getOpcode(); 3126 bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr || 3127 Opc == ARM::SUBri || Opc == ARM::t2SUBri || 3128 Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 || 3129 Opc == ARM::tSUBi8; 3130 unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2; 3131 if (!IsSub || 3132 (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 && 3133 SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) { 3134 // VSel doesn't support condition code update. 3135 if (IsInstrVSel) 3136 return false; 3137 // Ensure we can swap the condition. 3138 ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC)); 3139 if (NewCC == ARMCC::AL) 3140 return false; 3141 OperandsToUpdate.push_back( 3142 std::make_pair(&((*I).getOperand(IO - 1)), NewCC)); 3143 } 3144 } else { 3145 // No SubAdd, so this is x = <op> y, z; cmp x, 0. 3146 switch (CC) { 3147 case ARMCC::EQ: // Z 3148 case ARMCC::NE: // Z 3149 case ARMCC::MI: // N 3150 case ARMCC::PL: // N 3151 case ARMCC::AL: // none 3152 // CPSR can be used multiple times, we should continue. 3153 break; 3154 case ARMCC::HS: // C 3155 case ARMCC::LO: // C 3156 case ARMCC::VS: // V 3157 case ARMCC::VC: // V 3158 case ARMCC::HI: // C Z 3159 case ARMCC::LS: // C Z 3160 case ARMCC::GE: // N V 3161 case ARMCC::LT: // N V 3162 case ARMCC::GT: // Z N V 3163 case ARMCC::LE: // Z N V 3164 // The instruction uses the V bit or C bit which is not safe. 3165 return false; 3166 } 3167 } 3168 } 3169 } 3170 3171 // If CPSR is not killed nor re-defined, we should check whether it is 3172 // live-out. If it is live-out, do not optimize. 3173 if (!isSafe) { 3174 MachineBasicBlock *MBB = CmpInstr.getParent(); 3175 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(), 3176 SE = MBB->succ_end(); SI != SE; ++SI) 3177 if ((*SI)->isLiveIn(ARM::CPSR)) 3178 return false; 3179 } 3180 3181 // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always 3182 // set CPSR so this is represented as an explicit output) 3183 if (!IsThumb1) { 3184 MI->getOperand(5).setReg(ARM::CPSR); 3185 MI->getOperand(5).setIsDef(true); 3186 } 3187 assert(!isPredicated(*MI) && "Can't use flags from predicated instruction"); 3188 CmpInstr.eraseFromParent(); 3189 3190 // Modify the condition code of operands in OperandsToUpdate. 3191 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to 3192 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc. 3193 for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++) 3194 OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second); 3195 3196 MI->clearRegisterDeads(ARM::CPSR); 3197 3198 return true; 3199 } 3200 3201 bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const { 3202 // Do not sink MI if it might be used to optimize a redundant compare. 3203 // We heuristically only look at the instruction immediately following MI to 3204 // avoid potentially searching the entire basic block. 3205 if (isPredicated(MI)) 3206 return true; 3207 MachineBasicBlock::const_iterator Next = &MI; 3208 ++Next; 3209 Register SrcReg, SrcReg2; 3210 int CmpMask, CmpValue; 3211 bool IsThumb1; 3212 if (Next != MI.getParent()->end() && 3213 analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) && 3214 isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1)) 3215 return false; 3216 return true; 3217 } 3218 3219 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, 3220 Register Reg, 3221 MachineRegisterInfo *MRI) const { 3222 // Fold large immediates into add, sub, or, xor. 3223 unsigned DefOpc = DefMI.getOpcode(); 3224 if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm) 3225 return false; 3226 if (!DefMI.getOperand(1).isImm()) 3227 // Could be t2MOVi32imm @xx 3228 return false; 3229 3230 if (!MRI->hasOneNonDBGUse(Reg)) 3231 return false; 3232 3233 const MCInstrDesc &DefMCID = DefMI.getDesc(); 3234 if (DefMCID.hasOptionalDef()) { 3235 unsigned NumOps = DefMCID.getNumOperands(); 3236 const MachineOperand &MO = DefMI.getOperand(NumOps - 1); 3237 if (MO.getReg() == ARM::CPSR && !MO.isDead()) 3238 // If DefMI defines CPSR and it is not dead, it's obviously not safe 3239 // to delete DefMI. 3240 return false; 3241 } 3242 3243 const MCInstrDesc &UseMCID = UseMI.getDesc(); 3244 if (UseMCID.hasOptionalDef()) { 3245 unsigned NumOps = UseMCID.getNumOperands(); 3246 if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR) 3247 // If the instruction sets the flag, do not attempt this optimization 3248 // since it may change the semantics of the code. 3249 return false; 3250 } 3251 3252 unsigned UseOpc = UseMI.getOpcode(); 3253 unsigned NewUseOpc = 0; 3254 uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm(); 3255 uint32_t SOImmValV1 = 0, SOImmValV2 = 0; 3256 bool Commute = false; 3257 switch (UseOpc) { 3258 default: return false; 3259 case ARM::SUBrr: 3260 case ARM::ADDrr: 3261 case ARM::ORRrr: 3262 case ARM::EORrr: 3263 case ARM::t2SUBrr: 3264 case ARM::t2ADDrr: 3265 case ARM::t2ORRrr: 3266 case ARM::t2EORrr: { 3267 Commute = UseMI.getOperand(2).getReg() != Reg; 3268 switch (UseOpc) { 3269 default: break; 3270 case ARM::ADDrr: 3271 case ARM::SUBrr: 3272 if (UseOpc == ARM::SUBrr && Commute) 3273 return false; 3274 3275 // ADD/SUB are special because they're essentially the same operation, so 3276 // we can handle a larger range of immediates. 3277 if (ARM_AM::isSOImmTwoPartVal(ImmVal)) 3278 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri; 3279 else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) { 3280 ImmVal = -ImmVal; 3281 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri; 3282 } else 3283 return false; 3284 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal); 3285 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal); 3286 break; 3287 case ARM::ORRrr: 3288 case ARM::EORrr: 3289 if (!ARM_AM::isSOImmTwoPartVal(ImmVal)) 3290 return false; 3291 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal); 3292 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal); 3293 switch (UseOpc) { 3294 default: break; 3295 case ARM::ORRrr: NewUseOpc = ARM::ORRri; break; 3296 case ARM::EORrr: NewUseOpc = ARM::EORri; break; 3297 } 3298 break; 3299 case ARM::t2ADDrr: 3300 case ARM::t2SUBrr: { 3301 if (UseOpc == ARM::t2SUBrr && Commute) 3302 return false; 3303 3304 // ADD/SUB are special because they're essentially the same operation, so 3305 // we can handle a larger range of immediates. 3306 const bool ToSP = DefMI.getOperand(0).getReg() == ARM::SP; 3307 const unsigned t2ADD = ToSP ? ARM::t2ADDspImm : ARM::t2ADDri; 3308 const unsigned t2SUB = ToSP ? ARM::t2SUBspImm : ARM::t2SUBri; 3309 if (ARM_AM::isT2SOImmTwoPartVal(ImmVal)) 3310 NewUseOpc = UseOpc == ARM::t2ADDrr ? t2ADD : t2SUB; 3311 else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) { 3312 ImmVal = -ImmVal; 3313 NewUseOpc = UseOpc == ARM::t2ADDrr ? t2SUB : t2ADD; 3314 } else 3315 return false; 3316 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal); 3317 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal); 3318 break; 3319 } 3320 case ARM::t2ORRrr: 3321 case ARM::t2EORrr: 3322 if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal)) 3323 return false; 3324 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal); 3325 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal); 3326 switch (UseOpc) { 3327 default: break; 3328 case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break; 3329 case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break; 3330 } 3331 break; 3332 } 3333 } 3334 } 3335 3336 unsigned OpIdx = Commute ? 2 : 1; 3337 Register Reg1 = UseMI.getOperand(OpIdx).getReg(); 3338 bool isKill = UseMI.getOperand(OpIdx).isKill(); 3339 const TargetRegisterClass *TRC = MRI->getRegClass(Reg); 3340 Register NewReg = MRI->createVirtualRegister(TRC); 3341 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc), 3342 NewReg) 3343 .addReg(Reg1, getKillRegState(isKill)) 3344 .addImm(SOImmValV1) 3345 .add(predOps(ARMCC::AL)) 3346 .add(condCodeOp()); 3347 UseMI.setDesc(get(NewUseOpc)); 3348 UseMI.getOperand(1).setReg(NewReg); 3349 UseMI.getOperand(1).setIsKill(); 3350 UseMI.getOperand(2).ChangeToImmediate(SOImmValV2); 3351 DefMI.eraseFromParent(); 3352 // FIXME: t2ADDrr should be split, as different rulles apply when writing to SP. 3353 // Just as t2ADDri, that was split to [t2ADDri, t2ADDspImm]. 3354 // Then the below code will not be needed, as the input/output register 3355 // classes will be rgpr or gprSP. 3356 // For now, we fix the UseMI operand explicitly here: 3357 switch(NewUseOpc){ 3358 case ARM::t2ADDspImm: 3359 case ARM::t2SUBspImm: 3360 case ARM::t2ADDri: 3361 case ARM::t2SUBri: 3362 MRI->setRegClass(UseMI.getOperand(0).getReg(), TRC); 3363 } 3364 return true; 3365 } 3366 3367 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData, 3368 const MachineInstr &MI) { 3369 switch (MI.getOpcode()) { 3370 default: { 3371 const MCInstrDesc &Desc = MI.getDesc(); 3372 int UOps = ItinData->getNumMicroOps(Desc.getSchedClass()); 3373 assert(UOps >= 0 && "bad # UOps"); 3374 return UOps; 3375 } 3376 3377 case ARM::LDRrs: 3378 case ARM::LDRBrs: 3379 case ARM::STRrs: 3380 case ARM::STRBrs: { 3381 unsigned ShOpVal = MI.getOperand(3).getImm(); 3382 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3383 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3384 if (!isSub && 3385 (ShImm == 0 || 3386 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3387 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3388 return 1; 3389 return 2; 3390 } 3391 3392 case ARM::LDRH: 3393 case ARM::STRH: { 3394 if (!MI.getOperand(2).getReg()) 3395 return 1; 3396 3397 unsigned ShOpVal = MI.getOperand(3).getImm(); 3398 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3399 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3400 if (!isSub && 3401 (ShImm == 0 || 3402 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3403 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3404 return 1; 3405 return 2; 3406 } 3407 3408 case ARM::LDRSB: 3409 case ARM::LDRSH: 3410 return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2; 3411 3412 case ARM::LDRSB_POST: 3413 case ARM::LDRSH_POST: { 3414 Register Rt = MI.getOperand(0).getReg(); 3415 Register Rm = MI.getOperand(3).getReg(); 3416 return (Rt == Rm) ? 4 : 3; 3417 } 3418 3419 case ARM::LDR_PRE_REG: 3420 case ARM::LDRB_PRE_REG: { 3421 Register Rt = MI.getOperand(0).getReg(); 3422 Register Rm = MI.getOperand(3).getReg(); 3423 if (Rt == Rm) 3424 return 3; 3425 unsigned ShOpVal = MI.getOperand(4).getImm(); 3426 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3427 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3428 if (!isSub && 3429 (ShImm == 0 || 3430 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3431 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3432 return 2; 3433 return 3; 3434 } 3435 3436 case ARM::STR_PRE_REG: 3437 case ARM::STRB_PRE_REG: { 3438 unsigned ShOpVal = MI.getOperand(4).getImm(); 3439 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3440 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3441 if (!isSub && 3442 (ShImm == 0 || 3443 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3444 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3445 return 2; 3446 return 3; 3447 } 3448 3449 case ARM::LDRH_PRE: 3450 case ARM::STRH_PRE: { 3451 Register Rt = MI.getOperand(0).getReg(); 3452 Register Rm = MI.getOperand(3).getReg(); 3453 if (!Rm) 3454 return 2; 3455 if (Rt == Rm) 3456 return 3; 3457 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2; 3458 } 3459 3460 case ARM::LDR_POST_REG: 3461 case ARM::LDRB_POST_REG: 3462 case ARM::LDRH_POST: { 3463 Register Rt = MI.getOperand(0).getReg(); 3464 Register Rm = MI.getOperand(3).getReg(); 3465 return (Rt == Rm) ? 3 : 2; 3466 } 3467 3468 case ARM::LDR_PRE_IMM: 3469 case ARM::LDRB_PRE_IMM: 3470 case ARM::LDR_POST_IMM: 3471 case ARM::LDRB_POST_IMM: 3472 case ARM::STRB_POST_IMM: 3473 case ARM::STRB_POST_REG: 3474 case ARM::STRB_PRE_IMM: 3475 case ARM::STRH_POST: 3476 case ARM::STR_POST_IMM: 3477 case ARM::STR_POST_REG: 3478 case ARM::STR_PRE_IMM: 3479 return 2; 3480 3481 case ARM::LDRSB_PRE: 3482 case ARM::LDRSH_PRE: { 3483 Register Rm = MI.getOperand(3).getReg(); 3484 if (Rm == 0) 3485 return 3; 3486 Register Rt = MI.getOperand(0).getReg(); 3487 if (Rt == Rm) 3488 return 4; 3489 unsigned ShOpVal = MI.getOperand(4).getImm(); 3490 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 3491 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 3492 if (!isSub && 3493 (ShImm == 0 || 3494 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 3495 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 3496 return 3; 3497 return 4; 3498 } 3499 3500 case ARM::LDRD: { 3501 Register Rt = MI.getOperand(0).getReg(); 3502 Register Rn = MI.getOperand(2).getReg(); 3503 Register Rm = MI.getOperand(3).getReg(); 3504 if (Rm) 3505 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4 3506 : 3; 3507 return (Rt == Rn) ? 3 : 2; 3508 } 3509 3510 case ARM::STRD: { 3511 Register Rm = MI.getOperand(3).getReg(); 3512 if (Rm) 3513 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4 3514 : 3; 3515 return 2; 3516 } 3517 3518 case ARM::LDRD_POST: 3519 case ARM::t2LDRD_POST: 3520 return 3; 3521 3522 case ARM::STRD_POST: 3523 case ARM::t2STRD_POST: 3524 return 4; 3525 3526 case ARM::LDRD_PRE: { 3527 Register Rt = MI.getOperand(0).getReg(); 3528 Register Rn = MI.getOperand(3).getReg(); 3529 Register Rm = MI.getOperand(4).getReg(); 3530 if (Rm) 3531 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5 3532 : 4; 3533 return (Rt == Rn) ? 4 : 3; 3534 } 3535 3536 case ARM::t2LDRD_PRE: { 3537 Register Rt = MI.getOperand(0).getReg(); 3538 Register Rn = MI.getOperand(3).getReg(); 3539 return (Rt == Rn) ? 4 : 3; 3540 } 3541 3542 case ARM::STRD_PRE: { 3543 Register Rm = MI.getOperand(4).getReg(); 3544 if (Rm) 3545 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5 3546 : 4; 3547 return 3; 3548 } 3549 3550 case ARM::t2STRD_PRE: 3551 return 3; 3552 3553 case ARM::t2LDR_POST: 3554 case ARM::t2LDRB_POST: 3555 case ARM::t2LDRB_PRE: 3556 case ARM::t2LDRSBi12: 3557 case ARM::t2LDRSBi8: 3558 case ARM::t2LDRSBpci: 3559 case ARM::t2LDRSBs: 3560 case ARM::t2LDRH_POST: 3561 case ARM::t2LDRH_PRE: 3562 case ARM::t2LDRSBT: 3563 case ARM::t2LDRSB_POST: 3564 case ARM::t2LDRSB_PRE: 3565 case ARM::t2LDRSH_POST: 3566 case ARM::t2LDRSH_PRE: 3567 case ARM::t2LDRSHi12: 3568 case ARM::t2LDRSHi8: 3569 case ARM::t2LDRSHpci: 3570 case ARM::t2LDRSHs: 3571 return 2; 3572 3573 case ARM::t2LDRDi8: { 3574 Register Rt = MI.getOperand(0).getReg(); 3575 Register Rn = MI.getOperand(2).getReg(); 3576 return (Rt == Rn) ? 3 : 2; 3577 } 3578 3579 case ARM::t2STRB_POST: 3580 case ARM::t2STRB_PRE: 3581 case ARM::t2STRBs: 3582 case ARM::t2STRDi8: 3583 case ARM::t2STRH_POST: 3584 case ARM::t2STRH_PRE: 3585 case ARM::t2STRHs: 3586 case ARM::t2STR_POST: 3587 case ARM::t2STR_PRE: 3588 case ARM::t2STRs: 3589 return 2; 3590 } 3591 } 3592 3593 // Return the number of 32-bit words loaded by LDM or stored by STM. If this 3594 // can't be easily determined return 0 (missing MachineMemOperand). 3595 // 3596 // FIXME: The current MachineInstr design does not support relying on machine 3597 // mem operands to determine the width of a memory access. Instead, we expect 3598 // the target to provide this information based on the instruction opcode and 3599 // operands. However, using MachineMemOperand is the best solution now for 3600 // two reasons: 3601 // 3602 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI 3603 // operands. This is much more dangerous than using the MachineMemOperand 3604 // sizes because CodeGen passes can insert/remove optional machine operands. In 3605 // fact, it's totally incorrect for preRA passes and appears to be wrong for 3606 // postRA passes as well. 3607 // 3608 // 2) getNumLDMAddresses is only used by the scheduling machine model and any 3609 // machine model that calls this should handle the unknown (zero size) case. 3610 // 3611 // Long term, we should require a target hook that verifies MachineMemOperand 3612 // sizes during MC lowering. That target hook should be local to MC lowering 3613 // because we can't ensure that it is aware of other MI forms. Doing this will 3614 // ensure that MachineMemOperands are correctly propagated through all passes. 3615 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const { 3616 unsigned Size = 0; 3617 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(), 3618 E = MI.memoperands_end(); 3619 I != E; ++I) { 3620 Size += (*I)->getSize(); 3621 } 3622 // FIXME: The scheduler currently can't handle values larger than 16. But 3623 // the values can actually go up to 32 for floating-point load/store 3624 // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory 3625 // operations isn't right; we could end up with "extra" memory operands for 3626 // various reasons, like tail merge merging two memory operations. 3627 return std::min(Size / 4, 16U); 3628 } 3629 3630 static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc, 3631 unsigned NumRegs) { 3632 unsigned UOps = 1 + NumRegs; // 1 for address computation. 3633 switch (Opc) { 3634 default: 3635 break; 3636 case ARM::VLDMDIA_UPD: 3637 case ARM::VLDMDDB_UPD: 3638 case ARM::VLDMSIA_UPD: 3639 case ARM::VLDMSDB_UPD: 3640 case ARM::VSTMDIA_UPD: 3641 case ARM::VSTMDDB_UPD: 3642 case ARM::VSTMSIA_UPD: 3643 case ARM::VSTMSDB_UPD: 3644 case ARM::LDMIA_UPD: 3645 case ARM::LDMDA_UPD: 3646 case ARM::LDMDB_UPD: 3647 case ARM::LDMIB_UPD: 3648 case ARM::STMIA_UPD: 3649 case ARM::STMDA_UPD: 3650 case ARM::STMDB_UPD: 3651 case ARM::STMIB_UPD: 3652 case ARM::tLDMIA_UPD: 3653 case ARM::tSTMIA_UPD: 3654 case ARM::t2LDMIA_UPD: 3655 case ARM::t2LDMDB_UPD: 3656 case ARM::t2STMIA_UPD: 3657 case ARM::t2STMDB_UPD: 3658 ++UOps; // One for base register writeback. 3659 break; 3660 case ARM::LDMIA_RET: 3661 case ARM::tPOP_RET: 3662 case ARM::t2LDMIA_RET: 3663 UOps += 2; // One for base reg wb, one for write to pc. 3664 break; 3665 } 3666 return UOps; 3667 } 3668 3669 unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData, 3670 const MachineInstr &MI) const { 3671 if (!ItinData || ItinData->isEmpty()) 3672 return 1; 3673 3674 const MCInstrDesc &Desc = MI.getDesc(); 3675 unsigned Class = Desc.getSchedClass(); 3676 int ItinUOps = ItinData->getNumMicroOps(Class); 3677 if (ItinUOps >= 0) { 3678 if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore())) 3679 return getNumMicroOpsSwiftLdSt(ItinData, MI); 3680 3681 return ItinUOps; 3682 } 3683 3684 unsigned Opc = MI.getOpcode(); 3685 switch (Opc) { 3686 default: 3687 llvm_unreachable("Unexpected multi-uops instruction!"); 3688 case ARM::VLDMQIA: 3689 case ARM::VSTMQIA: 3690 return 2; 3691 3692 // The number of uOps for load / store multiple are determined by the number 3693 // registers. 3694 // 3695 // On Cortex-A8, each pair of register loads / stores can be scheduled on the 3696 // same cycle. The scheduling for the first load / store must be done 3697 // separately by assuming the address is not 64-bit aligned. 3698 // 3699 // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address 3700 // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON 3701 // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1. 3702 case ARM::VLDMDIA: 3703 case ARM::VLDMDIA_UPD: 3704 case ARM::VLDMDDB_UPD: 3705 case ARM::VLDMSIA: 3706 case ARM::VLDMSIA_UPD: 3707 case ARM::VLDMSDB_UPD: 3708 case ARM::VSTMDIA: 3709 case ARM::VSTMDIA_UPD: 3710 case ARM::VSTMDDB_UPD: 3711 case ARM::VSTMSIA: 3712 case ARM::VSTMSIA_UPD: 3713 case ARM::VSTMSDB_UPD: { 3714 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands(); 3715 return (NumRegs / 2) + (NumRegs % 2) + 1; 3716 } 3717 3718 case ARM::LDMIA_RET: 3719 case ARM::LDMIA: 3720 case ARM::LDMDA: 3721 case ARM::LDMDB: 3722 case ARM::LDMIB: 3723 case ARM::LDMIA_UPD: 3724 case ARM::LDMDA_UPD: 3725 case ARM::LDMDB_UPD: 3726 case ARM::LDMIB_UPD: 3727 case ARM::STMIA: 3728 case ARM::STMDA: 3729 case ARM::STMDB: 3730 case ARM::STMIB: 3731 case ARM::STMIA_UPD: 3732 case ARM::STMDA_UPD: 3733 case ARM::STMDB_UPD: 3734 case ARM::STMIB_UPD: 3735 case ARM::tLDMIA: 3736 case ARM::tLDMIA_UPD: 3737 case ARM::tSTMIA_UPD: 3738 case ARM::tPOP_RET: 3739 case ARM::tPOP: 3740 case ARM::tPUSH: 3741 case ARM::t2LDMIA_RET: 3742 case ARM::t2LDMIA: 3743 case ARM::t2LDMDB: 3744 case ARM::t2LDMIA_UPD: 3745 case ARM::t2LDMDB_UPD: 3746 case ARM::t2STMIA: 3747 case ARM::t2STMDB: 3748 case ARM::t2STMIA_UPD: 3749 case ARM::t2STMDB_UPD: { 3750 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1; 3751 switch (Subtarget.getLdStMultipleTiming()) { 3752 case ARMSubtarget::SingleIssuePlusExtras: 3753 return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs); 3754 case ARMSubtarget::SingleIssue: 3755 // Assume the worst. 3756 return NumRegs; 3757 case ARMSubtarget::DoubleIssue: { 3758 if (NumRegs < 4) 3759 return 2; 3760 // 4 registers would be issued: 2, 2. 3761 // 5 registers would be issued: 2, 2, 1. 3762 unsigned UOps = (NumRegs / 2); 3763 if (NumRegs % 2) 3764 ++UOps; 3765 return UOps; 3766 } 3767 case ARMSubtarget::DoubleIssueCheckUnalignedAccess: { 3768 unsigned UOps = (NumRegs / 2); 3769 // If there are odd number of registers or if it's not 64-bit aligned, 3770 // then it takes an extra AGU (Address Generation Unit) cycle. 3771 if ((NumRegs % 2) || !MI.hasOneMemOperand() || 3772 (*MI.memoperands_begin())->getAlign() < Align(8)) 3773 ++UOps; 3774 return UOps; 3775 } 3776 } 3777 } 3778 } 3779 llvm_unreachable("Didn't find the number of microops"); 3780 } 3781 3782 int 3783 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData, 3784 const MCInstrDesc &DefMCID, 3785 unsigned DefClass, 3786 unsigned DefIdx, unsigned DefAlign) const { 3787 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1; 3788 if (RegNo <= 0) 3789 // Def is the address writeback. 3790 return ItinData->getOperandCycle(DefClass, DefIdx); 3791 3792 int DefCycle; 3793 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3794 // (regno / 2) + (regno % 2) + 1 3795 DefCycle = RegNo / 2 + 1; 3796 if (RegNo % 2) 3797 ++DefCycle; 3798 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3799 DefCycle = RegNo; 3800 bool isSLoad = false; 3801 3802 switch (DefMCID.getOpcode()) { 3803 default: break; 3804 case ARM::VLDMSIA: 3805 case ARM::VLDMSIA_UPD: 3806 case ARM::VLDMSDB_UPD: 3807 isSLoad = true; 3808 break; 3809 } 3810 3811 // If there are odd number of 'S' registers or if it's not 64-bit aligned, 3812 // then it takes an extra cycle. 3813 if ((isSLoad && (RegNo % 2)) || DefAlign < 8) 3814 ++DefCycle; 3815 } else { 3816 // Assume the worst. 3817 DefCycle = RegNo + 2; 3818 } 3819 3820 return DefCycle; 3821 } 3822 3823 int 3824 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData, 3825 const MCInstrDesc &DefMCID, 3826 unsigned DefClass, 3827 unsigned DefIdx, unsigned DefAlign) const { 3828 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1; 3829 if (RegNo <= 0) 3830 // Def is the address writeback. 3831 return ItinData->getOperandCycle(DefClass, DefIdx); 3832 3833 int DefCycle; 3834 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3835 // 4 registers would be issued: 1, 2, 1. 3836 // 5 registers would be issued: 1, 2, 2. 3837 DefCycle = RegNo / 2; 3838 if (DefCycle < 1) 3839 DefCycle = 1; 3840 // Result latency is issue cycle + 2: E2. 3841 DefCycle += 2; 3842 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3843 DefCycle = (RegNo / 2); 3844 // If there are odd number of registers or if it's not 64-bit aligned, 3845 // then it takes an extra AGU (Address Generation Unit) cycle. 3846 if ((RegNo % 2) || DefAlign < 8) 3847 ++DefCycle; 3848 // Result latency is AGU cycles + 2. 3849 DefCycle += 2; 3850 } else { 3851 // Assume the worst. 3852 DefCycle = RegNo + 2; 3853 } 3854 3855 return DefCycle; 3856 } 3857 3858 int 3859 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData, 3860 const MCInstrDesc &UseMCID, 3861 unsigned UseClass, 3862 unsigned UseIdx, unsigned UseAlign) const { 3863 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1; 3864 if (RegNo <= 0) 3865 return ItinData->getOperandCycle(UseClass, UseIdx); 3866 3867 int UseCycle; 3868 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3869 // (regno / 2) + (regno % 2) + 1 3870 UseCycle = RegNo / 2 + 1; 3871 if (RegNo % 2) 3872 ++UseCycle; 3873 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3874 UseCycle = RegNo; 3875 bool isSStore = false; 3876 3877 switch (UseMCID.getOpcode()) { 3878 default: break; 3879 case ARM::VSTMSIA: 3880 case ARM::VSTMSIA_UPD: 3881 case ARM::VSTMSDB_UPD: 3882 isSStore = true; 3883 break; 3884 } 3885 3886 // If there are odd number of 'S' registers or if it's not 64-bit aligned, 3887 // then it takes an extra cycle. 3888 if ((isSStore && (RegNo % 2)) || UseAlign < 8) 3889 ++UseCycle; 3890 } else { 3891 // Assume the worst. 3892 UseCycle = RegNo + 2; 3893 } 3894 3895 return UseCycle; 3896 } 3897 3898 int 3899 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData, 3900 const MCInstrDesc &UseMCID, 3901 unsigned UseClass, 3902 unsigned UseIdx, unsigned UseAlign) const { 3903 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1; 3904 if (RegNo <= 0) 3905 return ItinData->getOperandCycle(UseClass, UseIdx); 3906 3907 int UseCycle; 3908 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) { 3909 UseCycle = RegNo / 2; 3910 if (UseCycle < 2) 3911 UseCycle = 2; 3912 // Read in E3. 3913 UseCycle += 2; 3914 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) { 3915 UseCycle = (RegNo / 2); 3916 // If there are odd number of registers or if it's not 64-bit aligned, 3917 // then it takes an extra AGU (Address Generation Unit) cycle. 3918 if ((RegNo % 2) || UseAlign < 8) 3919 ++UseCycle; 3920 } else { 3921 // Assume the worst. 3922 UseCycle = 1; 3923 } 3924 return UseCycle; 3925 } 3926 3927 int 3928 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 3929 const MCInstrDesc &DefMCID, 3930 unsigned DefIdx, unsigned DefAlign, 3931 const MCInstrDesc &UseMCID, 3932 unsigned UseIdx, unsigned UseAlign) const { 3933 unsigned DefClass = DefMCID.getSchedClass(); 3934 unsigned UseClass = UseMCID.getSchedClass(); 3935 3936 if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands()) 3937 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 3938 3939 // This may be a def / use of a variable_ops instruction, the operand 3940 // latency might be determinable dynamically. Let the target try to 3941 // figure it out. 3942 int DefCycle = -1; 3943 bool LdmBypass = false; 3944 switch (DefMCID.getOpcode()) { 3945 default: 3946 DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); 3947 break; 3948 3949 case ARM::VLDMDIA: 3950 case ARM::VLDMDIA_UPD: 3951 case ARM::VLDMDDB_UPD: 3952 case ARM::VLDMSIA: 3953 case ARM::VLDMSIA_UPD: 3954 case ARM::VLDMSDB_UPD: 3955 DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign); 3956 break; 3957 3958 case ARM::LDMIA_RET: 3959 case ARM::LDMIA: 3960 case ARM::LDMDA: 3961 case ARM::LDMDB: 3962 case ARM::LDMIB: 3963 case ARM::LDMIA_UPD: 3964 case ARM::LDMDA_UPD: 3965 case ARM::LDMDB_UPD: 3966 case ARM::LDMIB_UPD: 3967 case ARM::tLDMIA: 3968 case ARM::tLDMIA_UPD: 3969 case ARM::tPUSH: 3970 case ARM::t2LDMIA_RET: 3971 case ARM::t2LDMIA: 3972 case ARM::t2LDMDB: 3973 case ARM::t2LDMIA_UPD: 3974 case ARM::t2LDMDB_UPD: 3975 LdmBypass = true; 3976 DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign); 3977 break; 3978 } 3979 3980 if (DefCycle == -1) 3981 // We can't seem to determine the result latency of the def, assume it's 2. 3982 DefCycle = 2; 3983 3984 int UseCycle = -1; 3985 switch (UseMCID.getOpcode()) { 3986 default: 3987 UseCycle = ItinData->getOperandCycle(UseClass, UseIdx); 3988 break; 3989 3990 case ARM::VSTMDIA: 3991 case ARM::VSTMDIA_UPD: 3992 case ARM::VSTMDDB_UPD: 3993 case ARM::VSTMSIA: 3994 case ARM::VSTMSIA_UPD: 3995 case ARM::VSTMSDB_UPD: 3996 UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign); 3997 break; 3998 3999 case ARM::STMIA: 4000 case ARM::STMDA: 4001 case ARM::STMDB: 4002 case ARM::STMIB: 4003 case ARM::STMIA_UPD: 4004 case ARM::STMDA_UPD: 4005 case ARM::STMDB_UPD: 4006 case ARM::STMIB_UPD: 4007 case ARM::tSTMIA_UPD: 4008 case ARM::tPOP_RET: 4009 case ARM::tPOP: 4010 case ARM::t2STMIA: 4011 case ARM::t2STMDB: 4012 case ARM::t2STMIA_UPD: 4013 case ARM::t2STMDB_UPD: 4014 UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign); 4015 break; 4016 } 4017 4018 if (UseCycle == -1) 4019 // Assume it's read in the first stage. 4020 UseCycle = 1; 4021 4022 UseCycle = DefCycle - UseCycle + 1; 4023 if (UseCycle > 0) { 4024 if (LdmBypass) { 4025 // It's a variable_ops instruction so we can't use DefIdx here. Just use 4026 // first def operand. 4027 if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1, 4028 UseClass, UseIdx)) 4029 --UseCycle; 4030 } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx, 4031 UseClass, UseIdx)) { 4032 --UseCycle; 4033 } 4034 } 4035 4036 return UseCycle; 4037 } 4038 4039 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI, 4040 const MachineInstr *MI, unsigned Reg, 4041 unsigned &DefIdx, unsigned &Dist) { 4042 Dist = 0; 4043 4044 MachineBasicBlock::const_iterator I = MI; ++I; 4045 MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator()); 4046 assert(II->isInsideBundle() && "Empty bundle?"); 4047 4048 int Idx = -1; 4049 while (II->isInsideBundle()) { 4050 Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI); 4051 if (Idx != -1) 4052 break; 4053 --II; 4054 ++Dist; 4055 } 4056 4057 assert(Idx != -1 && "Cannot find bundled definition!"); 4058 DefIdx = Idx; 4059 return &*II; 4060 } 4061 4062 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI, 4063 const MachineInstr &MI, unsigned Reg, 4064 unsigned &UseIdx, unsigned &Dist) { 4065 Dist = 0; 4066 4067 MachineBasicBlock::const_instr_iterator II = ++MI.getIterator(); 4068 assert(II->isInsideBundle() && "Empty bundle?"); 4069 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 4070 4071 // FIXME: This doesn't properly handle multiple uses. 4072 int Idx = -1; 4073 while (II != E && II->isInsideBundle()) { 4074 Idx = II->findRegisterUseOperandIdx(Reg, false, TRI); 4075 if (Idx != -1) 4076 break; 4077 if (II->getOpcode() != ARM::t2IT) 4078 ++Dist; 4079 ++II; 4080 } 4081 4082 if (Idx == -1) { 4083 Dist = 0; 4084 return nullptr; 4085 } 4086 4087 UseIdx = Idx; 4088 return &*II; 4089 } 4090 4091 /// Return the number of cycles to add to (or subtract from) the static 4092 /// itinerary based on the def opcode and alignment. The caller will ensure that 4093 /// adjusted latency is at least one cycle. 4094 static int adjustDefLatency(const ARMSubtarget &Subtarget, 4095 const MachineInstr &DefMI, 4096 const MCInstrDesc &DefMCID, unsigned DefAlign) { 4097 int Adjust = 0; 4098 if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) { 4099 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2] 4100 // variants are one cycle cheaper. 4101 switch (DefMCID.getOpcode()) { 4102 default: break; 4103 case ARM::LDRrs: 4104 case ARM::LDRBrs: { 4105 unsigned ShOpVal = DefMI.getOperand(3).getImm(); 4106 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4107 if (ShImm == 0 || 4108 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) 4109 --Adjust; 4110 break; 4111 } 4112 case ARM::t2LDRs: 4113 case ARM::t2LDRBs: 4114 case ARM::t2LDRHs: 4115 case ARM::t2LDRSHs: { 4116 // Thumb2 mode: lsl only. 4117 unsigned ShAmt = DefMI.getOperand(3).getImm(); 4118 if (ShAmt == 0 || ShAmt == 2) 4119 --Adjust; 4120 break; 4121 } 4122 } 4123 } else if (Subtarget.isSwift()) { 4124 // FIXME: Properly handle all of the latency adjustments for address 4125 // writeback. 4126 switch (DefMCID.getOpcode()) { 4127 default: break; 4128 case ARM::LDRrs: 4129 case ARM::LDRBrs: { 4130 unsigned ShOpVal = DefMI.getOperand(3).getImm(); 4131 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub; 4132 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4133 if (!isSub && 4134 (ShImm == 0 || 4135 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 4136 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))) 4137 Adjust -= 2; 4138 else if (!isSub && 4139 ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr) 4140 --Adjust; 4141 break; 4142 } 4143 case ARM::t2LDRs: 4144 case ARM::t2LDRBs: 4145 case ARM::t2LDRHs: 4146 case ARM::t2LDRSHs: { 4147 // Thumb2 mode: lsl only. 4148 unsigned ShAmt = DefMI.getOperand(3).getImm(); 4149 if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3) 4150 Adjust -= 2; 4151 break; 4152 } 4153 } 4154 } 4155 4156 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) { 4157 switch (DefMCID.getOpcode()) { 4158 default: break; 4159 case ARM::VLD1q8: 4160 case ARM::VLD1q16: 4161 case ARM::VLD1q32: 4162 case ARM::VLD1q64: 4163 case ARM::VLD1q8wb_fixed: 4164 case ARM::VLD1q16wb_fixed: 4165 case ARM::VLD1q32wb_fixed: 4166 case ARM::VLD1q64wb_fixed: 4167 case ARM::VLD1q8wb_register: 4168 case ARM::VLD1q16wb_register: 4169 case ARM::VLD1q32wb_register: 4170 case ARM::VLD1q64wb_register: 4171 case ARM::VLD2d8: 4172 case ARM::VLD2d16: 4173 case ARM::VLD2d32: 4174 case ARM::VLD2q8: 4175 case ARM::VLD2q16: 4176 case ARM::VLD2q32: 4177 case ARM::VLD2d8wb_fixed: 4178 case ARM::VLD2d16wb_fixed: 4179 case ARM::VLD2d32wb_fixed: 4180 case ARM::VLD2q8wb_fixed: 4181 case ARM::VLD2q16wb_fixed: 4182 case ARM::VLD2q32wb_fixed: 4183 case ARM::VLD2d8wb_register: 4184 case ARM::VLD2d16wb_register: 4185 case ARM::VLD2d32wb_register: 4186 case ARM::VLD2q8wb_register: 4187 case ARM::VLD2q16wb_register: 4188 case ARM::VLD2q32wb_register: 4189 case ARM::VLD3d8: 4190 case ARM::VLD3d16: 4191 case ARM::VLD3d32: 4192 case ARM::VLD1d64T: 4193 case ARM::VLD3d8_UPD: 4194 case ARM::VLD3d16_UPD: 4195 case ARM::VLD3d32_UPD: 4196 case ARM::VLD1d64Twb_fixed: 4197 case ARM::VLD1d64Twb_register: 4198 case ARM::VLD3q8_UPD: 4199 case ARM::VLD3q16_UPD: 4200 case ARM::VLD3q32_UPD: 4201 case ARM::VLD4d8: 4202 case ARM::VLD4d16: 4203 case ARM::VLD4d32: 4204 case ARM::VLD1d64Q: 4205 case ARM::VLD4d8_UPD: 4206 case ARM::VLD4d16_UPD: 4207 case ARM::VLD4d32_UPD: 4208 case ARM::VLD1d64Qwb_fixed: 4209 case ARM::VLD1d64Qwb_register: 4210 case ARM::VLD4q8_UPD: 4211 case ARM::VLD4q16_UPD: 4212 case ARM::VLD4q32_UPD: 4213 case ARM::VLD1DUPq8: 4214 case ARM::VLD1DUPq16: 4215 case ARM::VLD1DUPq32: 4216 case ARM::VLD1DUPq8wb_fixed: 4217 case ARM::VLD1DUPq16wb_fixed: 4218 case ARM::VLD1DUPq32wb_fixed: 4219 case ARM::VLD1DUPq8wb_register: 4220 case ARM::VLD1DUPq16wb_register: 4221 case ARM::VLD1DUPq32wb_register: 4222 case ARM::VLD2DUPd8: 4223 case ARM::VLD2DUPd16: 4224 case ARM::VLD2DUPd32: 4225 case ARM::VLD2DUPd8wb_fixed: 4226 case ARM::VLD2DUPd16wb_fixed: 4227 case ARM::VLD2DUPd32wb_fixed: 4228 case ARM::VLD2DUPd8wb_register: 4229 case ARM::VLD2DUPd16wb_register: 4230 case ARM::VLD2DUPd32wb_register: 4231 case ARM::VLD4DUPd8: 4232 case ARM::VLD4DUPd16: 4233 case ARM::VLD4DUPd32: 4234 case ARM::VLD4DUPd8_UPD: 4235 case ARM::VLD4DUPd16_UPD: 4236 case ARM::VLD4DUPd32_UPD: 4237 case ARM::VLD1LNd8: 4238 case ARM::VLD1LNd16: 4239 case ARM::VLD1LNd32: 4240 case ARM::VLD1LNd8_UPD: 4241 case ARM::VLD1LNd16_UPD: 4242 case ARM::VLD1LNd32_UPD: 4243 case ARM::VLD2LNd8: 4244 case ARM::VLD2LNd16: 4245 case ARM::VLD2LNd32: 4246 case ARM::VLD2LNq16: 4247 case ARM::VLD2LNq32: 4248 case ARM::VLD2LNd8_UPD: 4249 case ARM::VLD2LNd16_UPD: 4250 case ARM::VLD2LNd32_UPD: 4251 case ARM::VLD2LNq16_UPD: 4252 case ARM::VLD2LNq32_UPD: 4253 case ARM::VLD4LNd8: 4254 case ARM::VLD4LNd16: 4255 case ARM::VLD4LNd32: 4256 case ARM::VLD4LNq16: 4257 case ARM::VLD4LNq32: 4258 case ARM::VLD4LNd8_UPD: 4259 case ARM::VLD4LNd16_UPD: 4260 case ARM::VLD4LNd32_UPD: 4261 case ARM::VLD4LNq16_UPD: 4262 case ARM::VLD4LNq32_UPD: 4263 // If the address is not 64-bit aligned, the latencies of these 4264 // instructions increases by one. 4265 ++Adjust; 4266 break; 4267 } 4268 } 4269 return Adjust; 4270 } 4271 4272 int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 4273 const MachineInstr &DefMI, 4274 unsigned DefIdx, 4275 const MachineInstr &UseMI, 4276 unsigned UseIdx) const { 4277 // No operand latency. The caller may fall back to getInstrLatency. 4278 if (!ItinData || ItinData->isEmpty()) 4279 return -1; 4280 4281 const MachineOperand &DefMO = DefMI.getOperand(DefIdx); 4282 Register Reg = DefMO.getReg(); 4283 4284 const MachineInstr *ResolvedDefMI = &DefMI; 4285 unsigned DefAdj = 0; 4286 if (DefMI.isBundle()) 4287 ResolvedDefMI = 4288 getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj); 4289 if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() || 4290 ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) { 4291 return 1; 4292 } 4293 4294 const MachineInstr *ResolvedUseMI = &UseMI; 4295 unsigned UseAdj = 0; 4296 if (UseMI.isBundle()) { 4297 ResolvedUseMI = 4298 getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj); 4299 if (!ResolvedUseMI) 4300 return -1; 4301 } 4302 4303 return getOperandLatencyImpl( 4304 ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO, 4305 Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj); 4306 } 4307 4308 int ARMBaseInstrInfo::getOperandLatencyImpl( 4309 const InstrItineraryData *ItinData, const MachineInstr &DefMI, 4310 unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj, 4311 const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI, 4312 unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const { 4313 if (Reg == ARM::CPSR) { 4314 if (DefMI.getOpcode() == ARM::FMSTAT) { 4315 // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?) 4316 return Subtarget.isLikeA9() ? 1 : 20; 4317 } 4318 4319 // CPSR set and branch can be paired in the same cycle. 4320 if (UseMI.isBranch()) 4321 return 0; 4322 4323 // Otherwise it takes the instruction latency (generally one). 4324 unsigned Latency = getInstrLatency(ItinData, DefMI); 4325 4326 // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to 4327 // its uses. Instructions which are otherwise scheduled between them may 4328 // incur a code size penalty (not able to use the CPSR setting 16-bit 4329 // instructions). 4330 if (Latency > 0 && Subtarget.isThumb2()) { 4331 const MachineFunction *MF = DefMI.getParent()->getParent(); 4332 // FIXME: Use Function::hasOptSize(). 4333 if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize)) 4334 --Latency; 4335 } 4336 return Latency; 4337 } 4338 4339 if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit()) 4340 return -1; 4341 4342 unsigned DefAlign = DefMI.hasOneMemOperand() 4343 ? (*DefMI.memoperands_begin())->getAlign().value() 4344 : 0; 4345 unsigned UseAlign = UseMI.hasOneMemOperand() 4346 ? (*UseMI.memoperands_begin())->getAlign().value() 4347 : 0; 4348 4349 // Get the itinerary's latency if possible, and handle variable_ops. 4350 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID, 4351 UseIdx, UseAlign); 4352 // Unable to find operand latency. The caller may resort to getInstrLatency. 4353 if (Latency < 0) 4354 return Latency; 4355 4356 // Adjust for IT block position. 4357 int Adj = DefAdj + UseAdj; 4358 4359 // Adjust for dynamic def-side opcode variants not captured by the itinerary. 4360 Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign); 4361 if (Adj >= 0 || (int)Latency > -Adj) { 4362 return Latency + Adj; 4363 } 4364 // Return the itinerary latency, which may be zero but not less than zero. 4365 return Latency; 4366 } 4367 4368 int 4369 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 4370 SDNode *DefNode, unsigned DefIdx, 4371 SDNode *UseNode, unsigned UseIdx) const { 4372 if (!DefNode->isMachineOpcode()) 4373 return 1; 4374 4375 const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode()); 4376 4377 if (isZeroCost(DefMCID.Opcode)) 4378 return 0; 4379 4380 if (!ItinData || ItinData->isEmpty()) 4381 return DefMCID.mayLoad() ? 3 : 1; 4382 4383 if (!UseNode->isMachineOpcode()) { 4384 int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx); 4385 int Adj = Subtarget.getPreISelOperandLatencyAdjustment(); 4386 int Threshold = 1 + Adj; 4387 return Latency <= Threshold ? 1 : Latency - Adj; 4388 } 4389 4390 const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode()); 4391 auto *DefMN = cast<MachineSDNode>(DefNode); 4392 unsigned DefAlign = !DefMN->memoperands_empty() 4393 ? (*DefMN->memoperands_begin())->getAlign().value() 4394 : 0; 4395 auto *UseMN = cast<MachineSDNode>(UseNode); 4396 unsigned UseAlign = !UseMN->memoperands_empty() 4397 ? (*UseMN->memoperands_begin())->getAlign().value() 4398 : 0; 4399 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, 4400 UseMCID, UseIdx, UseAlign); 4401 4402 if (Latency > 1 && 4403 (Subtarget.isCortexA8() || Subtarget.isLikeA9() || 4404 Subtarget.isCortexA7())) { 4405 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2] 4406 // variants are one cycle cheaper. 4407 switch (DefMCID.getOpcode()) { 4408 default: break; 4409 case ARM::LDRrs: 4410 case ARM::LDRBrs: { 4411 unsigned ShOpVal = 4412 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue(); 4413 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4414 if (ShImm == 0 || 4415 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) 4416 --Latency; 4417 break; 4418 } 4419 case ARM::t2LDRs: 4420 case ARM::t2LDRBs: 4421 case ARM::t2LDRHs: 4422 case ARM::t2LDRSHs: { 4423 // Thumb2 mode: lsl only. 4424 unsigned ShAmt = 4425 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue(); 4426 if (ShAmt == 0 || ShAmt == 2) 4427 --Latency; 4428 break; 4429 } 4430 } 4431 } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) { 4432 // FIXME: Properly handle all of the latency adjustments for address 4433 // writeback. 4434 switch (DefMCID.getOpcode()) { 4435 default: break; 4436 case ARM::LDRrs: 4437 case ARM::LDRBrs: { 4438 unsigned ShOpVal = 4439 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue(); 4440 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal); 4441 if (ShImm == 0 || 4442 ((ShImm == 1 || ShImm == 2 || ShImm == 3) && 4443 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)) 4444 Latency -= 2; 4445 else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr) 4446 --Latency; 4447 break; 4448 } 4449 case ARM::t2LDRs: 4450 case ARM::t2LDRBs: 4451 case ARM::t2LDRHs: 4452 case ARM::t2LDRSHs: 4453 // Thumb2 mode: lsl 0-3 only. 4454 Latency -= 2; 4455 break; 4456 } 4457 } 4458 4459 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) 4460 switch (DefMCID.getOpcode()) { 4461 default: break; 4462 case ARM::VLD1q8: 4463 case ARM::VLD1q16: 4464 case ARM::VLD1q32: 4465 case ARM::VLD1q64: 4466 case ARM::VLD1q8wb_register: 4467 case ARM::VLD1q16wb_register: 4468 case ARM::VLD1q32wb_register: 4469 case ARM::VLD1q64wb_register: 4470 case ARM::VLD1q8wb_fixed: 4471 case ARM::VLD1q16wb_fixed: 4472 case ARM::VLD1q32wb_fixed: 4473 case ARM::VLD1q64wb_fixed: 4474 case ARM::VLD2d8: 4475 case ARM::VLD2d16: 4476 case ARM::VLD2d32: 4477 case ARM::VLD2q8Pseudo: 4478 case ARM::VLD2q16Pseudo: 4479 case ARM::VLD2q32Pseudo: 4480 case ARM::VLD2d8wb_fixed: 4481 case ARM::VLD2d16wb_fixed: 4482 case ARM::VLD2d32wb_fixed: 4483 case ARM::VLD2q8PseudoWB_fixed: 4484 case ARM::VLD2q16PseudoWB_fixed: 4485 case ARM::VLD2q32PseudoWB_fixed: 4486 case ARM::VLD2d8wb_register: 4487 case ARM::VLD2d16wb_register: 4488 case ARM::VLD2d32wb_register: 4489 case ARM::VLD2q8PseudoWB_register: 4490 case ARM::VLD2q16PseudoWB_register: 4491 case ARM::VLD2q32PseudoWB_register: 4492 case ARM::VLD3d8Pseudo: 4493 case ARM::VLD3d16Pseudo: 4494 case ARM::VLD3d32Pseudo: 4495 case ARM::VLD1d8TPseudo: 4496 case ARM::VLD1d16TPseudo: 4497 case ARM::VLD1d32TPseudo: 4498 case ARM::VLD1d64TPseudo: 4499 case ARM::VLD1d64TPseudoWB_fixed: 4500 case ARM::VLD1d64TPseudoWB_register: 4501 case ARM::VLD3d8Pseudo_UPD: 4502 case ARM::VLD3d16Pseudo_UPD: 4503 case ARM::VLD3d32Pseudo_UPD: 4504 case ARM::VLD3q8Pseudo_UPD: 4505 case ARM::VLD3q16Pseudo_UPD: 4506 case ARM::VLD3q32Pseudo_UPD: 4507 case ARM::VLD3q8oddPseudo: 4508 case ARM::VLD3q16oddPseudo: 4509 case ARM::VLD3q32oddPseudo: 4510 case ARM::VLD3q8oddPseudo_UPD: 4511 case ARM::VLD3q16oddPseudo_UPD: 4512 case ARM::VLD3q32oddPseudo_UPD: 4513 case ARM::VLD4d8Pseudo: 4514 case ARM::VLD4d16Pseudo: 4515 case ARM::VLD4d32Pseudo: 4516 case ARM::VLD1d8QPseudo: 4517 case ARM::VLD1d16QPseudo: 4518 case ARM::VLD1d32QPseudo: 4519 case ARM::VLD1d64QPseudo: 4520 case ARM::VLD1d64QPseudoWB_fixed: 4521 case ARM::VLD1d64QPseudoWB_register: 4522 case ARM::VLD1q8HighQPseudo: 4523 case ARM::VLD1q8LowQPseudo_UPD: 4524 case ARM::VLD1q8HighTPseudo: 4525 case ARM::VLD1q8LowTPseudo_UPD: 4526 case ARM::VLD1q16HighQPseudo: 4527 case ARM::VLD1q16LowQPseudo_UPD: 4528 case ARM::VLD1q16HighTPseudo: 4529 case ARM::VLD1q16LowTPseudo_UPD: 4530 case ARM::VLD1q32HighQPseudo: 4531 case ARM::VLD1q32LowQPseudo_UPD: 4532 case ARM::VLD1q32HighTPseudo: 4533 case ARM::VLD1q32LowTPseudo_UPD: 4534 case ARM::VLD1q64HighQPseudo: 4535 case ARM::VLD1q64LowQPseudo_UPD: 4536 case ARM::VLD1q64HighTPseudo: 4537 case ARM::VLD1q64LowTPseudo_UPD: 4538 case ARM::VLD4d8Pseudo_UPD: 4539 case ARM::VLD4d16Pseudo_UPD: 4540 case ARM::VLD4d32Pseudo_UPD: 4541 case ARM::VLD4q8Pseudo_UPD: 4542 case ARM::VLD4q16Pseudo_UPD: 4543 case ARM::VLD4q32Pseudo_UPD: 4544 case ARM::VLD4q8oddPseudo: 4545 case ARM::VLD4q16oddPseudo: 4546 case ARM::VLD4q32oddPseudo: 4547 case ARM::VLD4q8oddPseudo_UPD: 4548 case ARM::VLD4q16oddPseudo_UPD: 4549 case ARM::VLD4q32oddPseudo_UPD: 4550 case ARM::VLD1DUPq8: 4551 case ARM::VLD1DUPq16: 4552 case ARM::VLD1DUPq32: 4553 case ARM::VLD1DUPq8wb_fixed: 4554 case ARM::VLD1DUPq16wb_fixed: 4555 case ARM::VLD1DUPq32wb_fixed: 4556 case ARM::VLD1DUPq8wb_register: 4557 case ARM::VLD1DUPq16wb_register: 4558 case ARM::VLD1DUPq32wb_register: 4559 case ARM::VLD2DUPd8: 4560 case ARM::VLD2DUPd16: 4561 case ARM::VLD2DUPd32: 4562 case ARM::VLD2DUPd8wb_fixed: 4563 case ARM::VLD2DUPd16wb_fixed: 4564 case ARM::VLD2DUPd32wb_fixed: 4565 case ARM::VLD2DUPd8wb_register: 4566 case ARM::VLD2DUPd16wb_register: 4567 case ARM::VLD2DUPd32wb_register: 4568 case ARM::VLD2DUPq8EvenPseudo: 4569 case ARM::VLD2DUPq8OddPseudo: 4570 case ARM::VLD2DUPq16EvenPseudo: 4571 case ARM::VLD2DUPq16OddPseudo: 4572 case ARM::VLD2DUPq32EvenPseudo: 4573 case ARM::VLD2DUPq32OddPseudo: 4574 case ARM::VLD3DUPq8EvenPseudo: 4575 case ARM::VLD3DUPq8OddPseudo: 4576 case ARM::VLD3DUPq16EvenPseudo: 4577 case ARM::VLD3DUPq16OddPseudo: 4578 case ARM::VLD3DUPq32EvenPseudo: 4579 case ARM::VLD3DUPq32OddPseudo: 4580 case ARM::VLD4DUPd8Pseudo: 4581 case ARM::VLD4DUPd16Pseudo: 4582 case ARM::VLD4DUPd32Pseudo: 4583 case ARM::VLD4DUPd8Pseudo_UPD: 4584 case ARM::VLD4DUPd16Pseudo_UPD: 4585 case ARM::VLD4DUPd32Pseudo_UPD: 4586 case ARM::VLD4DUPq8EvenPseudo: 4587 case ARM::VLD4DUPq8OddPseudo: 4588 case ARM::VLD4DUPq16EvenPseudo: 4589 case ARM::VLD4DUPq16OddPseudo: 4590 case ARM::VLD4DUPq32EvenPseudo: 4591 case ARM::VLD4DUPq32OddPseudo: 4592 case ARM::VLD1LNq8Pseudo: 4593 case ARM::VLD1LNq16Pseudo: 4594 case ARM::VLD1LNq32Pseudo: 4595 case ARM::VLD1LNq8Pseudo_UPD: 4596 case ARM::VLD1LNq16Pseudo_UPD: 4597 case ARM::VLD1LNq32Pseudo_UPD: 4598 case ARM::VLD2LNd8Pseudo: 4599 case ARM::VLD2LNd16Pseudo: 4600 case ARM::VLD2LNd32Pseudo: 4601 case ARM::VLD2LNq16Pseudo: 4602 case ARM::VLD2LNq32Pseudo: 4603 case ARM::VLD2LNd8Pseudo_UPD: 4604 case ARM::VLD2LNd16Pseudo_UPD: 4605 case ARM::VLD2LNd32Pseudo_UPD: 4606 case ARM::VLD2LNq16Pseudo_UPD: 4607 case ARM::VLD2LNq32Pseudo_UPD: 4608 case ARM::VLD4LNd8Pseudo: 4609 case ARM::VLD4LNd16Pseudo: 4610 case ARM::VLD4LNd32Pseudo: 4611 case ARM::VLD4LNq16Pseudo: 4612 case ARM::VLD4LNq32Pseudo: 4613 case ARM::VLD4LNd8Pseudo_UPD: 4614 case ARM::VLD4LNd16Pseudo_UPD: 4615 case ARM::VLD4LNd32Pseudo_UPD: 4616 case ARM::VLD4LNq16Pseudo_UPD: 4617 case ARM::VLD4LNq32Pseudo_UPD: 4618 // If the address is not 64-bit aligned, the latencies of these 4619 // instructions increases by one. 4620 ++Latency; 4621 break; 4622 } 4623 4624 return Latency; 4625 } 4626 4627 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const { 4628 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() || 4629 MI.isImplicitDef()) 4630 return 0; 4631 4632 if (MI.isBundle()) 4633 return 0; 4634 4635 const MCInstrDesc &MCID = MI.getDesc(); 4636 4637 if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) && 4638 !Subtarget.cheapPredicableCPSRDef())) { 4639 // When predicated, CPSR is an additional source operand for CPSR updating 4640 // instructions, this apparently increases their latencies. 4641 return 1; 4642 } 4643 return 0; 4644 } 4645 4646 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 4647 const MachineInstr &MI, 4648 unsigned *PredCost) const { 4649 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() || 4650 MI.isImplicitDef()) 4651 return 1; 4652 4653 // An instruction scheduler typically runs on unbundled instructions, however 4654 // other passes may query the latency of a bundled instruction. 4655 if (MI.isBundle()) { 4656 unsigned Latency = 0; 4657 MachineBasicBlock::const_instr_iterator I = MI.getIterator(); 4658 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 4659 while (++I != E && I->isInsideBundle()) { 4660 if (I->getOpcode() != ARM::t2IT) 4661 Latency += getInstrLatency(ItinData, *I, PredCost); 4662 } 4663 return Latency; 4664 } 4665 4666 const MCInstrDesc &MCID = MI.getDesc(); 4667 if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) && 4668 !Subtarget.cheapPredicableCPSRDef()))) { 4669 // When predicated, CPSR is an additional source operand for CPSR updating 4670 // instructions, this apparently increases their latencies. 4671 *PredCost = 1; 4672 } 4673 // Be sure to call getStageLatency for an empty itinerary in case it has a 4674 // valid MinLatency property. 4675 if (!ItinData) 4676 return MI.mayLoad() ? 3 : 1; 4677 4678 unsigned Class = MCID.getSchedClass(); 4679 4680 // For instructions with variable uops, use uops as latency. 4681 if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0) 4682 return getNumMicroOps(ItinData, MI); 4683 4684 // For the common case, fall back on the itinerary's latency. 4685 unsigned Latency = ItinData->getStageLatency(Class); 4686 4687 // Adjust for dynamic def-side opcode variants not captured by the itinerary. 4688 unsigned DefAlign = 4689 MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlign().value() : 0; 4690 int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign); 4691 if (Adj >= 0 || (int)Latency > -Adj) { 4692 return Latency + Adj; 4693 } 4694 return Latency; 4695 } 4696 4697 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 4698 SDNode *Node) const { 4699 if (!Node->isMachineOpcode()) 4700 return 1; 4701 4702 if (!ItinData || ItinData->isEmpty()) 4703 return 1; 4704 4705 unsigned Opcode = Node->getMachineOpcode(); 4706 switch (Opcode) { 4707 default: 4708 return ItinData->getStageLatency(get(Opcode).getSchedClass()); 4709 case ARM::VLDMQIA: 4710 case ARM::VSTMQIA: 4711 return 2; 4712 } 4713 } 4714 4715 bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel, 4716 const MachineRegisterInfo *MRI, 4717 const MachineInstr &DefMI, 4718 unsigned DefIdx, 4719 const MachineInstr &UseMI, 4720 unsigned UseIdx) const { 4721 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask; 4722 unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask; 4723 if (Subtarget.nonpipelinedVFP() && 4724 (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP)) 4725 return true; 4726 4727 // Hoist VFP / NEON instructions with 4 or higher latency. 4728 unsigned Latency = 4729 SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx); 4730 if (Latency <= 3) 4731 return false; 4732 return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON || 4733 UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON; 4734 } 4735 4736 bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel, 4737 const MachineInstr &DefMI, 4738 unsigned DefIdx) const { 4739 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries(); 4740 if (!ItinData || ItinData->isEmpty()) 4741 return false; 4742 4743 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask; 4744 if (DDomain == ARMII::DomainGeneral) { 4745 unsigned DefClass = DefMI.getDesc().getSchedClass(); 4746 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); 4747 return (DefCycle != -1 && DefCycle <= 2); 4748 } 4749 return false; 4750 } 4751 4752 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI, 4753 StringRef &ErrInfo) const { 4754 if (convertAddSubFlagsOpcode(MI.getOpcode())) { 4755 ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG"; 4756 return false; 4757 } 4758 if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) { 4759 // Make sure we don't generate a lo-lo mov that isn't supported. 4760 if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) && 4761 !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) { 4762 ErrInfo = "Non-flag-setting Thumb1 mov is v6-only"; 4763 return false; 4764 } 4765 } 4766 if (MI.getOpcode() == ARM::tPUSH || 4767 MI.getOpcode() == ARM::tPOP || 4768 MI.getOpcode() == ARM::tPOP_RET) { 4769 for (int i = 2, e = MI.getNumOperands(); i < e; ++i) { 4770 if (MI.getOperand(i).isImplicit() || 4771 !MI.getOperand(i).isReg()) 4772 continue; 4773 Register Reg = MI.getOperand(i).getReg(); 4774 if (Reg < ARM::R0 || Reg > ARM::R7) { 4775 if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) && 4776 !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) { 4777 ErrInfo = "Unsupported register in Thumb1 push/pop"; 4778 return false; 4779 } 4780 } 4781 } 4782 } 4783 return true; 4784 } 4785 4786 // LoadStackGuard has so far only been implemented for MachO. Different code 4787 // sequence is needed for other targets. 4788 void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI, 4789 unsigned LoadImmOpc, 4790 unsigned LoadOpc) const { 4791 assert(!Subtarget.isROPI() && !Subtarget.isRWPI() && 4792 "ROPI/RWPI not currently supported with stack guard"); 4793 4794 MachineBasicBlock &MBB = *MI->getParent(); 4795 DebugLoc DL = MI->getDebugLoc(); 4796 Register Reg = MI->getOperand(0).getReg(); 4797 const GlobalValue *GV = 4798 cast<GlobalValue>((*MI->memoperands_begin())->getValue()); 4799 MachineInstrBuilder MIB; 4800 4801 BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg) 4802 .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY); 4803 4804 if (Subtarget.isGVIndirectSymbol(GV)) { 4805 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg); 4806 MIB.addReg(Reg, RegState::Kill).addImm(0); 4807 auto Flags = MachineMemOperand::MOLoad | 4808 MachineMemOperand::MODereferenceable | 4809 MachineMemOperand::MOInvariant; 4810 MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand( 4811 MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, Align(4)); 4812 MIB.addMemOperand(MMO).add(predOps(ARMCC::AL)); 4813 } 4814 4815 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg); 4816 MIB.addReg(Reg, RegState::Kill) 4817 .addImm(0) 4818 .cloneMemRefs(*MI) 4819 .add(predOps(ARMCC::AL)); 4820 } 4821 4822 bool 4823 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc, 4824 unsigned &AddSubOpc, 4825 bool &NegAcc, bool &HasLane) const { 4826 DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode); 4827 if (I == MLxEntryMap.end()) 4828 return false; 4829 4830 const ARM_MLxEntry &Entry = ARM_MLxTable[I->second]; 4831 MulOpc = Entry.MulOpc; 4832 AddSubOpc = Entry.AddSubOpc; 4833 NegAcc = Entry.NegAcc; 4834 HasLane = Entry.HasLane; 4835 return true; 4836 } 4837 4838 //===----------------------------------------------------------------------===// 4839 // Execution domains. 4840 //===----------------------------------------------------------------------===// 4841 // 4842 // Some instructions go down the NEON pipeline, some go down the VFP pipeline, 4843 // and some can go down both. The vmov instructions go down the VFP pipeline, 4844 // but they can be changed to vorr equivalents that are executed by the NEON 4845 // pipeline. 4846 // 4847 // We use the following execution domain numbering: 4848 // 4849 enum ARMExeDomain { 4850 ExeGeneric = 0, 4851 ExeVFP = 1, 4852 ExeNEON = 2 4853 }; 4854 4855 // 4856 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h 4857 // 4858 std::pair<uint16_t, uint16_t> 4859 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const { 4860 // If we don't have access to NEON instructions then we won't be able 4861 // to swizzle anything to the NEON domain. Check to make sure. 4862 if (Subtarget.hasNEON()) { 4863 // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON 4864 // if they are not predicated. 4865 if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI)) 4866 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON)); 4867 4868 // CortexA9 is particularly picky about mixing the two and wants these 4869 // converted. 4870 if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) && 4871 (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR || 4872 MI.getOpcode() == ARM::VMOVS)) 4873 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON)); 4874 } 4875 // No other instructions can be swizzled, so just determine their domain. 4876 unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask; 4877 4878 if (Domain & ARMII::DomainNEON) 4879 return std::make_pair(ExeNEON, 0); 4880 4881 // Certain instructions can go either way on Cortex-A8. 4882 // Treat them as NEON instructions. 4883 if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8()) 4884 return std::make_pair(ExeNEON, 0); 4885 4886 if (Domain & ARMII::DomainVFP) 4887 return std::make_pair(ExeVFP, 0); 4888 4889 return std::make_pair(ExeGeneric, 0); 4890 } 4891 4892 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI, 4893 unsigned SReg, unsigned &Lane) { 4894 unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass); 4895 Lane = 0; 4896 4897 if (DReg != ARM::NoRegister) 4898 return DReg; 4899 4900 Lane = 1; 4901 DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass); 4902 4903 assert(DReg && "S-register with no D super-register?"); 4904 return DReg; 4905 } 4906 4907 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane, 4908 /// set ImplicitSReg to a register number that must be marked as implicit-use or 4909 /// zero if no register needs to be defined as implicit-use. 4910 /// 4911 /// If the function cannot determine if an SPR should be marked implicit use or 4912 /// not, it returns false. 4913 /// 4914 /// This function handles cases where an instruction is being modified from taking 4915 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict 4916 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other 4917 /// lane of the DPR). 4918 /// 4919 /// If the other SPR is defined, an implicit-use of it should be added. Else, 4920 /// (including the case where the DPR itself is defined), it should not. 4921 /// 4922 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI, 4923 MachineInstr &MI, unsigned DReg, 4924 unsigned Lane, unsigned &ImplicitSReg) { 4925 // If the DPR is defined or used already, the other SPR lane will be chained 4926 // correctly, so there is nothing to be done. 4927 if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) { 4928 ImplicitSReg = 0; 4929 return true; 4930 } 4931 4932 // Otherwise we need to go searching to see if the SPR is set explicitly. 4933 ImplicitSReg = TRI->getSubReg(DReg, 4934 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1); 4935 MachineBasicBlock::LivenessQueryResult LQR = 4936 MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI); 4937 4938 if (LQR == MachineBasicBlock::LQR_Live) 4939 return true; 4940 else if (LQR == MachineBasicBlock::LQR_Unknown) 4941 return false; 4942 4943 // If the register is known not to be live, there is no need to add an 4944 // implicit-use. 4945 ImplicitSReg = 0; 4946 return true; 4947 } 4948 4949 void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI, 4950 unsigned Domain) const { 4951 unsigned DstReg, SrcReg, DReg; 4952 unsigned Lane; 4953 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI); 4954 const TargetRegisterInfo *TRI = &getRegisterInfo(); 4955 switch (MI.getOpcode()) { 4956 default: 4957 llvm_unreachable("cannot handle opcode!"); 4958 break; 4959 case ARM::VMOVD: 4960 if (Domain != ExeNEON) 4961 break; 4962 4963 // Zap the predicate operands. 4964 assert(!isPredicated(MI) && "Cannot predicate a VORRd"); 4965 4966 // Make sure we've got NEON instructions. 4967 assert(Subtarget.hasNEON() && "VORRd requires NEON"); 4968 4969 // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits) 4970 DstReg = MI.getOperand(0).getReg(); 4971 SrcReg = MI.getOperand(1).getReg(); 4972 4973 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 4974 MI.RemoveOperand(i - 1); 4975 4976 // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits) 4977 MI.setDesc(get(ARM::VORRd)); 4978 MIB.addReg(DstReg, RegState::Define) 4979 .addReg(SrcReg) 4980 .addReg(SrcReg) 4981 .add(predOps(ARMCC::AL)); 4982 break; 4983 case ARM::VMOVRS: 4984 if (Domain != ExeNEON) 4985 break; 4986 assert(!isPredicated(MI) && "Cannot predicate a VGETLN"); 4987 4988 // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits) 4989 DstReg = MI.getOperand(0).getReg(); 4990 SrcReg = MI.getOperand(1).getReg(); 4991 4992 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 4993 MI.RemoveOperand(i - 1); 4994 4995 DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane); 4996 4997 // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps) 4998 // Note that DSrc has been widened and the other lane may be undef, which 4999 // contaminates the entire register. 5000 MI.setDesc(get(ARM::VGETLNi32)); 5001 MIB.addReg(DstReg, RegState::Define) 5002 .addReg(DReg, RegState::Undef) 5003 .addImm(Lane) 5004 .add(predOps(ARMCC::AL)); 5005 5006 // The old source should be an implicit use, otherwise we might think it 5007 // was dead before here. 5008 MIB.addReg(SrcReg, RegState::Implicit); 5009 break; 5010 case ARM::VMOVSR: { 5011 if (Domain != ExeNEON) 5012 break; 5013 assert(!isPredicated(MI) && "Cannot predicate a VSETLN"); 5014 5015 // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits) 5016 DstReg = MI.getOperand(0).getReg(); 5017 SrcReg = MI.getOperand(1).getReg(); 5018 5019 DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane); 5020 5021 unsigned ImplicitSReg; 5022 if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg)) 5023 break; 5024 5025 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 5026 MI.RemoveOperand(i - 1); 5027 5028 // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps) 5029 // Again DDst may be undefined at the beginning of this instruction. 5030 MI.setDesc(get(ARM::VSETLNi32)); 5031 MIB.addReg(DReg, RegState::Define) 5032 .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI))) 5033 .addReg(SrcReg) 5034 .addImm(Lane) 5035 .add(predOps(ARMCC::AL)); 5036 5037 // The narrower destination must be marked as set to keep previous chains 5038 // in place. 5039 MIB.addReg(DstReg, RegState::Define | RegState::Implicit); 5040 if (ImplicitSReg != 0) 5041 MIB.addReg(ImplicitSReg, RegState::Implicit); 5042 break; 5043 } 5044 case ARM::VMOVS: { 5045 if (Domain != ExeNEON) 5046 break; 5047 5048 // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits) 5049 DstReg = MI.getOperand(0).getReg(); 5050 SrcReg = MI.getOperand(1).getReg(); 5051 5052 unsigned DstLane = 0, SrcLane = 0, DDst, DSrc; 5053 DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane); 5054 DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane); 5055 5056 unsigned ImplicitSReg; 5057 if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg)) 5058 break; 5059 5060 for (unsigned i = MI.getDesc().getNumOperands(); i; --i) 5061 MI.RemoveOperand(i - 1); 5062 5063 if (DSrc == DDst) { 5064 // Destination can be: 5065 // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits) 5066 MI.setDesc(get(ARM::VDUPLN32d)); 5067 MIB.addReg(DDst, RegState::Define) 5068 .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI))) 5069 .addImm(SrcLane) 5070 .add(predOps(ARMCC::AL)); 5071 5072 // Neither the source or the destination are naturally represented any 5073 // more, so add them in manually. 5074 MIB.addReg(DstReg, RegState::Implicit | RegState::Define); 5075 MIB.addReg(SrcReg, RegState::Implicit); 5076 if (ImplicitSReg != 0) 5077 MIB.addReg(ImplicitSReg, RegState::Implicit); 5078 break; 5079 } 5080 5081 // In general there's no single instruction that can perform an S <-> S 5082 // move in NEON space, but a pair of VEXT instructions *can* do the 5083 // job. It turns out that the VEXTs needed will only use DSrc once, with 5084 // the position based purely on the combination of lane-0 and lane-1 5085 // involved. For example 5086 // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1 5087 // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1 5088 // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1 5089 // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1 5090 // 5091 // Pattern of the MachineInstrs is: 5092 // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits) 5093 MachineInstrBuilder NewMIB; 5094 NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32), 5095 DDst); 5096 5097 // On the first instruction, both DSrc and DDst may be undef if present. 5098 // Specifically when the original instruction didn't have them as an 5099 // <imp-use>. 5100 unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst; 5101 bool CurUndef = !MI.readsRegister(CurReg, TRI); 5102 NewMIB.addReg(CurReg, getUndefRegState(CurUndef)); 5103 5104 CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst; 5105 CurUndef = !MI.readsRegister(CurReg, TRI); 5106 NewMIB.addReg(CurReg, getUndefRegState(CurUndef)) 5107 .addImm(1) 5108 .add(predOps(ARMCC::AL)); 5109 5110 if (SrcLane == DstLane) 5111 NewMIB.addReg(SrcReg, RegState::Implicit); 5112 5113 MI.setDesc(get(ARM::VEXTd32)); 5114 MIB.addReg(DDst, RegState::Define); 5115 5116 // On the second instruction, DDst has definitely been defined above, so 5117 // it is not undef. DSrc, if present, can be undef as above. 5118 CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst; 5119 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI); 5120 MIB.addReg(CurReg, getUndefRegState(CurUndef)); 5121 5122 CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst; 5123 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI); 5124 MIB.addReg(CurReg, getUndefRegState(CurUndef)) 5125 .addImm(1) 5126 .add(predOps(ARMCC::AL)); 5127 5128 if (SrcLane != DstLane) 5129 MIB.addReg(SrcReg, RegState::Implicit); 5130 5131 // As before, the original destination is no longer represented, add it 5132 // implicitly. 5133 MIB.addReg(DstReg, RegState::Define | RegState::Implicit); 5134 if (ImplicitSReg != 0) 5135 MIB.addReg(ImplicitSReg, RegState::Implicit); 5136 break; 5137 } 5138 } 5139 } 5140 5141 //===----------------------------------------------------------------------===// 5142 // Partial register updates 5143 //===----------------------------------------------------------------------===// 5144 // 5145 // Swift renames NEON registers with 64-bit granularity. That means any 5146 // instruction writing an S-reg implicitly reads the containing D-reg. The 5147 // problem is mostly avoided by translating f32 operations to v2f32 operations 5148 // on D-registers, but f32 loads are still a problem. 5149 // 5150 // These instructions can load an f32 into a NEON register: 5151 // 5152 // VLDRS - Only writes S, partial D update. 5153 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops. 5154 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops. 5155 // 5156 // FCONSTD can be used as a dependency-breaking instruction. 5157 unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance( 5158 const MachineInstr &MI, unsigned OpNum, 5159 const TargetRegisterInfo *TRI) const { 5160 auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance(); 5161 if (!PartialUpdateClearance) 5162 return 0; 5163 5164 assert(TRI && "Need TRI instance"); 5165 5166 const MachineOperand &MO = MI.getOperand(OpNum); 5167 if (MO.readsReg()) 5168 return 0; 5169 Register Reg = MO.getReg(); 5170 int UseOp = -1; 5171 5172 switch (MI.getOpcode()) { 5173 // Normal instructions writing only an S-register. 5174 case ARM::VLDRS: 5175 case ARM::FCONSTS: 5176 case ARM::VMOVSR: 5177 case ARM::VMOVv8i8: 5178 case ARM::VMOVv4i16: 5179 case ARM::VMOVv2i32: 5180 case ARM::VMOVv2f32: 5181 case ARM::VMOVv1i64: 5182 UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI); 5183 break; 5184 5185 // Explicitly reads the dependency. 5186 case ARM::VLD1LNd32: 5187 UseOp = 3; 5188 break; 5189 default: 5190 return 0; 5191 } 5192 5193 // If this instruction actually reads a value from Reg, there is no unwanted 5194 // dependency. 5195 if (UseOp != -1 && MI.getOperand(UseOp).readsReg()) 5196 return 0; 5197 5198 // We must be able to clobber the whole D-reg. 5199 if (Register::isVirtualRegister(Reg)) { 5200 // Virtual register must be a def undef foo:ssub_0 operand. 5201 if (!MO.getSubReg() || MI.readsVirtualRegister(Reg)) 5202 return 0; 5203 } else if (ARM::SPRRegClass.contains(Reg)) { 5204 // Physical register: MI must define the full D-reg. 5205 unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0, 5206 &ARM::DPRRegClass); 5207 if (!DReg || !MI.definesRegister(DReg, TRI)) 5208 return 0; 5209 } 5210 5211 // MI has an unwanted D-register dependency. 5212 // Avoid defs in the previous N instructrions. 5213 return PartialUpdateClearance; 5214 } 5215 5216 // Break a partial register dependency after getPartialRegUpdateClearance 5217 // returned non-zero. 5218 void ARMBaseInstrInfo::breakPartialRegDependency( 5219 MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const { 5220 assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def"); 5221 assert(TRI && "Need TRI instance"); 5222 5223 const MachineOperand &MO = MI.getOperand(OpNum); 5224 Register Reg = MO.getReg(); 5225 assert(Register::isPhysicalRegister(Reg) && 5226 "Can't break virtual register dependencies."); 5227 unsigned DReg = Reg; 5228 5229 // If MI defines an S-reg, find the corresponding D super-register. 5230 if (ARM::SPRRegClass.contains(Reg)) { 5231 DReg = ARM::D0 + (Reg - ARM::S0) / 2; 5232 assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken"); 5233 } 5234 5235 assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps"); 5236 assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg"); 5237 5238 // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines 5239 // the full D-register by loading the same value to both lanes. The 5240 // instruction is micro-coded with 2 uops, so don't do this until we can 5241 // properly schedule micro-coded instructions. The dispatcher stalls cause 5242 // too big regressions. 5243 5244 // Insert the dependency-breaking FCONSTD before MI. 5245 // 96 is the encoding of 0.5, but the actual value doesn't matter here. 5246 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg) 5247 .addImm(96) 5248 .add(predOps(ARMCC::AL)); 5249 MI.addRegisterKilled(DReg, TRI, true); 5250 } 5251 5252 bool ARMBaseInstrInfo::hasNOP() const { 5253 return Subtarget.getFeatureBits()[ARM::HasV6KOps]; 5254 } 5255 5256 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const { 5257 if (MI->getNumOperands() < 4) 5258 return true; 5259 unsigned ShOpVal = MI->getOperand(3).getImm(); 5260 unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal); 5261 // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1. 5262 if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) || 5263 ((ShImm == 1 || ShImm == 2) && 5264 ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl)) 5265 return true; 5266 5267 return false; 5268 } 5269 5270 bool ARMBaseInstrInfo::getRegSequenceLikeInputs( 5271 const MachineInstr &MI, unsigned DefIdx, 5272 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const { 5273 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index"); 5274 assert(MI.isRegSequenceLike() && "Invalid kind of instruction"); 5275 5276 switch (MI.getOpcode()) { 5277 case ARM::VMOVDRR: 5278 // dX = VMOVDRR rY, rZ 5279 // is the same as: 5280 // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1 5281 // Populate the InputRegs accordingly. 5282 // rY 5283 const MachineOperand *MOReg = &MI.getOperand(1); 5284 if (!MOReg->isUndef()) 5285 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(), 5286 MOReg->getSubReg(), ARM::ssub_0)); 5287 // rZ 5288 MOReg = &MI.getOperand(2); 5289 if (!MOReg->isUndef()) 5290 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(), 5291 MOReg->getSubReg(), ARM::ssub_1)); 5292 return true; 5293 } 5294 llvm_unreachable("Target dependent opcode missing"); 5295 } 5296 5297 bool ARMBaseInstrInfo::getExtractSubregLikeInputs( 5298 const MachineInstr &MI, unsigned DefIdx, 5299 RegSubRegPairAndIdx &InputReg) const { 5300 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index"); 5301 assert(MI.isExtractSubregLike() && "Invalid kind of instruction"); 5302 5303 switch (MI.getOpcode()) { 5304 case ARM::VMOVRRD: 5305 // rX, rY = VMOVRRD dZ 5306 // is the same as: 5307 // rX = EXTRACT_SUBREG dZ, ssub_0 5308 // rY = EXTRACT_SUBREG dZ, ssub_1 5309 const MachineOperand &MOReg = MI.getOperand(2); 5310 if (MOReg.isUndef()) 5311 return false; 5312 InputReg.Reg = MOReg.getReg(); 5313 InputReg.SubReg = MOReg.getSubReg(); 5314 InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1; 5315 return true; 5316 } 5317 llvm_unreachable("Target dependent opcode missing"); 5318 } 5319 5320 bool ARMBaseInstrInfo::getInsertSubregLikeInputs( 5321 const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, 5322 RegSubRegPairAndIdx &InsertedReg) const { 5323 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index"); 5324 assert(MI.isInsertSubregLike() && "Invalid kind of instruction"); 5325 5326 switch (MI.getOpcode()) { 5327 case ARM::VSETLNi32: 5328 // dX = VSETLNi32 dY, rZ, imm 5329 const MachineOperand &MOBaseReg = MI.getOperand(1); 5330 const MachineOperand &MOInsertedReg = MI.getOperand(2); 5331 if (MOInsertedReg.isUndef()) 5332 return false; 5333 const MachineOperand &MOIndex = MI.getOperand(3); 5334 BaseReg.Reg = MOBaseReg.getReg(); 5335 BaseReg.SubReg = MOBaseReg.getSubReg(); 5336 5337 InsertedReg.Reg = MOInsertedReg.getReg(); 5338 InsertedReg.SubReg = MOInsertedReg.getSubReg(); 5339 InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1; 5340 return true; 5341 } 5342 llvm_unreachable("Target dependent opcode missing"); 5343 } 5344 5345 std::pair<unsigned, unsigned> 5346 ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const { 5347 const unsigned Mask = ARMII::MO_OPTION_MASK; 5348 return std::make_pair(TF & Mask, TF & ~Mask); 5349 } 5350 5351 ArrayRef<std::pair<unsigned, const char *>> 5352 ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const { 5353 using namespace ARMII; 5354 5355 static const std::pair<unsigned, const char *> TargetFlags[] = { 5356 {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}}; 5357 return makeArrayRef(TargetFlags); 5358 } 5359 5360 ArrayRef<std::pair<unsigned, const char *>> 5361 ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const { 5362 using namespace ARMII; 5363 5364 static const std::pair<unsigned, const char *> TargetFlags[] = { 5365 {MO_COFFSTUB, "arm-coffstub"}, 5366 {MO_GOT, "arm-got"}, 5367 {MO_SBREL, "arm-sbrel"}, 5368 {MO_DLLIMPORT, "arm-dllimport"}, 5369 {MO_SECREL, "arm-secrel"}, 5370 {MO_NONLAZY, "arm-nonlazy"}}; 5371 return makeArrayRef(TargetFlags); 5372 } 5373 5374 Optional<RegImmPair> ARMBaseInstrInfo::isAddImmediate(const MachineInstr &MI, 5375 Register Reg) const { 5376 int Sign = 1; 5377 unsigned Opcode = MI.getOpcode(); 5378 int64_t Offset = 0; 5379 5380 // TODO: Handle cases where Reg is a super- or sub-register of the 5381 // destination register. 5382 const MachineOperand &Op0 = MI.getOperand(0); 5383 if (!Op0.isReg() || Reg != Op0.getReg()) 5384 return None; 5385 5386 // We describe SUBri or ADDri instructions. 5387 if (Opcode == ARM::SUBri) 5388 Sign = -1; 5389 else if (Opcode != ARM::ADDri) 5390 return None; 5391 5392 // TODO: Third operand can be global address (usually some string). Since 5393 // strings can be relocated we cannot calculate their offsets for 5394 // now. 5395 if (!MI.getOperand(1).isReg() || !MI.getOperand(2).isImm()) 5396 return None; 5397 5398 Offset = MI.getOperand(2).getImm() * Sign; 5399 return RegImmPair{MI.getOperand(1).getReg(), Offset}; 5400 } 5401 5402 bool llvm::registerDefinedBetween(unsigned Reg, 5403 MachineBasicBlock::iterator From, 5404 MachineBasicBlock::iterator To, 5405 const TargetRegisterInfo *TRI) { 5406 for (auto I = From; I != To; ++I) 5407 if (I->modifiesRegister(Reg, TRI)) 5408 return true; 5409 return false; 5410 } 5411 5412 MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br, 5413 const TargetRegisterInfo *TRI) { 5414 // Search backwards to the instruction that defines CSPR. This may or not 5415 // be a CMP, we check that after this loop. If we find another instruction 5416 // that reads cpsr, we return nullptr. 5417 MachineBasicBlock::iterator CmpMI = Br; 5418 while (CmpMI != Br->getParent()->begin()) { 5419 --CmpMI; 5420 if (CmpMI->modifiesRegister(ARM::CPSR, TRI)) 5421 break; 5422 if (CmpMI->readsRegister(ARM::CPSR, TRI)) 5423 break; 5424 } 5425 5426 // Check that this inst is a CMP r[0-7], #0 and that the register 5427 // is not redefined between the cmp and the br. 5428 if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri) 5429 return nullptr; 5430 Register Reg = CmpMI->getOperand(0).getReg(); 5431 Register PredReg; 5432 ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg); 5433 if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0) 5434 return nullptr; 5435 if (!isARMLowRegister(Reg)) 5436 return nullptr; 5437 if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI)) 5438 return nullptr; 5439 5440 return &*CmpMI; 5441 } 5442 5443 unsigned llvm::ConstantMaterializationCost(unsigned Val, 5444 const ARMSubtarget *Subtarget, 5445 bool ForCodesize) { 5446 if (Subtarget->isThumb()) { 5447 if (Val <= 255) // MOV 5448 return ForCodesize ? 2 : 1; 5449 if (Subtarget->hasV6T2Ops() && (Val <= 0xffff || // MOV 5450 ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW 5451 ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN 5452 return ForCodesize ? 4 : 1; 5453 if (Val <= 510) // MOV + ADDi8 5454 return ForCodesize ? 4 : 2; 5455 if (~Val <= 255) // MOV + MVN 5456 return ForCodesize ? 4 : 2; 5457 if (ARM_AM::isThumbImmShiftedVal(Val)) // MOV + LSL 5458 return ForCodesize ? 4 : 2; 5459 } else { 5460 if (ARM_AM::getSOImmVal(Val) != -1) // MOV 5461 return ForCodesize ? 4 : 1; 5462 if (ARM_AM::getSOImmVal(~Val) != -1) // MVN 5463 return ForCodesize ? 4 : 1; 5464 if (Subtarget->hasV6T2Ops() && Val <= 0xffff) // MOVW 5465 return ForCodesize ? 4 : 1; 5466 if (ARM_AM::isSOImmTwoPartVal(Val)) // two instrs 5467 return ForCodesize ? 8 : 2; 5468 if (ARM_AM::isSOImmTwoPartValNeg(Val)) // two instrs 5469 return ForCodesize ? 8 : 2; 5470 } 5471 if (Subtarget->useMovt()) // MOVW + MOVT 5472 return ForCodesize ? 8 : 2; 5473 return ForCodesize ? 8 : 3; // Literal pool load 5474 } 5475 5476 bool llvm::HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2, 5477 const ARMSubtarget *Subtarget, 5478 bool ForCodesize) { 5479 // Check with ForCodesize 5480 unsigned Cost1 = ConstantMaterializationCost(Val1, Subtarget, ForCodesize); 5481 unsigned Cost2 = ConstantMaterializationCost(Val2, Subtarget, ForCodesize); 5482 if (Cost1 < Cost2) 5483 return true; 5484 if (Cost1 > Cost2) 5485 return false; 5486 5487 // If they are equal, try with !ForCodesize 5488 return ConstantMaterializationCost(Val1, Subtarget, !ForCodesize) < 5489 ConstantMaterializationCost(Val2, Subtarget, !ForCodesize); 5490 } 5491 5492 /// Constants defining how certain sequences should be outlined. 5493 /// This encompasses how an outlined function should be called, and what kind of 5494 /// frame should be emitted for that outlined function. 5495 /// 5496 /// \p MachineOutlinerTailCall implies that the function is being created from 5497 /// a sequence of instructions ending in a return. 5498 /// 5499 /// That is, 5500 /// 5501 /// I1 OUTLINED_FUNCTION: 5502 /// I2 --> B OUTLINED_FUNCTION I1 5503 /// BX LR I2 5504 /// BX LR 5505 /// 5506 /// +-------------------------+--------+-----+ 5507 /// | | Thumb2 | ARM | 5508 /// +-------------------------+--------+-----+ 5509 /// | Call overhead in Bytes | 4 | 4 | 5510 /// | Frame overhead in Bytes | 0 | 0 | 5511 /// | Stack fixup required | No | No | 5512 /// +-------------------------+--------+-----+ 5513 /// 5514 /// \p MachineOutlinerThunk implies that the function is being created from 5515 /// a sequence of instructions ending in a call. The outlined function is 5516 /// called with a BL instruction, and the outlined function tail-calls the 5517 /// original call destination. 5518 /// 5519 /// That is, 5520 /// 5521 /// I1 OUTLINED_FUNCTION: 5522 /// I2 --> BL OUTLINED_FUNCTION I1 5523 /// BL f I2 5524 /// B f 5525 /// 5526 /// +-------------------------+--------+-----+ 5527 /// | | Thumb2 | ARM | 5528 /// +-------------------------+--------+-----+ 5529 /// | Call overhead in Bytes | 4 | 4 | 5530 /// | Frame overhead in Bytes | 0 | 0 | 5531 /// | Stack fixup required | No | No | 5532 /// +-------------------------+--------+-----+ 5533 /// 5534 /// \p MachineOutlinerNoLRSave implies that the function should be called using 5535 /// a BL instruction, but doesn't require LR to be saved and restored. This 5536 /// happens when LR is known to be dead. 5537 /// 5538 /// That is, 5539 /// 5540 /// I1 OUTLINED_FUNCTION: 5541 /// I2 --> BL OUTLINED_FUNCTION I1 5542 /// I3 I2 5543 /// I3 5544 /// BX LR 5545 /// 5546 /// +-------------------------+--------+-----+ 5547 /// | | Thumb2 | ARM | 5548 /// +-------------------------+--------+-----+ 5549 /// | Call overhead in Bytes | 4 | 4 | 5550 /// | Frame overhead in Bytes | 4 | 4 | 5551 /// | Stack fixup required | No | No | 5552 /// +-------------------------+--------+-----+ 5553 /// 5554 /// \p MachineOutlinerRegSave implies that the function should be called with a 5555 /// save and restore of LR to an available register. This allows us to avoid 5556 /// stack fixups. Note that this outlining variant is compatible with the 5557 /// NoLRSave case. 5558 /// 5559 /// That is, 5560 /// 5561 /// I1 Save LR OUTLINED_FUNCTION: 5562 /// I2 --> BL OUTLINED_FUNCTION I1 5563 /// I3 Restore LR I2 5564 /// I3 5565 /// BX LR 5566 /// 5567 /// +-------------------------+--------+-----+ 5568 /// | | Thumb2 | ARM | 5569 /// +-------------------------+--------+-----+ 5570 /// | Call overhead in Bytes | 8 | 12 | 5571 /// | Frame overhead in Bytes | 2 | 4 | 5572 /// | Stack fixup required | No | No | 5573 /// +-------------------------+--------+-----+ 5574 /// 5575 /// \p MachineOutlinerDefault implies that the function should be called with 5576 /// a save and restore of LR to the stack. 5577 /// 5578 /// That is, 5579 /// 5580 /// I1 Save LR OUTLINED_FUNCTION: 5581 /// I2 --> BL OUTLINED_FUNCTION I1 5582 /// I3 Restore LR I2 5583 /// I3 5584 /// BX LR 5585 /// 5586 /// +-------------------------+--------+-----+ 5587 /// | | Thumb2 | ARM | 5588 /// +-------------------------+--------+-----+ 5589 /// | Call overhead in Bytes | 8 | 12 | 5590 /// | Frame overhead in Bytes | 2 | 4 | 5591 /// | Stack fixup required | Yes | Yes | 5592 /// +-------------------------+--------+-----+ 5593 5594 enum MachineOutlinerClass { 5595 MachineOutlinerTailCall, 5596 MachineOutlinerThunk, 5597 MachineOutlinerNoLRSave, 5598 MachineOutlinerRegSave, 5599 MachineOutlinerDefault 5600 }; 5601 5602 enum MachineOutlinerMBBFlags { 5603 LRUnavailableSomewhere = 0x2, 5604 HasCalls = 0x4, 5605 UnsafeRegsDead = 0x8 5606 }; 5607 5608 struct OutlinerCosts { 5609 const int CallTailCall; 5610 const int FrameTailCall; 5611 const int CallThunk; 5612 const int FrameThunk; 5613 const int CallNoLRSave; 5614 const int FrameNoLRSave; 5615 const int CallRegSave; 5616 const int FrameRegSave; 5617 const int CallDefault; 5618 const int FrameDefault; 5619 const int SaveRestoreLROnStack; 5620 5621 OutlinerCosts(const ARMSubtarget &target) 5622 : CallTailCall(target.isThumb() ? 4 : 4), 5623 FrameTailCall(target.isThumb() ? 0 : 0), 5624 CallThunk(target.isThumb() ? 4 : 4), 5625 FrameThunk(target.isThumb() ? 0 : 0), 5626 CallNoLRSave(target.isThumb() ? 4 : 4), 5627 FrameNoLRSave(target.isThumb() ? 4 : 4), 5628 CallRegSave(target.isThumb() ? 8 : 12), 5629 FrameRegSave(target.isThumb() ? 2 : 4), 5630 CallDefault(target.isThumb() ? 8 : 12), 5631 FrameDefault(target.isThumb() ? 2 : 4), 5632 SaveRestoreLROnStack(target.isThumb() ? 8 : 8) {} 5633 }; 5634 5635 unsigned 5636 ARMBaseInstrInfo::findRegisterToSaveLRTo(const outliner::Candidate &C) const { 5637 assert(C.LRUWasSet && "LRU wasn't set?"); 5638 MachineFunction *MF = C.getMF(); 5639 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo *>( 5640 MF->getSubtarget().getRegisterInfo()); 5641 5642 BitVector regsReserved = ARI->getReservedRegs(*MF); 5643 // Check if there is an available register across the sequence that we can 5644 // use. 5645 for (unsigned Reg : ARM::rGPRRegClass) { 5646 if (!(Reg < regsReserved.size() && regsReserved.test(Reg)) && 5647 Reg != ARM::LR && // LR is not reserved, but don't use it. 5648 Reg != ARM::R12 && // R12 is not guaranteed to be preserved. 5649 C.LRU.available(Reg) && C.UsedInSequence.available(Reg)) 5650 return Reg; 5651 } 5652 5653 // No suitable register. Return 0. 5654 return 0u; 5655 } 5656 5657 outliner::OutlinedFunction ARMBaseInstrInfo::getOutliningCandidateInfo( 5658 std::vector<outliner::Candidate> &RepeatedSequenceLocs) const { 5659 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0]; 5660 unsigned SequenceSize = 5661 std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0, 5662 [this](unsigned Sum, const MachineInstr &MI) { 5663 return Sum + getInstSizeInBytes(MI); 5664 }); 5665 5666 // Properties about candidate MBBs that hold for all of them. 5667 unsigned FlagsSetInAll = 0xF; 5668 5669 // Compute liveness information for each candidate, and set FlagsSetInAll. 5670 const TargetRegisterInfo &TRI = getRegisterInfo(); 5671 std::for_each( 5672 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(), 5673 [&FlagsSetInAll](outliner::Candidate &C) { FlagsSetInAll &= C.Flags; }); 5674 5675 // According to the ARM Procedure Call Standard, the following are 5676 // undefined on entry/exit from a function call: 5677 // 5678 // * Register R12(IP), 5679 // * Condition codes (and thus the CPSR register) 5680 // 5681 // Since we control the instructions which are part of the outlined regions 5682 // we don't need to be fully compliant with the AAPCS, but we have to 5683 // guarantee that if a veneer is inserted at link time the code is still 5684 // correct. Because of this, we can't outline any sequence of instructions 5685 // where one of these registers is live into/across it. Thus, we need to 5686 // delete those candidates. 5687 auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) { 5688 // If the unsafe registers in this block are all dead, then we don't need 5689 // to compute liveness here. 5690 if (C.Flags & UnsafeRegsDead) 5691 return false; 5692 C.initLRU(TRI); 5693 LiveRegUnits LRU = C.LRU; 5694 return (!LRU.available(ARM::R12) || !LRU.available(ARM::CPSR)); 5695 }; 5696 5697 // Are there any candidates where those registers are live? 5698 if (!(FlagsSetInAll & UnsafeRegsDead)) { 5699 // Erase every candidate that violates the restrictions above. (It could be 5700 // true that we have viable candidates, so it's not worth bailing out in 5701 // the case that, say, 1 out of 20 candidates violate the restructions.) 5702 RepeatedSequenceLocs.erase(std::remove_if(RepeatedSequenceLocs.begin(), 5703 RepeatedSequenceLocs.end(), 5704 CantGuaranteeValueAcrossCall), 5705 RepeatedSequenceLocs.end()); 5706 5707 // If the sequence doesn't have enough candidates left, then we're done. 5708 if (RepeatedSequenceLocs.size() < 2) 5709 return outliner::OutlinedFunction(); 5710 } 5711 5712 // At this point, we have only "safe" candidates to outline. Figure out 5713 // frame + call instruction information. 5714 5715 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode(); 5716 5717 // Helper lambda which sets call information for every candidate. 5718 auto SetCandidateCallInfo = 5719 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) { 5720 for (outliner::Candidate &C : RepeatedSequenceLocs) 5721 C.setCallInfo(CallID, NumBytesForCall); 5722 }; 5723 5724 OutlinerCosts Costs(Subtarget); 5725 unsigned FrameID = MachineOutlinerDefault; 5726 unsigned NumBytesToCreateFrame = Costs.FrameDefault; 5727 5728 // If the last instruction in any candidate is a terminator, then we should 5729 // tail call all of the candidates. 5730 if (RepeatedSequenceLocs[0].back()->isTerminator()) { 5731 FrameID = MachineOutlinerTailCall; 5732 NumBytesToCreateFrame = Costs.FrameTailCall; 5733 SetCandidateCallInfo(MachineOutlinerTailCall, Costs.CallTailCall); 5734 } else if (LastInstrOpcode == ARM::BL || LastInstrOpcode == ARM::BLX || 5735 LastInstrOpcode == ARM::tBL || LastInstrOpcode == ARM::tBLXr || 5736 LastInstrOpcode == ARM::tBLXi) { 5737 FrameID = MachineOutlinerThunk; 5738 NumBytesToCreateFrame = Costs.FrameThunk; 5739 SetCandidateCallInfo(MachineOutlinerThunk, Costs.CallThunk); 5740 } else { 5741 // We need to decide how to emit calls + frames. We can always emit the same 5742 // frame if we don't need to save to the stack. If we have to save to the 5743 // stack, then we need a different frame. 5744 unsigned NumBytesNoStackCalls = 0; 5745 std::vector<outliner::Candidate> CandidatesWithoutStackFixups; 5746 5747 for (outliner::Candidate &C : RepeatedSequenceLocs) { 5748 C.initLRU(TRI); 5749 // Is LR available? If so, we don't need a save. 5750 if (C.LRU.available(ARM::LR)) { 5751 FrameID = MachineOutlinerNoLRSave; 5752 NumBytesNoStackCalls += Costs.CallNoLRSave; 5753 C.setCallInfo(MachineOutlinerNoLRSave, Costs.CallNoLRSave); 5754 CandidatesWithoutStackFixups.push_back(C); 5755 } 5756 5757 // Is an unused register available? If so, we won't modify the stack, so 5758 // we can outline with the same frame type as those that don't save LR. 5759 else if (findRegisterToSaveLRTo(C)) { 5760 FrameID = MachineOutlinerRegSave; 5761 NumBytesNoStackCalls += Costs.CallRegSave; 5762 C.setCallInfo(MachineOutlinerRegSave, Costs.CallRegSave); 5763 CandidatesWithoutStackFixups.push_back(C); 5764 } 5765 5766 // Is SP used in the sequence at all? If not, we don't have to modify 5767 // the stack, so we are guaranteed to get the same frame. 5768 else if (C.UsedInSequence.available(ARM::SP)) { 5769 NumBytesNoStackCalls += Costs.CallDefault; 5770 C.setCallInfo(MachineOutlinerDefault, Costs.CallDefault); 5771 SetCandidateCallInfo(MachineOutlinerDefault, Costs.CallDefault); 5772 CandidatesWithoutStackFixups.push_back(C); 5773 } else 5774 return outliner::OutlinedFunction(); 5775 } 5776 5777 // Does every candidate's MBB contain a call? If so, then we might have a 5778 // call in the range. 5779 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) { 5780 // check if the range contains a call. These require a save + restore of 5781 // the link register. 5782 if (std::any_of(FirstCand.front(), FirstCand.back(), 5783 [](const MachineInstr &MI) { return MI.isCall(); })) 5784 NumBytesToCreateFrame += Costs.SaveRestoreLROnStack; 5785 5786 // Handle the last instruction separately. If it is tail call, then the 5787 // last instruction is a call, we don't want to save + restore in this 5788 // case. However, it could be possible that the last instruction is a 5789 // call without it being valid to tail call this sequence. We should 5790 // consider this as well. 5791 else if (FrameID != MachineOutlinerThunk && 5792 FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall()) 5793 NumBytesToCreateFrame += Costs.SaveRestoreLROnStack; 5794 } 5795 RepeatedSequenceLocs = CandidatesWithoutStackFixups; 5796 } 5797 5798 return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize, 5799 NumBytesToCreateFrame, FrameID); 5800 } 5801 5802 bool ARMBaseInstrInfo::isFunctionSafeToOutlineFrom( 5803 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const { 5804 const Function &F = MF.getFunction(); 5805 5806 // Can F be deduplicated by the linker? If it can, don't outline from it. 5807 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage()) 5808 return false; 5809 5810 // Don't outline from functions with section markings; the program could 5811 // expect that all the code is in the named section. 5812 // FIXME: Allow outlining from multiple functions with the same section 5813 // marking. 5814 if (F.hasSection()) 5815 return false; 5816 5817 // FIXME: Thumb1 outlining is not handled 5818 if (MF.getInfo<ARMFunctionInfo>()->isThumb1OnlyFunction()) 5819 return false; 5820 5821 // It's safe to outline from MF. 5822 return true; 5823 } 5824 5825 bool ARMBaseInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB, 5826 unsigned &Flags) const { 5827 // Check if LR is available through all of the MBB. If it's not, then set 5828 // a flag. 5829 assert(MBB.getParent()->getRegInfo().tracksLiveness() && 5830 "Suitable Machine Function for outlining must track liveness"); 5831 5832 LiveRegUnits LRU(getRegisterInfo()); 5833 5834 std::for_each(MBB.rbegin(), MBB.rend(), 5835 [&LRU](MachineInstr &MI) { LRU.accumulate(MI); }); 5836 5837 // Check if each of the unsafe registers are available... 5838 bool R12AvailableInBlock = LRU.available(ARM::R12); 5839 bool CPSRAvailableInBlock = LRU.available(ARM::CPSR); 5840 5841 // If all of these are dead (and not live out), we know we don't have to check 5842 // them later. 5843 if (R12AvailableInBlock && CPSRAvailableInBlock) 5844 Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead; 5845 5846 // Now, add the live outs to the set. 5847 LRU.addLiveOuts(MBB); 5848 5849 // If any of these registers is available in the MBB, but also a live out of 5850 // the block, then we know outlining is unsafe. 5851 if (R12AvailableInBlock && !LRU.available(ARM::R12)) 5852 return false; 5853 if (CPSRAvailableInBlock && !LRU.available(ARM::CPSR)) 5854 return false; 5855 5856 // Check if there's a call inside this MachineBasicBlock. If there is, then 5857 // set a flag. 5858 if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); })) 5859 Flags |= MachineOutlinerMBBFlags::HasCalls; 5860 5861 if (!LRU.available(ARM::LR)) 5862 Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere; 5863 5864 return true; 5865 } 5866 5867 outliner::InstrType 5868 ARMBaseInstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT, 5869 unsigned Flags) const { 5870 MachineInstr &MI = *MIT; 5871 const TargetRegisterInfo *TRI = &getRegisterInfo(); 5872 5873 // Be conservative with inline ASM 5874 if (MI.isInlineAsm()) 5875 return outliner::InstrType::Illegal; 5876 5877 // Don't allow debug values to impact outlining type. 5878 if (MI.isDebugInstr() || MI.isIndirectDebugValue()) 5879 return outliner::InstrType::Invisible; 5880 5881 // At this point, KILL or IMPLICIT_DEF instructions don't really tell us much 5882 // so we can go ahead and skip over them. 5883 if (MI.isKill() || MI.isImplicitDef()) 5884 return outliner::InstrType::Invisible; 5885 5886 // PIC instructions contain labels, outlining them would break offset 5887 // computing. unsigned Opc = MI.getOpcode(); 5888 unsigned Opc = MI.getOpcode(); 5889 if (Opc == ARM::tPICADD || Opc == ARM::PICADD || Opc == ARM::PICSTR || 5890 Opc == ARM::PICSTRB || Opc == ARM::PICSTRH || Opc == ARM::PICLDR || 5891 Opc == ARM::PICLDRB || Opc == ARM::PICLDRH || Opc == ARM::PICLDRSB || 5892 Opc == ARM::PICLDRSH || Opc == ARM::t2LDRpci_pic || 5893 Opc == ARM::t2MOVi16_ga_pcrel || Opc == ARM::t2MOVTi16_ga_pcrel || 5894 Opc == ARM::t2MOV_ga_pcrel) 5895 return outliner::InstrType::Illegal; 5896 5897 // Be conservative with ARMv8.1 MVE instructions. 5898 if (Opc == ARM::t2BF_LabelPseudo || Opc == ARM::t2DoLoopStart || 5899 Opc == ARM::t2WhileLoopStart || Opc == ARM::t2LoopDec || 5900 Opc == ARM::t2LoopEnd) 5901 return outliner::InstrType::Illegal; 5902 5903 const MCInstrDesc &MCID = MI.getDesc(); 5904 uint64_t MIFlags = MCID.TSFlags; 5905 if ((MIFlags & ARMII::DomainMask) == ARMII::DomainMVE) 5906 return outliner::InstrType::Illegal; 5907 5908 // Is this a terminator for a basic block? 5909 if (MI.isTerminator()) { 5910 // Don't outline if the branch is not unconditional. 5911 if (isPredicated(MI)) 5912 return outliner::InstrType::Illegal; 5913 5914 // Is this the end of a function? 5915 if (MI.getParent()->succ_empty()) 5916 return outliner::InstrType::Legal; 5917 5918 // It's not, so don't outline it. 5919 return outliner::InstrType::Illegal; 5920 } 5921 5922 // Make sure none of the operands are un-outlinable. 5923 for (const MachineOperand &MOP : MI.operands()) { 5924 if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() || 5925 MOP.isTargetIndex()) 5926 return outliner::InstrType::Illegal; 5927 } 5928 5929 // Don't outline if link register or program counter value are used. 5930 if (MI.readsRegister(ARM::LR, TRI) || MI.readsRegister(ARM::PC, TRI)) 5931 return outliner::InstrType::Illegal; 5932 5933 if (MI.isCall()) { 5934 // Get the function associated with the call. Look at each operand and find 5935 // the one that represents the calle and get its name. 5936 const Function *Callee = nullptr; 5937 for (const MachineOperand &MOP : MI.operands()) { 5938 if (MOP.isGlobal()) { 5939 Callee = dyn_cast<Function>(MOP.getGlobal()); 5940 break; 5941 } 5942 } 5943 5944 // Dont't outline calls to "mcount" like functions, in particular Linux 5945 // kernel function tracing relies on it. 5946 if (Callee && 5947 (Callee->getName() == "\01__gnu_mcount_nc" || 5948 Callee->getName() == "\01mcount" || Callee->getName() == "__mcount")) 5949 return outliner::InstrType::Illegal; 5950 5951 // If we don't know anything about the callee, assume it depends on the 5952 // stack layout of the caller. In that case, it's only legal to outline 5953 // as a tail-call. Explicitly list the call instructions we know about so 5954 // we don't get unexpected results with call pseudo-instructions. 5955 auto UnknownCallOutlineType = outliner::InstrType::Illegal; 5956 if (Opc == ARM::BL || Opc == ARM::tBL || Opc == ARM::BLX || 5957 Opc == ARM::tBLXr || Opc == ARM::tBLXi) 5958 UnknownCallOutlineType = outliner::InstrType::LegalTerminator; 5959 5960 if (!Callee) 5961 return UnknownCallOutlineType; 5962 5963 // We have a function we have information about. Check if it's something we 5964 // can safely outline. 5965 MachineFunction *MF = MI.getParent()->getParent(); 5966 MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee); 5967 5968 // We don't know what's going on with the callee at all. Don't touch it. 5969 if (!CalleeMF) 5970 return UnknownCallOutlineType; 5971 5972 // Check if we know anything about the callee saves on the function. If we 5973 // don't, then don't touch it, since that implies that we haven't computed 5974 // anything about its stack frame yet. 5975 MachineFrameInfo &MFI = CalleeMF->getFrameInfo(); 5976 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 || 5977 MFI.getNumObjects() > 0) 5978 return UnknownCallOutlineType; 5979 5980 // At this point, we can say that CalleeMF ought to not pass anything on the 5981 // stack. Therefore, we can outline it. 5982 return outliner::InstrType::Legal; 5983 } 5984 5985 // Since calls are handled, don't touch LR or PC 5986 if (MI.modifiesRegister(ARM::LR, TRI) || MI.modifiesRegister(ARM::PC, TRI)) 5987 return outliner::InstrType::Illegal; 5988 5989 // Does this use the stack? 5990 if (MI.modifiesRegister(ARM::SP, TRI) || MI.readsRegister(ARM::SP, TRI)) { 5991 // True if there is no chance that any outlined candidate from this range 5992 // could require stack fixups. That is, both 5993 // * LR is available in the range (No save/restore around call) 5994 // * The range doesn't include calls (No save/restore in outlined frame) 5995 // are true. 5996 // FIXME: This is very restrictive; the flags check the whole block, 5997 // not just the bit we will try to outline. 5998 bool MightNeedStackFixUp = 5999 (Flags & (MachineOutlinerMBBFlags::LRUnavailableSomewhere | 6000 MachineOutlinerMBBFlags::HasCalls)); 6001 6002 if (!MightNeedStackFixUp) 6003 return outliner::InstrType::Legal; 6004 6005 return outliner::InstrType::Illegal; 6006 } 6007 6008 // Be conservative with IT blocks. 6009 if (MI.readsRegister(ARM::ITSTATE, TRI) || 6010 MI.modifiesRegister(ARM::ITSTATE, TRI)) 6011 return outliner::InstrType::Illegal; 6012 6013 // Don't outline positions. 6014 if (MI.isPosition()) 6015 return outliner::InstrType::Illegal; 6016 6017 return outliner::InstrType::Legal; 6018 } 6019 6020 void ARMBaseInstrInfo::saveLROnStack(MachineBasicBlock &MBB, 6021 MachineBasicBlock::iterator &It) const { 6022 unsigned Opc = Subtarget.isThumb() ? ARM::t2STR_PRE : ARM::STR_PRE_IMM; 6023 int Align = -Subtarget.getStackAlignment().value(); 6024 BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::SP) 6025 .addReg(ARM::LR, RegState::Kill) 6026 .addReg(ARM::SP) 6027 .addImm(Align) 6028 .add(predOps(ARMCC::AL)); 6029 } 6030 6031 void ARMBaseInstrInfo::restoreLRFromStack( 6032 MachineBasicBlock &MBB, MachineBasicBlock::iterator &It) const { 6033 unsigned Opc = Subtarget.isThumb() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM; 6034 MachineInstrBuilder MIB = BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::LR) 6035 .addReg(ARM::SP, RegState::Define) 6036 .addReg(ARM::SP); 6037 if (!Subtarget.isThumb()) 6038 MIB.addReg(0); 6039 MIB.addImm(Subtarget.getStackAlignment().value()).add(predOps(ARMCC::AL)); 6040 } 6041 6042 void ARMBaseInstrInfo::buildOutlinedFrame( 6043 MachineBasicBlock &MBB, MachineFunction &MF, 6044 const outliner::OutlinedFunction &OF) const { 6045 // For thunk outlining, rewrite the last instruction from a call to a 6046 // tail-call. 6047 if (OF.FrameConstructionID == MachineOutlinerThunk) { 6048 MachineInstr *Call = &*--MBB.instr_end(); 6049 bool isThumb = Subtarget.isThumb(); 6050 unsigned FuncOp = isThumb ? 2 : 0; 6051 unsigned Opc = Call->getOperand(FuncOp).isReg() 6052 ? isThumb ? ARM::tTAILJMPr : ARM::TAILJMPr 6053 : isThumb ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd 6054 : ARM::tTAILJMPdND 6055 : ARM::TAILJMPd; 6056 MachineInstrBuilder MIB = BuildMI(MBB, MBB.end(), DebugLoc(), get(Opc)) 6057 .add(Call->getOperand(FuncOp)); 6058 if (isThumb && !Call->getOperand(FuncOp).isReg()) 6059 MIB.add(predOps(ARMCC::AL)); 6060 Call->eraseFromParent(); 6061 } 6062 6063 // Is there a call in the outlined range? 6064 auto IsNonTailCall = [](MachineInstr &MI) { 6065 return MI.isCall() && !MI.isReturn(); 6066 }; 6067 if (std::any_of(MBB.instr_begin(), MBB.instr_end(), IsNonTailCall)) { 6068 MachineBasicBlock::iterator It = MBB.begin(); 6069 MachineBasicBlock::iterator Et = MBB.end(); 6070 6071 if (OF.FrameConstructionID == MachineOutlinerTailCall || 6072 OF.FrameConstructionID == MachineOutlinerThunk) 6073 Et = std::prev(MBB.end()); 6074 6075 // We have to save and restore LR, we need to add it to the liveins if it 6076 // is not already part of the set. This is suffient since outlined 6077 // functions only have one block. 6078 if (!MBB.isLiveIn(ARM::LR)) 6079 MBB.addLiveIn(ARM::LR); 6080 6081 // Insert a save before the outlined region 6082 saveLROnStack(MBB, It); 6083 6084 unsigned StackAlignment = Subtarget.getStackAlignment().value(); 6085 const TargetSubtargetInfo &STI = MF.getSubtarget(); 6086 const MCRegisterInfo *MRI = STI.getRegisterInfo(); 6087 unsigned DwarfReg = MRI->getDwarfRegNum(ARM::LR, true); 6088 // Add a CFI saying the stack was moved down. 6089 int64_t StackPosEntry = MF.addFrameInst( 6090 MCCFIInstruction::cfiDefCfaOffset(nullptr, StackAlignment)); 6091 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION)) 6092 .addCFIIndex(StackPosEntry) 6093 .setMIFlags(MachineInstr::FrameSetup); 6094 6095 // Add a CFI saying that the LR that we want to find is now higher than 6096 // before. 6097 int64_t LRPosEntry = MF.addFrameInst( 6098 MCCFIInstruction::createOffset(nullptr, DwarfReg, StackAlignment)); 6099 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION)) 6100 .addCFIIndex(LRPosEntry) 6101 .setMIFlags(MachineInstr::FrameSetup); 6102 6103 // Insert a restore before the terminator for the function. Restore LR. 6104 restoreLRFromStack(MBB, Et); 6105 } 6106 6107 // If this is a tail call outlined function, then there's already a return. 6108 if (OF.FrameConstructionID == MachineOutlinerTailCall || 6109 OF.FrameConstructionID == MachineOutlinerThunk) 6110 return; 6111 6112 // Here we have to insert the return ourselves. Get the correct opcode from 6113 // current feature set. 6114 BuildMI(MBB, MBB.end(), DebugLoc(), get(Subtarget.getReturnOpcode())) 6115 .add(predOps(ARMCC::AL)); 6116 } 6117 6118 MachineBasicBlock::iterator ARMBaseInstrInfo::insertOutlinedCall( 6119 Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It, 6120 MachineFunction &MF, const outliner::Candidate &C) const { 6121 MachineInstrBuilder MIB; 6122 MachineBasicBlock::iterator CallPt; 6123 unsigned Opc; 6124 bool isThumb = Subtarget.isThumb(); 6125 6126 // Are we tail calling? 6127 if (C.CallConstructionID == MachineOutlinerTailCall) { 6128 // If yes, then we can just branch to the label. 6129 Opc = isThumb 6130 ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND 6131 : ARM::TAILJMPd; 6132 MIB = BuildMI(MF, DebugLoc(), get(Opc)) 6133 .addGlobalAddress(M.getNamedValue(MF.getName())); 6134 if (isThumb) 6135 MIB.add(predOps(ARMCC::AL)); 6136 It = MBB.insert(It, MIB); 6137 return It; 6138 } 6139 6140 // Create the call instruction. 6141 Opc = isThumb ? ARM::tBL : ARM::BL; 6142 MachineInstrBuilder CallMIB = BuildMI(MF, DebugLoc(), get(Opc)); 6143 if (isThumb) 6144 CallMIB.add(predOps(ARMCC::AL)); 6145 CallMIB.addGlobalAddress(M.getNamedValue(MF.getName())); 6146 6147 if (C.CallConstructionID == MachineOutlinerNoLRSave || 6148 C.CallConstructionID == MachineOutlinerThunk) { 6149 // No, so just insert the call. 6150 It = MBB.insert(It, CallMIB); 6151 return It; 6152 } 6153 6154 // Can we save to a register? 6155 if (C.CallConstructionID == MachineOutlinerRegSave) { 6156 unsigned Reg = findRegisterToSaveLRTo(C); 6157 assert(Reg != 0 && "No callee-saved register available?"); 6158 6159 // Save and restore LR from that register. 6160 copyPhysReg(MBB, It, DebugLoc(), Reg, ARM::LR, true); 6161 CallPt = MBB.insert(It, CallMIB); 6162 copyPhysReg(MBB, It, DebugLoc(), ARM::LR, Reg, true); 6163 It--; 6164 return CallPt; 6165 } 6166 // We have the default case. Save and restore from SP. 6167 saveLROnStack(MBB, It); 6168 CallPt = MBB.insert(It, CallMIB); 6169 restoreLRFromStack(MBB, It); 6170 It--; 6171 return CallPt; 6172 } 6173 6174 bool ARMBaseInstrInfo::shouldOutlineFromFunctionByDefault( 6175 MachineFunction &MF) const { 6176 return Subtarget.isMClass() && MF.getFunction().hasMinSize(); 6177 } 6178 6179 bool ARMBaseInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI, 6180 AAResults *AA) const { 6181 // Try hard to rematerialize any VCTPs because if we spill P0, it will block 6182 // the tail predication conversion. This means that the element count 6183 // register has to be live for longer, but that has to be better than 6184 // spill/restore and VPT predication. 6185 return isVCTP(&MI) && !isPredicated(MI); 6186 } 6187