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