1 //===- AArch64InstrInfo.cpp - AArch64 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 AArch64 implementation of the TargetInstrInfo class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "AArch64InstrInfo.h" 14 #include "AArch64MachineFunctionInfo.h" 15 #include "AArch64Subtarget.h" 16 #include "MCTargetDesc/AArch64AddressingModes.h" 17 #include "Utils/AArch64BaseInfo.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/CodeGen/MachineBasicBlock.h" 22 #include "llvm/CodeGen/MachineFrameInfo.h" 23 #include "llvm/CodeGen/MachineFunction.h" 24 #include "llvm/CodeGen/MachineInstr.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineMemOperand.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/CodeGen/MachineOperand.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/StackMaps.h" 31 #include "llvm/CodeGen/TargetRegisterInfo.h" 32 #include "llvm/CodeGen/TargetSubtargetInfo.h" 33 #include "llvm/IR/DebugInfoMetadata.h" 34 #include "llvm/IR/DebugLoc.h" 35 #include "llvm/IR/GlobalValue.h" 36 #include "llvm/MC/MCAsmInfo.h" 37 #include "llvm/MC/MCInst.h" 38 #include "llvm/MC/MCInstBuilder.h" 39 #include "llvm/MC/MCInstrDesc.h" 40 #include "llvm/Support/Casting.h" 41 #include "llvm/Support/CodeGen.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Compiler.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/MathExtras.h" 46 #include "llvm/Target/TargetMachine.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include <cassert> 49 #include <cstdint> 50 #include <iterator> 51 #include <utility> 52 53 using namespace llvm; 54 55 #define GET_INSTRINFO_CTOR_DTOR 56 #include "AArch64GenInstrInfo.inc" 57 58 static cl::opt<unsigned> TBZDisplacementBits( 59 "aarch64-tbz-offset-bits", cl::Hidden, cl::init(14), 60 cl::desc("Restrict range of TB[N]Z instructions (DEBUG)")); 61 62 static cl::opt<unsigned> CBZDisplacementBits( 63 "aarch64-cbz-offset-bits", cl::Hidden, cl::init(19), 64 cl::desc("Restrict range of CB[N]Z instructions (DEBUG)")); 65 66 static cl::opt<unsigned> 67 BCCDisplacementBits("aarch64-bcc-offset-bits", cl::Hidden, cl::init(19), 68 cl::desc("Restrict range of Bcc instructions (DEBUG)")); 69 70 AArch64InstrInfo::AArch64InstrInfo(const AArch64Subtarget &STI) 71 : AArch64GenInstrInfo(AArch64::ADJCALLSTACKDOWN, AArch64::ADJCALLSTACKUP, 72 AArch64::CATCHRET), 73 RI(STI.getTargetTriple()), Subtarget(STI) {} 74 75 /// GetInstSize - Return the number of bytes of code the specified 76 /// instruction may be. This returns the maximum number of bytes. 77 unsigned AArch64InstrInfo::getInstSizeInBytes(const MachineInstr &MI) const { 78 const MachineBasicBlock &MBB = *MI.getParent(); 79 const MachineFunction *MF = MBB.getParent(); 80 const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo(); 81 82 { 83 auto Op = MI.getOpcode(); 84 if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR) 85 return getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI); 86 } 87 88 // Meta-instructions emit no code. 89 if (MI.isMetaInstruction()) 90 return 0; 91 92 // FIXME: We currently only handle pseudoinstructions that don't get expanded 93 // before the assembly printer. 94 unsigned NumBytes = 0; 95 const MCInstrDesc &Desc = MI.getDesc(); 96 switch (Desc.getOpcode()) { 97 default: 98 // Anything not explicitly designated otherwise is a normal 4-byte insn. 99 NumBytes = 4; 100 break; 101 case TargetOpcode::STACKMAP: 102 // The upper bound for a stackmap intrinsic is the full length of its shadow 103 NumBytes = StackMapOpers(&MI).getNumPatchBytes(); 104 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!"); 105 break; 106 case TargetOpcode::PATCHPOINT: 107 // The size of the patchpoint intrinsic is the number of bytes requested 108 NumBytes = PatchPointOpers(&MI).getNumPatchBytes(); 109 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!"); 110 break; 111 case TargetOpcode::STATEPOINT: 112 NumBytes = StatepointOpers(&MI).getNumPatchBytes(); 113 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!"); 114 // No patch bytes means a normal call inst is emitted 115 if (NumBytes == 0) 116 NumBytes = 4; 117 break; 118 case AArch64::TLSDESC_CALLSEQ: 119 // This gets lowered to an instruction sequence which takes 16 bytes 120 NumBytes = 16; 121 break; 122 case AArch64::SpeculationBarrierISBDSBEndBB: 123 // This gets lowered to 2 4-byte instructions. 124 NumBytes = 8; 125 break; 126 case AArch64::SpeculationBarrierSBEndBB: 127 // This gets lowered to 1 4-byte instructions. 128 NumBytes = 4; 129 break; 130 case AArch64::JumpTableDest32: 131 case AArch64::JumpTableDest16: 132 case AArch64::JumpTableDest8: 133 NumBytes = 12; 134 break; 135 case AArch64::SPACE: 136 NumBytes = MI.getOperand(1).getImm(); 137 break; 138 case AArch64::StoreSwiftAsyncContext: 139 NumBytes = 20; 140 break; 141 case TargetOpcode::BUNDLE: 142 NumBytes = getInstBundleLength(MI); 143 break; 144 } 145 146 return NumBytes; 147 } 148 149 unsigned AArch64InstrInfo::getInstBundleLength(const MachineInstr &MI) const { 150 unsigned Size = 0; 151 MachineBasicBlock::const_instr_iterator I = MI.getIterator(); 152 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end(); 153 while (++I != E && I->isInsideBundle()) { 154 assert(!I->isBundle() && "No nested bundle!"); 155 Size += getInstSizeInBytes(*I); 156 } 157 return Size; 158 } 159 160 static void parseCondBranch(MachineInstr *LastInst, MachineBasicBlock *&Target, 161 SmallVectorImpl<MachineOperand> &Cond) { 162 // Block ends with fall-through condbranch. 163 switch (LastInst->getOpcode()) { 164 default: 165 llvm_unreachable("Unknown branch instruction?"); 166 case AArch64::Bcc: 167 Target = LastInst->getOperand(1).getMBB(); 168 Cond.push_back(LastInst->getOperand(0)); 169 break; 170 case AArch64::CBZW: 171 case AArch64::CBZX: 172 case AArch64::CBNZW: 173 case AArch64::CBNZX: 174 Target = LastInst->getOperand(1).getMBB(); 175 Cond.push_back(MachineOperand::CreateImm(-1)); 176 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); 177 Cond.push_back(LastInst->getOperand(0)); 178 break; 179 case AArch64::TBZW: 180 case AArch64::TBZX: 181 case AArch64::TBNZW: 182 case AArch64::TBNZX: 183 Target = LastInst->getOperand(2).getMBB(); 184 Cond.push_back(MachineOperand::CreateImm(-1)); 185 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); 186 Cond.push_back(LastInst->getOperand(0)); 187 Cond.push_back(LastInst->getOperand(1)); 188 } 189 } 190 191 static unsigned getBranchDisplacementBits(unsigned Opc) { 192 switch (Opc) { 193 default: 194 llvm_unreachable("unexpected opcode!"); 195 case AArch64::B: 196 return 64; 197 case AArch64::TBNZW: 198 case AArch64::TBZW: 199 case AArch64::TBNZX: 200 case AArch64::TBZX: 201 return TBZDisplacementBits; 202 case AArch64::CBNZW: 203 case AArch64::CBZW: 204 case AArch64::CBNZX: 205 case AArch64::CBZX: 206 return CBZDisplacementBits; 207 case AArch64::Bcc: 208 return BCCDisplacementBits; 209 } 210 } 211 212 bool AArch64InstrInfo::isBranchOffsetInRange(unsigned BranchOp, 213 int64_t BrOffset) const { 214 unsigned Bits = getBranchDisplacementBits(BranchOp); 215 assert(Bits >= 3 && "max branch displacement must be enough to jump" 216 "over conditional branch expansion"); 217 return isIntN(Bits, BrOffset / 4); 218 } 219 220 MachineBasicBlock * 221 AArch64InstrInfo::getBranchDestBlock(const MachineInstr &MI) const { 222 switch (MI.getOpcode()) { 223 default: 224 llvm_unreachable("unexpected opcode!"); 225 case AArch64::B: 226 return MI.getOperand(0).getMBB(); 227 case AArch64::TBZW: 228 case AArch64::TBNZW: 229 case AArch64::TBZX: 230 case AArch64::TBNZX: 231 return MI.getOperand(2).getMBB(); 232 case AArch64::CBZW: 233 case AArch64::CBNZW: 234 case AArch64::CBZX: 235 case AArch64::CBNZX: 236 case AArch64::Bcc: 237 return MI.getOperand(1).getMBB(); 238 } 239 } 240 241 // Branch analysis. 242 bool AArch64InstrInfo::analyzeBranch(MachineBasicBlock &MBB, 243 MachineBasicBlock *&TBB, 244 MachineBasicBlock *&FBB, 245 SmallVectorImpl<MachineOperand> &Cond, 246 bool AllowModify) const { 247 // If the block has no terminators, it just falls into the block after it. 248 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 249 if (I == MBB.end()) 250 return false; 251 252 // Skip over SpeculationBarrierEndBB terminators 253 if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB || 254 I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) { 255 --I; 256 } 257 258 if (!isUnpredicatedTerminator(*I)) 259 return false; 260 261 // Get the last instruction in the block. 262 MachineInstr *LastInst = &*I; 263 264 // If there is only one terminator instruction, process it. 265 unsigned LastOpc = LastInst->getOpcode(); 266 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) { 267 if (isUncondBranchOpcode(LastOpc)) { 268 TBB = LastInst->getOperand(0).getMBB(); 269 return false; 270 } 271 if (isCondBranchOpcode(LastOpc)) { 272 // Block ends with fall-through condbranch. 273 parseCondBranch(LastInst, TBB, Cond); 274 return false; 275 } 276 return true; // Can't handle indirect branch. 277 } 278 279 // Get the instruction before it if it is a terminator. 280 MachineInstr *SecondLastInst = &*I; 281 unsigned SecondLastOpc = SecondLastInst->getOpcode(); 282 283 // If AllowModify is true and the block ends with two or more unconditional 284 // branches, delete all but the first unconditional branch. 285 if (AllowModify && isUncondBranchOpcode(LastOpc)) { 286 while (isUncondBranchOpcode(SecondLastOpc)) { 287 LastInst->eraseFromParent(); 288 LastInst = SecondLastInst; 289 LastOpc = LastInst->getOpcode(); 290 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) { 291 // Return now the only terminator is an unconditional branch. 292 TBB = LastInst->getOperand(0).getMBB(); 293 return false; 294 } else { 295 SecondLastInst = &*I; 296 SecondLastOpc = SecondLastInst->getOpcode(); 297 } 298 } 299 } 300 301 // If we're allowed to modify and the block ends in a unconditional branch 302 // which could simply fallthrough, remove the branch. (Note: This case only 303 // matters when we can't understand the whole sequence, otherwise it's also 304 // handled by BranchFolding.cpp.) 305 if (AllowModify && isUncondBranchOpcode(LastOpc) && 306 MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) { 307 LastInst->eraseFromParent(); 308 LastInst = SecondLastInst; 309 LastOpc = LastInst->getOpcode(); 310 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) { 311 assert(!isUncondBranchOpcode(LastOpc) && 312 "unreachable unconditional branches removed above"); 313 314 if (isCondBranchOpcode(LastOpc)) { 315 // Block ends with fall-through condbranch. 316 parseCondBranch(LastInst, TBB, Cond); 317 return false; 318 } 319 return true; // Can't handle indirect branch. 320 } else { 321 SecondLastInst = &*I; 322 SecondLastOpc = SecondLastInst->getOpcode(); 323 } 324 } 325 326 // If there are three terminators, we don't know what sort of block this is. 327 if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I)) 328 return true; 329 330 // If the block ends with a B and a Bcc, handle it. 331 if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) { 332 parseCondBranch(SecondLastInst, TBB, Cond); 333 FBB = LastInst->getOperand(0).getMBB(); 334 return false; 335 } 336 337 // If the block ends with two unconditional branches, handle it. The second 338 // one is not executed, so remove it. 339 if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) { 340 TBB = SecondLastInst->getOperand(0).getMBB(); 341 I = LastInst; 342 if (AllowModify) 343 I->eraseFromParent(); 344 return false; 345 } 346 347 // ...likewise if it ends with an indirect branch followed by an unconditional 348 // branch. 349 if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) { 350 I = LastInst; 351 if (AllowModify) 352 I->eraseFromParent(); 353 return true; 354 } 355 356 // Otherwise, can't handle this. 357 return true; 358 } 359 360 bool AArch64InstrInfo::analyzeBranchPredicate(MachineBasicBlock &MBB, 361 MachineBranchPredicate &MBP, 362 bool AllowModify) const { 363 // For the moment, handle only a block which ends with a cb(n)zx followed by 364 // a fallthrough. Why this? Because it is a common form. 365 // TODO: Should we handle b.cc? 366 367 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 368 if (I == MBB.end()) 369 return true; 370 371 // Skip over SpeculationBarrierEndBB terminators 372 if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB || 373 I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) { 374 --I; 375 } 376 377 if (!isUnpredicatedTerminator(*I)) 378 return true; 379 380 // Get the last instruction in the block. 381 MachineInstr *LastInst = &*I; 382 unsigned LastOpc = LastInst->getOpcode(); 383 if (!isCondBranchOpcode(LastOpc)) 384 return true; 385 386 switch (LastOpc) { 387 default: 388 return true; 389 case AArch64::CBZW: 390 case AArch64::CBZX: 391 case AArch64::CBNZW: 392 case AArch64::CBNZX: 393 break; 394 }; 395 396 MBP.TrueDest = LastInst->getOperand(1).getMBB(); 397 assert(MBP.TrueDest && "expected!"); 398 MBP.FalseDest = MBB.getNextNode(); 399 400 MBP.ConditionDef = nullptr; 401 MBP.SingleUseCondition = false; 402 403 MBP.LHS = LastInst->getOperand(0); 404 MBP.RHS = MachineOperand::CreateImm(0); 405 MBP.Predicate = LastOpc == AArch64::CBNZX ? MachineBranchPredicate::PRED_NE 406 : MachineBranchPredicate::PRED_EQ; 407 return false; 408 } 409 410 bool AArch64InstrInfo::reverseBranchCondition( 411 SmallVectorImpl<MachineOperand> &Cond) const { 412 if (Cond[0].getImm() != -1) { 413 // Regular Bcc 414 AArch64CC::CondCode CC = (AArch64CC::CondCode)(int)Cond[0].getImm(); 415 Cond[0].setImm(AArch64CC::getInvertedCondCode(CC)); 416 } else { 417 // Folded compare-and-branch 418 switch (Cond[1].getImm()) { 419 default: 420 llvm_unreachable("Unknown conditional branch!"); 421 case AArch64::CBZW: 422 Cond[1].setImm(AArch64::CBNZW); 423 break; 424 case AArch64::CBNZW: 425 Cond[1].setImm(AArch64::CBZW); 426 break; 427 case AArch64::CBZX: 428 Cond[1].setImm(AArch64::CBNZX); 429 break; 430 case AArch64::CBNZX: 431 Cond[1].setImm(AArch64::CBZX); 432 break; 433 case AArch64::TBZW: 434 Cond[1].setImm(AArch64::TBNZW); 435 break; 436 case AArch64::TBNZW: 437 Cond[1].setImm(AArch64::TBZW); 438 break; 439 case AArch64::TBZX: 440 Cond[1].setImm(AArch64::TBNZX); 441 break; 442 case AArch64::TBNZX: 443 Cond[1].setImm(AArch64::TBZX); 444 break; 445 } 446 } 447 448 return false; 449 } 450 451 unsigned AArch64InstrInfo::removeBranch(MachineBasicBlock &MBB, 452 int *BytesRemoved) const { 453 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 454 if (I == MBB.end()) 455 return 0; 456 457 if (!isUncondBranchOpcode(I->getOpcode()) && 458 !isCondBranchOpcode(I->getOpcode())) 459 return 0; 460 461 // Remove the branch. 462 I->eraseFromParent(); 463 464 I = MBB.end(); 465 466 if (I == MBB.begin()) { 467 if (BytesRemoved) 468 *BytesRemoved = 4; 469 return 1; 470 } 471 --I; 472 if (!isCondBranchOpcode(I->getOpcode())) { 473 if (BytesRemoved) 474 *BytesRemoved = 4; 475 return 1; 476 } 477 478 // Remove the branch. 479 I->eraseFromParent(); 480 if (BytesRemoved) 481 *BytesRemoved = 8; 482 483 return 2; 484 } 485 486 void AArch64InstrInfo::instantiateCondBranch( 487 MachineBasicBlock &MBB, const DebugLoc &DL, MachineBasicBlock *TBB, 488 ArrayRef<MachineOperand> Cond) const { 489 if (Cond[0].getImm() != -1) { 490 // Regular Bcc 491 BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB); 492 } else { 493 // Folded compare-and-branch 494 // Note that we use addOperand instead of addReg to keep the flags. 495 const MachineInstrBuilder MIB = 496 BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]); 497 if (Cond.size() > 3) 498 MIB.addImm(Cond[3].getImm()); 499 MIB.addMBB(TBB); 500 } 501 } 502 503 unsigned AArch64InstrInfo::insertBranch( 504 MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, 505 ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const { 506 // Shouldn't be a fall through. 507 assert(TBB && "insertBranch must not be told to insert a fallthrough"); 508 509 if (!FBB) { 510 if (Cond.empty()) // Unconditional branch? 511 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB); 512 else 513 instantiateCondBranch(MBB, DL, TBB, Cond); 514 515 if (BytesAdded) 516 *BytesAdded = 4; 517 518 return 1; 519 } 520 521 // Two-way conditional branch. 522 instantiateCondBranch(MBB, DL, TBB, Cond); 523 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB); 524 525 if (BytesAdded) 526 *BytesAdded = 8; 527 528 return 2; 529 } 530 531 // Find the original register that VReg is copied from. 532 static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) { 533 while (Register::isVirtualRegister(VReg)) { 534 const MachineInstr *DefMI = MRI.getVRegDef(VReg); 535 if (!DefMI->isFullCopy()) 536 return VReg; 537 VReg = DefMI->getOperand(1).getReg(); 538 } 539 return VReg; 540 } 541 542 // Determine if VReg is defined by an instruction that can be folded into a 543 // csel instruction. If so, return the folded opcode, and the replacement 544 // register. 545 static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg, 546 unsigned *NewVReg = nullptr) { 547 VReg = removeCopies(MRI, VReg); 548 if (!Register::isVirtualRegister(VReg)) 549 return 0; 550 551 bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg)); 552 const MachineInstr *DefMI = MRI.getVRegDef(VReg); 553 unsigned Opc = 0; 554 unsigned SrcOpNum = 0; 555 switch (DefMI->getOpcode()) { 556 case AArch64::ADDSXri: 557 case AArch64::ADDSWri: 558 // if NZCV is used, do not fold. 559 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1) 560 return 0; 561 // fall-through to ADDXri and ADDWri. 562 LLVM_FALLTHROUGH; 563 case AArch64::ADDXri: 564 case AArch64::ADDWri: 565 // add x, 1 -> csinc. 566 if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 || 567 DefMI->getOperand(3).getImm() != 0) 568 return 0; 569 SrcOpNum = 1; 570 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr; 571 break; 572 573 case AArch64::ORNXrr: 574 case AArch64::ORNWrr: { 575 // not x -> csinv, represented as orn dst, xzr, src. 576 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg()); 577 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR) 578 return 0; 579 SrcOpNum = 2; 580 Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr; 581 break; 582 } 583 584 case AArch64::SUBSXrr: 585 case AArch64::SUBSWrr: 586 // if NZCV is used, do not fold. 587 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1) 588 return 0; 589 // fall-through to SUBXrr and SUBWrr. 590 LLVM_FALLTHROUGH; 591 case AArch64::SUBXrr: 592 case AArch64::SUBWrr: { 593 // neg x -> csneg, represented as sub dst, xzr, src. 594 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg()); 595 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR) 596 return 0; 597 SrcOpNum = 2; 598 Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr; 599 break; 600 } 601 default: 602 return 0; 603 } 604 assert(Opc && SrcOpNum && "Missing parameters"); 605 606 if (NewVReg) 607 *NewVReg = DefMI->getOperand(SrcOpNum).getReg(); 608 return Opc; 609 } 610 611 bool AArch64InstrInfo::canInsertSelect(const MachineBasicBlock &MBB, 612 ArrayRef<MachineOperand> Cond, 613 Register DstReg, Register TrueReg, 614 Register FalseReg, int &CondCycles, 615 int &TrueCycles, 616 int &FalseCycles) const { 617 // Check register classes. 618 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 619 const TargetRegisterClass *RC = 620 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg)); 621 if (!RC) 622 return false; 623 624 // Also need to check the dest regclass, in case we're trying to optimize 625 // something like: 626 // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2 627 if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg))) 628 return false; 629 630 // Expanding cbz/tbz requires an extra cycle of latency on the condition. 631 unsigned ExtraCondLat = Cond.size() != 1; 632 633 // GPRs are handled by csel. 634 // FIXME: Fold in x+1, -x, and ~x when applicable. 635 if (AArch64::GPR64allRegClass.hasSubClassEq(RC) || 636 AArch64::GPR32allRegClass.hasSubClassEq(RC)) { 637 // Single-cycle csel, csinc, csinv, and csneg. 638 CondCycles = 1 + ExtraCondLat; 639 TrueCycles = FalseCycles = 1; 640 if (canFoldIntoCSel(MRI, TrueReg)) 641 TrueCycles = 0; 642 else if (canFoldIntoCSel(MRI, FalseReg)) 643 FalseCycles = 0; 644 return true; 645 } 646 647 // Scalar floating point is handled by fcsel. 648 // FIXME: Form fabs, fmin, and fmax when applicable. 649 if (AArch64::FPR64RegClass.hasSubClassEq(RC) || 650 AArch64::FPR32RegClass.hasSubClassEq(RC)) { 651 CondCycles = 5 + ExtraCondLat; 652 TrueCycles = FalseCycles = 2; 653 return true; 654 } 655 656 // Can't do vectors. 657 return false; 658 } 659 660 void AArch64InstrInfo::insertSelect(MachineBasicBlock &MBB, 661 MachineBasicBlock::iterator I, 662 const DebugLoc &DL, Register DstReg, 663 ArrayRef<MachineOperand> Cond, 664 Register TrueReg, Register FalseReg) const { 665 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 666 667 // Parse the condition code, see parseCondBranch() above. 668 AArch64CC::CondCode CC; 669 switch (Cond.size()) { 670 default: 671 llvm_unreachable("Unknown condition opcode in Cond"); 672 case 1: // b.cc 673 CC = AArch64CC::CondCode(Cond[0].getImm()); 674 break; 675 case 3: { // cbz/cbnz 676 // We must insert a compare against 0. 677 bool Is64Bit; 678 switch (Cond[1].getImm()) { 679 default: 680 llvm_unreachable("Unknown branch opcode in Cond"); 681 case AArch64::CBZW: 682 Is64Bit = false; 683 CC = AArch64CC::EQ; 684 break; 685 case AArch64::CBZX: 686 Is64Bit = true; 687 CC = AArch64CC::EQ; 688 break; 689 case AArch64::CBNZW: 690 Is64Bit = false; 691 CC = AArch64CC::NE; 692 break; 693 case AArch64::CBNZX: 694 Is64Bit = true; 695 CC = AArch64CC::NE; 696 break; 697 } 698 Register SrcReg = Cond[2].getReg(); 699 if (Is64Bit) { 700 // cmp reg, #0 is actually subs xzr, reg, #0. 701 MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass); 702 BuildMI(MBB, I, DL, get(AArch64::SUBSXri), AArch64::XZR) 703 .addReg(SrcReg) 704 .addImm(0) 705 .addImm(0); 706 } else { 707 MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass); 708 BuildMI(MBB, I, DL, get(AArch64::SUBSWri), AArch64::WZR) 709 .addReg(SrcReg) 710 .addImm(0) 711 .addImm(0); 712 } 713 break; 714 } 715 case 4: { // tbz/tbnz 716 // We must insert a tst instruction. 717 switch (Cond[1].getImm()) { 718 default: 719 llvm_unreachable("Unknown branch opcode in Cond"); 720 case AArch64::TBZW: 721 case AArch64::TBZX: 722 CC = AArch64CC::EQ; 723 break; 724 case AArch64::TBNZW: 725 case AArch64::TBNZX: 726 CC = AArch64CC::NE; 727 break; 728 } 729 // cmp reg, #foo is actually ands xzr, reg, #1<<foo. 730 if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW) 731 BuildMI(MBB, I, DL, get(AArch64::ANDSWri), AArch64::WZR) 732 .addReg(Cond[2].getReg()) 733 .addImm( 734 AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 32)); 735 else 736 BuildMI(MBB, I, DL, get(AArch64::ANDSXri), AArch64::XZR) 737 .addReg(Cond[2].getReg()) 738 .addImm( 739 AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 64)); 740 break; 741 } 742 } 743 744 unsigned Opc = 0; 745 const TargetRegisterClass *RC = nullptr; 746 bool TryFold = false; 747 if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) { 748 RC = &AArch64::GPR64RegClass; 749 Opc = AArch64::CSELXr; 750 TryFold = true; 751 } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) { 752 RC = &AArch64::GPR32RegClass; 753 Opc = AArch64::CSELWr; 754 TryFold = true; 755 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) { 756 RC = &AArch64::FPR64RegClass; 757 Opc = AArch64::FCSELDrrr; 758 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) { 759 RC = &AArch64::FPR32RegClass; 760 Opc = AArch64::FCSELSrrr; 761 } 762 assert(RC && "Unsupported regclass"); 763 764 // Try folding simple instructions into the csel. 765 if (TryFold) { 766 unsigned NewVReg = 0; 767 unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewVReg); 768 if (FoldedOpc) { 769 // The folded opcodes csinc, csinc and csneg apply the operation to 770 // FalseReg, so we need to invert the condition. 771 CC = AArch64CC::getInvertedCondCode(CC); 772 TrueReg = FalseReg; 773 } else 774 FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewVReg); 775 776 // Fold the operation. Leave any dead instructions for DCE to clean up. 777 if (FoldedOpc) { 778 FalseReg = NewVReg; 779 Opc = FoldedOpc; 780 // The extends the live range of NewVReg. 781 MRI.clearKillFlags(NewVReg); 782 } 783 } 784 785 // Pull all virtual register into the appropriate class. 786 MRI.constrainRegClass(TrueReg, RC); 787 MRI.constrainRegClass(FalseReg, RC); 788 789 // Insert the csel. 790 BuildMI(MBB, I, DL, get(Opc), DstReg) 791 .addReg(TrueReg) 792 .addReg(FalseReg) 793 .addImm(CC); 794 } 795 796 /// Returns true if a MOVi32imm or MOVi64imm can be expanded to an ORRxx. 797 static bool canBeExpandedToORR(const MachineInstr &MI, unsigned BitSize) { 798 uint64_t Imm = MI.getOperand(1).getImm(); 799 uint64_t UImm = Imm << (64 - BitSize) >> (64 - BitSize); 800 uint64_t Encoding; 801 return AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding); 802 } 803 804 // FIXME: this implementation should be micro-architecture dependent, so a 805 // micro-architecture target hook should be introduced here in future. 806 bool AArch64InstrInfo::isAsCheapAsAMove(const MachineInstr &MI) const { 807 if (!Subtarget.hasCustomCheapAsMoveHandling()) 808 return MI.isAsCheapAsAMove(); 809 810 const unsigned Opcode = MI.getOpcode(); 811 812 // Firstly, check cases gated by features. 813 814 if (Subtarget.hasZeroCycleZeroingFP()) { 815 if (Opcode == AArch64::FMOVH0 || 816 Opcode == AArch64::FMOVS0 || 817 Opcode == AArch64::FMOVD0) 818 return true; 819 } 820 821 if (Subtarget.hasZeroCycleZeroingGP()) { 822 if (Opcode == TargetOpcode::COPY && 823 (MI.getOperand(1).getReg() == AArch64::WZR || 824 MI.getOperand(1).getReg() == AArch64::XZR)) 825 return true; 826 } 827 828 // Secondly, check cases specific to sub-targets. 829 830 if (Subtarget.hasExynosCheapAsMoveHandling()) { 831 if (isExynosCheapAsMove(MI)) 832 return true; 833 834 return MI.isAsCheapAsAMove(); 835 } 836 837 // Finally, check generic cases. 838 839 switch (Opcode) { 840 default: 841 return false; 842 843 // add/sub on register without shift 844 case AArch64::ADDWri: 845 case AArch64::ADDXri: 846 case AArch64::SUBWri: 847 case AArch64::SUBXri: 848 return (MI.getOperand(3).getImm() == 0); 849 850 // logical ops on immediate 851 case AArch64::ANDWri: 852 case AArch64::ANDXri: 853 case AArch64::EORWri: 854 case AArch64::EORXri: 855 case AArch64::ORRWri: 856 case AArch64::ORRXri: 857 return true; 858 859 // logical ops on register without shift 860 case AArch64::ANDWrr: 861 case AArch64::ANDXrr: 862 case AArch64::BICWrr: 863 case AArch64::BICXrr: 864 case AArch64::EONWrr: 865 case AArch64::EONXrr: 866 case AArch64::EORWrr: 867 case AArch64::EORXrr: 868 case AArch64::ORNWrr: 869 case AArch64::ORNXrr: 870 case AArch64::ORRWrr: 871 case AArch64::ORRXrr: 872 return true; 873 874 // If MOVi32imm or MOVi64imm can be expanded into ORRWri or 875 // ORRXri, it is as cheap as MOV 876 case AArch64::MOVi32imm: 877 return canBeExpandedToORR(MI, 32); 878 case AArch64::MOVi64imm: 879 return canBeExpandedToORR(MI, 64); 880 } 881 882 llvm_unreachable("Unknown opcode to check as cheap as a move!"); 883 } 884 885 bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) { 886 switch (MI.getOpcode()) { 887 default: 888 return false; 889 890 case AArch64::ADDWrs: 891 case AArch64::ADDXrs: 892 case AArch64::ADDSWrs: 893 case AArch64::ADDSXrs: { 894 unsigned Imm = MI.getOperand(3).getImm(); 895 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm); 896 if (ShiftVal == 0) 897 return true; 898 return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5; 899 } 900 901 case AArch64::ADDWrx: 902 case AArch64::ADDXrx: 903 case AArch64::ADDXrx64: 904 case AArch64::ADDSWrx: 905 case AArch64::ADDSXrx: 906 case AArch64::ADDSXrx64: { 907 unsigned Imm = MI.getOperand(3).getImm(); 908 switch (AArch64_AM::getArithExtendType(Imm)) { 909 default: 910 return false; 911 case AArch64_AM::UXTB: 912 case AArch64_AM::UXTH: 913 case AArch64_AM::UXTW: 914 case AArch64_AM::UXTX: 915 return AArch64_AM::getArithShiftValue(Imm) <= 4; 916 } 917 } 918 919 case AArch64::SUBWrs: 920 case AArch64::SUBSWrs: { 921 unsigned Imm = MI.getOperand(3).getImm(); 922 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm); 923 return ShiftVal == 0 || 924 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31); 925 } 926 927 case AArch64::SUBXrs: 928 case AArch64::SUBSXrs: { 929 unsigned Imm = MI.getOperand(3).getImm(); 930 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm); 931 return ShiftVal == 0 || 932 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63); 933 } 934 935 case AArch64::SUBWrx: 936 case AArch64::SUBXrx: 937 case AArch64::SUBXrx64: 938 case AArch64::SUBSWrx: 939 case AArch64::SUBSXrx: 940 case AArch64::SUBSXrx64: { 941 unsigned Imm = MI.getOperand(3).getImm(); 942 switch (AArch64_AM::getArithExtendType(Imm)) { 943 default: 944 return false; 945 case AArch64_AM::UXTB: 946 case AArch64_AM::UXTH: 947 case AArch64_AM::UXTW: 948 case AArch64_AM::UXTX: 949 return AArch64_AM::getArithShiftValue(Imm) == 0; 950 } 951 } 952 953 case AArch64::LDRBBroW: 954 case AArch64::LDRBBroX: 955 case AArch64::LDRBroW: 956 case AArch64::LDRBroX: 957 case AArch64::LDRDroW: 958 case AArch64::LDRDroX: 959 case AArch64::LDRHHroW: 960 case AArch64::LDRHHroX: 961 case AArch64::LDRHroW: 962 case AArch64::LDRHroX: 963 case AArch64::LDRQroW: 964 case AArch64::LDRQroX: 965 case AArch64::LDRSBWroW: 966 case AArch64::LDRSBWroX: 967 case AArch64::LDRSBXroW: 968 case AArch64::LDRSBXroX: 969 case AArch64::LDRSHWroW: 970 case AArch64::LDRSHWroX: 971 case AArch64::LDRSHXroW: 972 case AArch64::LDRSHXroX: 973 case AArch64::LDRSWroW: 974 case AArch64::LDRSWroX: 975 case AArch64::LDRSroW: 976 case AArch64::LDRSroX: 977 case AArch64::LDRWroW: 978 case AArch64::LDRWroX: 979 case AArch64::LDRXroW: 980 case AArch64::LDRXroX: 981 case AArch64::PRFMroW: 982 case AArch64::PRFMroX: 983 case AArch64::STRBBroW: 984 case AArch64::STRBBroX: 985 case AArch64::STRBroW: 986 case AArch64::STRBroX: 987 case AArch64::STRDroW: 988 case AArch64::STRDroX: 989 case AArch64::STRHHroW: 990 case AArch64::STRHHroX: 991 case AArch64::STRHroW: 992 case AArch64::STRHroX: 993 case AArch64::STRQroW: 994 case AArch64::STRQroX: 995 case AArch64::STRSroW: 996 case AArch64::STRSroX: 997 case AArch64::STRWroW: 998 case AArch64::STRWroX: 999 case AArch64::STRXroW: 1000 case AArch64::STRXroX: { 1001 unsigned IsSigned = MI.getOperand(3).getImm(); 1002 return !IsSigned; 1003 } 1004 } 1005 } 1006 1007 bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) { 1008 unsigned Opc = MI.getOpcode(); 1009 switch (Opc) { 1010 default: 1011 return false; 1012 case AArch64::SEH_StackAlloc: 1013 case AArch64::SEH_SaveFPLR: 1014 case AArch64::SEH_SaveFPLR_X: 1015 case AArch64::SEH_SaveReg: 1016 case AArch64::SEH_SaveReg_X: 1017 case AArch64::SEH_SaveRegP: 1018 case AArch64::SEH_SaveRegP_X: 1019 case AArch64::SEH_SaveFReg: 1020 case AArch64::SEH_SaveFReg_X: 1021 case AArch64::SEH_SaveFRegP: 1022 case AArch64::SEH_SaveFRegP_X: 1023 case AArch64::SEH_SetFP: 1024 case AArch64::SEH_AddFP: 1025 case AArch64::SEH_Nop: 1026 case AArch64::SEH_PrologEnd: 1027 case AArch64::SEH_EpilogStart: 1028 case AArch64::SEH_EpilogEnd: 1029 return true; 1030 } 1031 } 1032 1033 bool AArch64InstrInfo::isCoalescableExtInstr(const MachineInstr &MI, 1034 Register &SrcReg, Register &DstReg, 1035 unsigned &SubIdx) const { 1036 switch (MI.getOpcode()) { 1037 default: 1038 return false; 1039 case AArch64::SBFMXri: // aka sxtw 1040 case AArch64::UBFMXri: // aka uxtw 1041 // Check for the 32 -> 64 bit extension case, these instructions can do 1042 // much more. 1043 if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31) 1044 return false; 1045 // This is a signed or unsigned 32 -> 64 bit extension. 1046 SrcReg = MI.getOperand(1).getReg(); 1047 DstReg = MI.getOperand(0).getReg(); 1048 SubIdx = AArch64::sub_32; 1049 return true; 1050 } 1051 } 1052 1053 bool AArch64InstrInfo::areMemAccessesTriviallyDisjoint( 1054 const MachineInstr &MIa, const MachineInstr &MIb) const { 1055 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1056 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr; 1057 int64_t OffsetA = 0, OffsetB = 0; 1058 unsigned WidthA = 0, WidthB = 0; 1059 bool OffsetAIsScalable = false, OffsetBIsScalable = false; 1060 1061 assert(MIa.mayLoadOrStore() && "MIa must be a load or store."); 1062 assert(MIb.mayLoadOrStore() && "MIb must be a load or store."); 1063 1064 if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() || 1065 MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef()) 1066 return false; 1067 1068 // Retrieve the base, offset from the base and width. Width 1069 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If 1070 // base are identical, and the offset of a lower memory access + 1071 // the width doesn't overlap the offset of a higher memory access, 1072 // then the memory accesses are different. 1073 // If OffsetAIsScalable and OffsetBIsScalable are both true, they 1074 // are assumed to have the same scale (vscale). 1075 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable, 1076 WidthA, TRI) && 1077 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable, 1078 WidthB, TRI)) { 1079 if (BaseOpA->isIdenticalTo(*BaseOpB) && 1080 OffsetAIsScalable == OffsetBIsScalable) { 1081 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB; 1082 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA; 1083 int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB; 1084 if (LowOffset + LowWidth <= HighOffset) 1085 return true; 1086 } 1087 } 1088 return false; 1089 } 1090 1091 bool AArch64InstrInfo::isSchedulingBoundary(const MachineInstr &MI, 1092 const MachineBasicBlock *MBB, 1093 const MachineFunction &MF) const { 1094 if (TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF)) 1095 return true; 1096 switch (MI.getOpcode()) { 1097 case AArch64::HINT: 1098 // CSDB hints are scheduling barriers. 1099 if (MI.getOperand(0).getImm() == 0x14) 1100 return true; 1101 break; 1102 case AArch64::DSB: 1103 case AArch64::ISB: 1104 // DSB and ISB also are scheduling barriers. 1105 return true; 1106 default:; 1107 } 1108 return isSEHInstruction(MI); 1109 } 1110 1111 /// analyzeCompare - For a comparison instruction, return the source registers 1112 /// in SrcReg and SrcReg2, and the value it compares against in CmpValue. 1113 /// Return true if the comparison instruction can be analyzed. 1114 bool AArch64InstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg, 1115 Register &SrcReg2, int &CmpMask, 1116 int &CmpValue) const { 1117 // The first operand can be a frame index where we'd normally expect a 1118 // register. 1119 assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands"); 1120 if (!MI.getOperand(1).isReg()) 1121 return false; 1122 1123 switch (MI.getOpcode()) { 1124 default: 1125 break; 1126 case AArch64::PTEST_PP: 1127 SrcReg = MI.getOperand(0).getReg(); 1128 SrcReg2 = MI.getOperand(1).getReg(); 1129 // Not sure about the mask and value for now... 1130 CmpMask = ~0; 1131 CmpValue = 0; 1132 return true; 1133 case AArch64::SUBSWrr: 1134 case AArch64::SUBSWrs: 1135 case AArch64::SUBSWrx: 1136 case AArch64::SUBSXrr: 1137 case AArch64::SUBSXrs: 1138 case AArch64::SUBSXrx: 1139 case AArch64::ADDSWrr: 1140 case AArch64::ADDSWrs: 1141 case AArch64::ADDSWrx: 1142 case AArch64::ADDSXrr: 1143 case AArch64::ADDSXrs: 1144 case AArch64::ADDSXrx: 1145 // Replace SUBSWrr with SUBWrr if NZCV is not used. 1146 SrcReg = MI.getOperand(1).getReg(); 1147 SrcReg2 = MI.getOperand(2).getReg(); 1148 CmpMask = ~0; 1149 CmpValue = 0; 1150 return true; 1151 case AArch64::SUBSWri: 1152 case AArch64::ADDSWri: 1153 case AArch64::SUBSXri: 1154 case AArch64::ADDSXri: 1155 SrcReg = MI.getOperand(1).getReg(); 1156 SrcReg2 = 0; 1157 CmpMask = ~0; 1158 // FIXME: In order to convert CmpValue to 0 or 1 1159 CmpValue = MI.getOperand(2).getImm() != 0; 1160 return true; 1161 case AArch64::ANDSWri: 1162 case AArch64::ANDSXri: 1163 // ANDS does not use the same encoding scheme as the others xxxS 1164 // instructions. 1165 SrcReg = MI.getOperand(1).getReg(); 1166 SrcReg2 = 0; 1167 CmpMask = ~0; 1168 // FIXME:The return val type of decodeLogicalImmediate is uint64_t, 1169 // while the type of CmpValue is int. When converting uint64_t to int, 1170 // the high 32 bits of uint64_t will be lost. 1171 // In fact it causes a bug in spec2006-483.xalancbmk 1172 // CmpValue is only used to compare with zero in OptimizeCompareInstr 1173 CmpValue = AArch64_AM::decodeLogicalImmediate( 1174 MI.getOperand(2).getImm(), 1175 MI.getOpcode() == AArch64::ANDSWri ? 32 : 64) != 0; 1176 return true; 1177 } 1178 1179 return false; 1180 } 1181 1182 static bool UpdateOperandRegClass(MachineInstr &Instr) { 1183 MachineBasicBlock *MBB = Instr.getParent(); 1184 assert(MBB && "Can't get MachineBasicBlock here"); 1185 MachineFunction *MF = MBB->getParent(); 1186 assert(MF && "Can't get MachineFunction here"); 1187 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1188 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 1189 MachineRegisterInfo *MRI = &MF->getRegInfo(); 1190 1191 for (unsigned OpIdx = 0, EndIdx = Instr.getNumOperands(); OpIdx < EndIdx; 1192 ++OpIdx) { 1193 MachineOperand &MO = Instr.getOperand(OpIdx); 1194 const TargetRegisterClass *OpRegCstraints = 1195 Instr.getRegClassConstraint(OpIdx, TII, TRI); 1196 1197 // If there's no constraint, there's nothing to do. 1198 if (!OpRegCstraints) 1199 continue; 1200 // If the operand is a frame index, there's nothing to do here. 1201 // A frame index operand will resolve correctly during PEI. 1202 if (MO.isFI()) 1203 continue; 1204 1205 assert(MO.isReg() && 1206 "Operand has register constraints without being a register!"); 1207 1208 Register Reg = MO.getReg(); 1209 if (Register::isPhysicalRegister(Reg)) { 1210 if (!OpRegCstraints->contains(Reg)) 1211 return false; 1212 } else if (!OpRegCstraints->hasSubClassEq(MRI->getRegClass(Reg)) && 1213 !MRI->constrainRegClass(Reg, OpRegCstraints)) 1214 return false; 1215 } 1216 1217 return true; 1218 } 1219 1220 /// Return the opcode that does not set flags when possible - otherwise 1221 /// return the original opcode. The caller is responsible to do the actual 1222 /// substitution and legality checking. 1223 static unsigned convertToNonFlagSettingOpc(const MachineInstr &MI) { 1224 // Don't convert all compare instructions, because for some the zero register 1225 // encoding becomes the sp register. 1226 bool MIDefinesZeroReg = false; 1227 if (MI.definesRegister(AArch64::WZR) || MI.definesRegister(AArch64::XZR)) 1228 MIDefinesZeroReg = true; 1229 1230 switch (MI.getOpcode()) { 1231 default: 1232 return MI.getOpcode(); 1233 case AArch64::ADDSWrr: 1234 return AArch64::ADDWrr; 1235 case AArch64::ADDSWri: 1236 return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri; 1237 case AArch64::ADDSWrs: 1238 return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs; 1239 case AArch64::ADDSWrx: 1240 return AArch64::ADDWrx; 1241 case AArch64::ADDSXrr: 1242 return AArch64::ADDXrr; 1243 case AArch64::ADDSXri: 1244 return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri; 1245 case AArch64::ADDSXrs: 1246 return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs; 1247 case AArch64::ADDSXrx: 1248 return AArch64::ADDXrx; 1249 case AArch64::SUBSWrr: 1250 return AArch64::SUBWrr; 1251 case AArch64::SUBSWri: 1252 return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri; 1253 case AArch64::SUBSWrs: 1254 return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs; 1255 case AArch64::SUBSWrx: 1256 return AArch64::SUBWrx; 1257 case AArch64::SUBSXrr: 1258 return AArch64::SUBXrr; 1259 case AArch64::SUBSXri: 1260 return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri; 1261 case AArch64::SUBSXrs: 1262 return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs; 1263 case AArch64::SUBSXrx: 1264 return AArch64::SUBXrx; 1265 } 1266 } 1267 1268 enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 }; 1269 1270 /// True when condition flags are accessed (either by writing or reading) 1271 /// on the instruction trace starting at From and ending at To. 1272 /// 1273 /// Note: If From and To are from different blocks it's assumed CC are accessed 1274 /// on the path. 1275 static bool areCFlagsAccessedBetweenInstrs( 1276 MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, 1277 const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) { 1278 // Early exit if To is at the beginning of the BB. 1279 if (To == To->getParent()->begin()) 1280 return true; 1281 1282 // Check whether the instructions are in the same basic block 1283 // If not, assume the condition flags might get modified somewhere. 1284 if (To->getParent() != From->getParent()) 1285 return true; 1286 1287 // From must be above To. 1288 assert(std::any_of( 1289 ++To.getReverse(), To->getParent()->rend(), 1290 [From](MachineInstr &MI) { return MI.getIterator() == From; })); 1291 1292 // We iterate backward starting at \p To until we hit \p From. 1293 for (const MachineInstr &Instr : 1294 instructionsWithoutDebug(++To.getReverse(), From.getReverse())) { 1295 if (((AccessToCheck & AK_Write) && 1296 Instr.modifiesRegister(AArch64::NZCV, TRI)) || 1297 ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI))) 1298 return true; 1299 } 1300 return false; 1301 } 1302 1303 /// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating 1304 /// operation which could set the flags in an identical manner 1305 bool AArch64InstrInfo::optimizePTestInstr( 1306 MachineInstr *PTest, unsigned MaskReg, unsigned PredReg, 1307 const MachineRegisterInfo *MRI) const { 1308 auto *Mask = MRI->getUniqueVRegDef(MaskReg); 1309 auto *Pred = MRI->getUniqueVRegDef(PredReg); 1310 auto NewOp = Pred->getOpcode(); 1311 bool OpChanged = false; 1312 1313 unsigned MaskOpcode = Mask->getOpcode(); 1314 unsigned PredOpcode = Pred->getOpcode(); 1315 bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode); 1316 bool PredIsWhileLike = isWhileOpcode(PredOpcode); 1317 1318 if (isPTrueOpcode(MaskOpcode) && (PredIsPTestLike || PredIsWhileLike)) { 1319 // For PTEST(PTRUE, OTHER_INST), PTEST is redundant when PTRUE doesn't 1320 // deactivate any lanes OTHER_INST might set. 1321 uint64_t MaskElementSize = getElementSizeForOpcode(MaskOpcode); 1322 uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode); 1323 1324 // Must be an all active predicate of matching element size. 1325 if ((PredElementSize != MaskElementSize) || 1326 (Mask->getOperand(1).getImm() != 31)) 1327 return false; 1328 1329 // Fallthough to simply remove the PTEST. 1330 } else if ((Mask == Pred) && (PredIsPTestLike || PredIsWhileLike)) { 1331 // For PTEST(PG, PG), PTEST is redundant when PG is the result of an 1332 // instruction that sets the flags as PTEST would. 1333 1334 // Fallthough to simply remove the PTEST. 1335 } else if (PredIsPTestLike) { 1336 // For PTEST(PG_1, PTEST_LIKE(PG2, ...)), PTEST is redundant when both 1337 // instructions use the same predicate. 1338 auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg()); 1339 if (Mask != PTestLikeMask) 1340 return false; 1341 1342 // Fallthough to simply remove the PTEST. 1343 } else { 1344 switch (Pred->getOpcode()) { 1345 case AArch64::BRKB_PPzP: 1346 case AArch64::BRKPB_PPzPP: { 1347 // Op 0 is chain, 1 is the mask, 2 the previous predicate to 1348 // propagate, 3 the new predicate. 1349 1350 // Check to see if our mask is the same as the brkpb's. If 1351 // not the resulting flag bits may be different and we 1352 // can't remove the ptest. 1353 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg()); 1354 if (Mask != PredMask) 1355 return false; 1356 1357 // Switch to the new opcode 1358 NewOp = Pred->getOpcode() == AArch64::BRKB_PPzP ? AArch64::BRKBS_PPzP 1359 : AArch64::BRKPBS_PPzPP; 1360 OpChanged = true; 1361 break; 1362 } 1363 case AArch64::BRKN_PPzP: { 1364 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg()); 1365 if (Mask != PredMask) 1366 return false; 1367 1368 NewOp = AArch64::BRKNS_PPzP; 1369 OpChanged = true; 1370 break; 1371 } 1372 case AArch64::RDFFR_PPz: { 1373 // rdffr p1.b, PredMask=p0/z <--- Definition of Pred 1374 // ptest Mask=p0, Pred=p1.b <--- If equal masks, remove this and use 1375 // `rdffrs p1.b, p0/z` above. 1376 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg()); 1377 if (Mask != PredMask) 1378 return false; 1379 1380 NewOp = AArch64::RDFFRS_PPz; 1381 OpChanged = true; 1382 break; 1383 } 1384 default: 1385 // Bail out if we don't recognize the input 1386 return false; 1387 } 1388 } 1389 1390 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1391 1392 // If another instruction between Pred and PTest accesses flags, don't remove 1393 // the ptest or update the earlier instruction to modify them. 1394 if (areCFlagsAccessedBetweenInstrs(Pred, PTest, TRI)) 1395 return false; 1396 1397 // If we pass all the checks, it's safe to remove the PTEST and use the flags 1398 // as they are prior to PTEST. Sometimes this requires the tested PTEST 1399 // operand to be replaced with an equivalent instruction that also sets the 1400 // flags. 1401 Pred->setDesc(get(NewOp)); 1402 PTest->eraseFromParent(); 1403 if (OpChanged) { 1404 bool succeeded = UpdateOperandRegClass(*Pred); 1405 (void)succeeded; 1406 assert(succeeded && "Operands have incompatible register classes!"); 1407 Pred->addRegisterDefined(AArch64::NZCV, TRI); 1408 } 1409 1410 // Ensure that the flags def is live. 1411 if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) { 1412 unsigned i = 0, e = Pred->getNumOperands(); 1413 for (; i != e; ++i) { 1414 MachineOperand &MO = Pred->getOperand(i); 1415 if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) { 1416 MO.setIsDead(false); 1417 break; 1418 } 1419 } 1420 } 1421 return true; 1422 } 1423 1424 /// Try to optimize a compare instruction. A compare instruction is an 1425 /// instruction which produces AArch64::NZCV. It can be truly compare 1426 /// instruction 1427 /// when there are no uses of its destination register. 1428 /// 1429 /// The following steps are tried in order: 1430 /// 1. Convert CmpInstr into an unconditional version. 1431 /// 2. Remove CmpInstr if above there is an instruction producing a needed 1432 /// condition code or an instruction which can be converted into such an 1433 /// instruction. 1434 /// Only comparison with zero is supported. 1435 bool AArch64InstrInfo::optimizeCompareInstr( 1436 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int CmpMask, 1437 int CmpValue, const MachineRegisterInfo *MRI) const { 1438 assert(CmpInstr.getParent()); 1439 assert(MRI); 1440 1441 // Replace SUBSWrr with SUBWrr if NZCV is not used. 1442 int DeadNZCVIdx = CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, true); 1443 if (DeadNZCVIdx != -1) { 1444 if (CmpInstr.definesRegister(AArch64::WZR) || 1445 CmpInstr.definesRegister(AArch64::XZR)) { 1446 CmpInstr.eraseFromParent(); 1447 return true; 1448 } 1449 unsigned Opc = CmpInstr.getOpcode(); 1450 unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr); 1451 if (NewOpc == Opc) 1452 return false; 1453 const MCInstrDesc &MCID = get(NewOpc); 1454 CmpInstr.setDesc(MCID); 1455 CmpInstr.RemoveOperand(DeadNZCVIdx); 1456 bool succeeded = UpdateOperandRegClass(CmpInstr); 1457 (void)succeeded; 1458 assert(succeeded && "Some operands reg class are incompatible!"); 1459 return true; 1460 } 1461 1462 if (CmpInstr.getOpcode() == AArch64::PTEST_PP) 1463 return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI); 1464 1465 // Continue only if we have a "ri" where immediate is zero. 1466 // FIXME:CmpValue has already been converted to 0 or 1 in analyzeCompare 1467 // function. 1468 assert((CmpValue == 0 || CmpValue == 1) && "CmpValue must be 0 or 1!"); 1469 if (SrcReg2 != 0) 1470 return false; 1471 1472 // CmpInstr is a Compare instruction if destination register is not used. 1473 if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg())) 1474 return false; 1475 1476 if (!CmpValue && substituteCmpToZero(CmpInstr, SrcReg, *MRI)) 1477 return true; 1478 return removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI); 1479 } 1480 1481 /// Get opcode of S version of Instr. 1482 /// If Instr is S version its opcode is returned. 1483 /// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version 1484 /// or we are not interested in it. 1485 static unsigned sForm(MachineInstr &Instr) { 1486 switch (Instr.getOpcode()) { 1487 default: 1488 return AArch64::INSTRUCTION_LIST_END; 1489 1490 case AArch64::ADDSWrr: 1491 case AArch64::ADDSWri: 1492 case AArch64::ADDSXrr: 1493 case AArch64::ADDSXri: 1494 case AArch64::SUBSWrr: 1495 case AArch64::SUBSWri: 1496 case AArch64::SUBSXrr: 1497 case AArch64::SUBSXri: 1498 return Instr.getOpcode(); 1499 1500 case AArch64::ADDWrr: 1501 return AArch64::ADDSWrr; 1502 case AArch64::ADDWri: 1503 return AArch64::ADDSWri; 1504 case AArch64::ADDXrr: 1505 return AArch64::ADDSXrr; 1506 case AArch64::ADDXri: 1507 return AArch64::ADDSXri; 1508 case AArch64::ADCWr: 1509 return AArch64::ADCSWr; 1510 case AArch64::ADCXr: 1511 return AArch64::ADCSXr; 1512 case AArch64::SUBWrr: 1513 return AArch64::SUBSWrr; 1514 case AArch64::SUBWri: 1515 return AArch64::SUBSWri; 1516 case AArch64::SUBXrr: 1517 return AArch64::SUBSXrr; 1518 case AArch64::SUBXri: 1519 return AArch64::SUBSXri; 1520 case AArch64::SBCWr: 1521 return AArch64::SBCSWr; 1522 case AArch64::SBCXr: 1523 return AArch64::SBCSXr; 1524 case AArch64::ANDWri: 1525 return AArch64::ANDSWri; 1526 case AArch64::ANDXri: 1527 return AArch64::ANDSXri; 1528 } 1529 } 1530 1531 /// Check if AArch64::NZCV should be alive in successors of MBB. 1532 static bool areCFlagsAliveInSuccessors(const MachineBasicBlock *MBB) { 1533 for (auto *BB : MBB->successors()) 1534 if (BB->isLiveIn(AArch64::NZCV)) 1535 return true; 1536 return false; 1537 } 1538 1539 /// \returns The condition code operand index for \p Instr if it is a branch 1540 /// or select and -1 otherwise. 1541 static int 1542 findCondCodeUseOperandIdxForBranchOrSelect(const MachineInstr &Instr) { 1543 switch (Instr.getOpcode()) { 1544 default: 1545 return -1; 1546 1547 case AArch64::Bcc: { 1548 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV); 1549 assert(Idx >= 2); 1550 return Idx - 2; 1551 } 1552 1553 case AArch64::CSINVWr: 1554 case AArch64::CSINVXr: 1555 case AArch64::CSINCWr: 1556 case AArch64::CSINCXr: 1557 case AArch64::CSELWr: 1558 case AArch64::CSELXr: 1559 case AArch64::CSNEGWr: 1560 case AArch64::CSNEGXr: 1561 case AArch64::FCSELSrrr: 1562 case AArch64::FCSELDrrr: { 1563 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV); 1564 assert(Idx >= 1); 1565 return Idx - 1; 1566 } 1567 } 1568 } 1569 1570 namespace { 1571 1572 struct UsedNZCV { 1573 bool N = false; 1574 bool Z = false; 1575 bool C = false; 1576 bool V = false; 1577 1578 UsedNZCV() = default; 1579 1580 UsedNZCV &operator|=(const UsedNZCV &UsedFlags) { 1581 this->N |= UsedFlags.N; 1582 this->Z |= UsedFlags.Z; 1583 this->C |= UsedFlags.C; 1584 this->V |= UsedFlags.V; 1585 return *this; 1586 } 1587 }; 1588 1589 } // end anonymous namespace 1590 1591 /// Find a condition code used by the instruction. 1592 /// Returns AArch64CC::Invalid if either the instruction does not use condition 1593 /// codes or we don't optimize CmpInstr in the presence of such instructions. 1594 static AArch64CC::CondCode findCondCodeUsedByInstr(const MachineInstr &Instr) { 1595 int CCIdx = findCondCodeUseOperandIdxForBranchOrSelect(Instr); 1596 return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>( 1597 Instr.getOperand(CCIdx).getImm()) 1598 : AArch64CC::Invalid; 1599 } 1600 1601 static UsedNZCV getUsedNZCV(AArch64CC::CondCode CC) { 1602 assert(CC != AArch64CC::Invalid); 1603 UsedNZCV UsedFlags; 1604 switch (CC) { 1605 default: 1606 break; 1607 1608 case AArch64CC::EQ: // Z set 1609 case AArch64CC::NE: // Z clear 1610 UsedFlags.Z = true; 1611 break; 1612 1613 case AArch64CC::HI: // Z clear and C set 1614 case AArch64CC::LS: // Z set or C clear 1615 UsedFlags.Z = true; 1616 LLVM_FALLTHROUGH; 1617 case AArch64CC::HS: // C set 1618 case AArch64CC::LO: // C clear 1619 UsedFlags.C = true; 1620 break; 1621 1622 case AArch64CC::MI: // N set 1623 case AArch64CC::PL: // N clear 1624 UsedFlags.N = true; 1625 break; 1626 1627 case AArch64CC::VS: // V set 1628 case AArch64CC::VC: // V clear 1629 UsedFlags.V = true; 1630 break; 1631 1632 case AArch64CC::GT: // Z clear, N and V the same 1633 case AArch64CC::LE: // Z set, N and V differ 1634 UsedFlags.Z = true; 1635 LLVM_FALLTHROUGH; 1636 case AArch64CC::GE: // N and V the same 1637 case AArch64CC::LT: // N and V differ 1638 UsedFlags.N = true; 1639 UsedFlags.V = true; 1640 break; 1641 } 1642 return UsedFlags; 1643 } 1644 1645 /// \returns Conditions flags used after \p CmpInstr in its MachineBB if they 1646 /// are not containing C or V flags and NZCV flags are not alive in successors 1647 /// of the same \p CmpInstr and \p MI parent. \returns None otherwise. 1648 /// 1649 /// Collect instructions using that flags in \p CCUseInstrs if provided. 1650 static Optional<UsedNZCV> 1651 examineCFlagsUse(MachineInstr &MI, MachineInstr &CmpInstr, 1652 const TargetRegisterInfo &TRI, 1653 SmallVectorImpl<MachineInstr *> *CCUseInstrs = nullptr) { 1654 MachineBasicBlock *CmpParent = CmpInstr.getParent(); 1655 if (MI.getParent() != CmpParent) 1656 return None; 1657 1658 if (areCFlagsAliveInSuccessors(CmpParent)) 1659 return None; 1660 1661 UsedNZCV NZCVUsedAfterCmp; 1662 for (MachineInstr &Instr : instructionsWithoutDebug( 1663 std::next(CmpInstr.getIterator()), CmpParent->instr_end())) { 1664 if (Instr.readsRegister(AArch64::NZCV, &TRI)) { 1665 AArch64CC::CondCode CC = findCondCodeUsedByInstr(Instr); 1666 if (CC == AArch64CC::Invalid) // Unsupported conditional instruction 1667 return None; 1668 NZCVUsedAfterCmp |= getUsedNZCV(CC); 1669 if (CCUseInstrs) 1670 CCUseInstrs->push_back(&Instr); 1671 } 1672 if (Instr.modifiesRegister(AArch64::NZCV, &TRI)) 1673 break; 1674 } 1675 if (NZCVUsedAfterCmp.C || NZCVUsedAfterCmp.V) 1676 return None; 1677 return NZCVUsedAfterCmp; 1678 } 1679 1680 static bool isADDSRegImm(unsigned Opcode) { 1681 return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri; 1682 } 1683 1684 static bool isSUBSRegImm(unsigned Opcode) { 1685 return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri; 1686 } 1687 1688 /// Check if CmpInstr can be substituted by MI. 1689 /// 1690 /// CmpInstr can be substituted: 1691 /// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0' 1692 /// - and, MI and CmpInstr are from the same MachineBB 1693 /// - and, condition flags are not alive in successors of the CmpInstr parent 1694 /// - and, if MI opcode is the S form there must be no defs of flags between 1695 /// MI and CmpInstr 1696 /// or if MI opcode is not the S form there must be neither defs of flags 1697 /// nor uses of flags between MI and CmpInstr. 1698 /// - and C/V flags are not used after CmpInstr 1699 static bool canInstrSubstituteCmpInstr(MachineInstr &MI, MachineInstr &CmpInstr, 1700 const TargetRegisterInfo &TRI) { 1701 assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END); 1702 1703 const unsigned CmpOpcode = CmpInstr.getOpcode(); 1704 if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode)) 1705 return false; 1706 1707 if (!examineCFlagsUse(MI, CmpInstr, TRI)) 1708 return false; 1709 1710 AccessKind AccessToCheck = AK_Write; 1711 if (sForm(MI) != MI.getOpcode()) 1712 AccessToCheck = AK_All; 1713 return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck); 1714 } 1715 1716 /// Substitute an instruction comparing to zero with another instruction 1717 /// which produces needed condition flags. 1718 /// 1719 /// Return true on success. 1720 bool AArch64InstrInfo::substituteCmpToZero( 1721 MachineInstr &CmpInstr, unsigned SrcReg, 1722 const MachineRegisterInfo &MRI) const { 1723 // Get the unique definition of SrcReg. 1724 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg); 1725 if (!MI) 1726 return false; 1727 1728 const TargetRegisterInfo &TRI = getRegisterInfo(); 1729 1730 unsigned NewOpc = sForm(*MI); 1731 if (NewOpc == AArch64::INSTRUCTION_LIST_END) 1732 return false; 1733 1734 if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI)) 1735 return false; 1736 1737 // Update the instruction to set NZCV. 1738 MI->setDesc(get(NewOpc)); 1739 CmpInstr.eraseFromParent(); 1740 bool succeeded = UpdateOperandRegClass(*MI); 1741 (void)succeeded; 1742 assert(succeeded && "Some operands reg class are incompatible!"); 1743 MI->addRegisterDefined(AArch64::NZCV, &TRI); 1744 return true; 1745 } 1746 1747 /// \returns True if \p CmpInstr can be removed. 1748 /// 1749 /// \p IsInvertCC is true if, after removing \p CmpInstr, condition 1750 /// codes used in \p CCUseInstrs must be inverted. 1751 static bool canCmpInstrBeRemoved(MachineInstr &MI, MachineInstr &CmpInstr, 1752 int CmpValue, const TargetRegisterInfo &TRI, 1753 SmallVectorImpl<MachineInstr *> &CCUseInstrs, 1754 bool &IsInvertCC) { 1755 assert((CmpValue == 0 || CmpValue == 1) && 1756 "Only comparisons to 0 or 1 considered for removal!"); 1757 1758 // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>' 1759 unsigned MIOpc = MI.getOpcode(); 1760 if (MIOpc == AArch64::CSINCWr) { 1761 if (MI.getOperand(1).getReg() != AArch64::WZR || 1762 MI.getOperand(2).getReg() != AArch64::WZR) 1763 return false; 1764 } else if (MIOpc == AArch64::CSINCXr) { 1765 if (MI.getOperand(1).getReg() != AArch64::XZR || 1766 MI.getOperand(2).getReg() != AArch64::XZR) 1767 return false; 1768 } else { 1769 return false; 1770 } 1771 AArch64CC::CondCode MICC = findCondCodeUsedByInstr(MI); 1772 if (MICC == AArch64CC::Invalid) 1773 return false; 1774 1775 // NZCV needs to be defined 1776 if (MI.findRegisterDefOperandIdx(AArch64::NZCV, true) != -1) 1777 return false; 1778 1779 // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1' 1780 const unsigned CmpOpcode = CmpInstr.getOpcode(); 1781 bool IsSubsRegImm = isSUBSRegImm(CmpOpcode); 1782 if (CmpValue && !IsSubsRegImm) 1783 return false; 1784 if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode)) 1785 return false; 1786 1787 // MI conditions allowed: eq, ne, mi, pl 1788 UsedNZCV MIUsedNZCV = getUsedNZCV(MICC); 1789 if (MIUsedNZCV.C || MIUsedNZCV.V) 1790 return false; 1791 1792 Optional<UsedNZCV> NZCVUsedAfterCmp = 1793 examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs); 1794 // Condition flags are not used in CmpInstr basic block successors and only 1795 // Z or N flags allowed to be used after CmpInstr within its basic block 1796 if (!NZCVUsedAfterCmp) 1797 return false; 1798 // Z or N flag used after CmpInstr must correspond to the flag used in MI 1799 if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) || 1800 (MIUsedNZCV.N && NZCVUsedAfterCmp->Z)) 1801 return false; 1802 // If CmpInstr is comparison to zero MI conditions are limited to eq, ne 1803 if (MIUsedNZCV.N && !CmpValue) 1804 return false; 1805 1806 // There must be no defs of flags between MI and CmpInstr 1807 if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write)) 1808 return false; 1809 1810 // Condition code is inverted in the following cases: 1811 // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' 1812 // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1' 1813 IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) || 1814 (!CmpValue && MICC == AArch64CC::NE); 1815 return true; 1816 } 1817 1818 /// Remove comparision in csinc-cmp sequence 1819 /// 1820 /// Examples: 1821 /// 1. \code 1822 /// csinc w9, wzr, wzr, ne 1823 /// cmp w9, #0 1824 /// b.eq 1825 /// \endcode 1826 /// to 1827 /// \code 1828 /// csinc w9, wzr, wzr, ne 1829 /// b.ne 1830 /// \endcode 1831 /// 1832 /// 2. \code 1833 /// csinc x2, xzr, xzr, mi 1834 /// cmp x2, #1 1835 /// b.pl 1836 /// \endcode 1837 /// to 1838 /// \code 1839 /// csinc x2, xzr, xzr, mi 1840 /// b.pl 1841 /// \endcode 1842 /// 1843 /// \param CmpInstr comparison instruction 1844 /// \return True when comparison removed 1845 bool AArch64InstrInfo::removeCmpToZeroOrOne( 1846 MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue, 1847 const MachineRegisterInfo &MRI) const { 1848 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg); 1849 if (!MI) 1850 return false; 1851 const TargetRegisterInfo &TRI = getRegisterInfo(); 1852 SmallVector<MachineInstr *, 4> CCUseInstrs; 1853 bool IsInvertCC = false; 1854 if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs, 1855 IsInvertCC)) 1856 return false; 1857 // Make transformation 1858 CmpInstr.eraseFromParent(); 1859 if (IsInvertCC) { 1860 // Invert condition codes in CmpInstr CC users 1861 for (MachineInstr *CCUseInstr : CCUseInstrs) { 1862 int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr); 1863 assert(Idx >= 0 && "Unexpected instruction using CC."); 1864 MachineOperand &CCOperand = CCUseInstr->getOperand(Idx); 1865 AArch64CC::CondCode CCUse = AArch64CC::getInvertedCondCode( 1866 static_cast<AArch64CC::CondCode>(CCOperand.getImm())); 1867 CCOperand.setImm(CCUse); 1868 } 1869 } 1870 return true; 1871 } 1872 1873 bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const { 1874 if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD && 1875 MI.getOpcode() != AArch64::CATCHRET) 1876 return false; 1877 1878 MachineBasicBlock &MBB = *MI.getParent(); 1879 auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>(); 1880 auto TRI = Subtarget.getRegisterInfo(); 1881 DebugLoc DL = MI.getDebugLoc(); 1882 1883 if (MI.getOpcode() == AArch64::CATCHRET) { 1884 // Skip to the first instruction before the epilog. 1885 const TargetInstrInfo *TII = 1886 MBB.getParent()->getSubtarget().getInstrInfo(); 1887 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB(); 1888 auto MBBI = MachineBasicBlock::iterator(MI); 1889 MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI); 1890 while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) && 1891 FirstEpilogSEH != MBB.begin()) 1892 FirstEpilogSEH = std::prev(FirstEpilogSEH); 1893 if (FirstEpilogSEH != MBB.begin()) 1894 FirstEpilogSEH = std::next(FirstEpilogSEH); 1895 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP)) 1896 .addReg(AArch64::X0, RegState::Define) 1897 .addMBB(TargetMBB); 1898 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri)) 1899 .addReg(AArch64::X0, RegState::Define) 1900 .addReg(AArch64::X0) 1901 .addMBB(TargetMBB) 1902 .addImm(0); 1903 return true; 1904 } 1905 1906 Register Reg = MI.getOperand(0).getReg(); 1907 const GlobalValue *GV = 1908 cast<GlobalValue>((*MI.memoperands_begin())->getValue()); 1909 const TargetMachine &TM = MBB.getParent()->getTarget(); 1910 unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM); 1911 const unsigned char MO_NC = AArch64II::MO_NC; 1912 1913 if ((OpFlags & AArch64II::MO_GOT) != 0) { 1914 BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg) 1915 .addGlobalAddress(GV, 0, OpFlags); 1916 if (Subtarget.isTargetILP32()) { 1917 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32); 1918 BuildMI(MBB, MI, DL, get(AArch64::LDRWui)) 1919 .addDef(Reg32, RegState::Dead) 1920 .addUse(Reg, RegState::Kill) 1921 .addImm(0) 1922 .addMemOperand(*MI.memoperands_begin()) 1923 .addDef(Reg, RegState::Implicit); 1924 } else { 1925 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg) 1926 .addReg(Reg, RegState::Kill) 1927 .addImm(0) 1928 .addMemOperand(*MI.memoperands_begin()); 1929 } 1930 } else if (TM.getCodeModel() == CodeModel::Large) { 1931 assert(!Subtarget.isTargetILP32() && "how can large exist in ILP32?"); 1932 BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg) 1933 .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC) 1934 .addImm(0); 1935 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg) 1936 .addReg(Reg, RegState::Kill) 1937 .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC) 1938 .addImm(16); 1939 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg) 1940 .addReg(Reg, RegState::Kill) 1941 .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC) 1942 .addImm(32); 1943 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg) 1944 .addReg(Reg, RegState::Kill) 1945 .addGlobalAddress(GV, 0, AArch64II::MO_G3) 1946 .addImm(48); 1947 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg) 1948 .addReg(Reg, RegState::Kill) 1949 .addImm(0) 1950 .addMemOperand(*MI.memoperands_begin()); 1951 } else if (TM.getCodeModel() == CodeModel::Tiny) { 1952 BuildMI(MBB, MI, DL, get(AArch64::ADR), Reg) 1953 .addGlobalAddress(GV, 0, OpFlags); 1954 } else { 1955 BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg) 1956 .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE); 1957 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC; 1958 if (Subtarget.isTargetILP32()) { 1959 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32); 1960 BuildMI(MBB, MI, DL, get(AArch64::LDRWui)) 1961 .addDef(Reg32, RegState::Dead) 1962 .addUse(Reg, RegState::Kill) 1963 .addGlobalAddress(GV, 0, LoFlags) 1964 .addMemOperand(*MI.memoperands_begin()) 1965 .addDef(Reg, RegState::Implicit); 1966 } else { 1967 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg) 1968 .addReg(Reg, RegState::Kill) 1969 .addGlobalAddress(GV, 0, LoFlags) 1970 .addMemOperand(*MI.memoperands_begin()); 1971 } 1972 } 1973 1974 MBB.erase(MI); 1975 1976 return true; 1977 } 1978 1979 // Return true if this instruction simply sets its single destination register 1980 // to zero. This is equivalent to a register rename of the zero-register. 1981 bool AArch64InstrInfo::isGPRZero(const MachineInstr &MI) { 1982 switch (MI.getOpcode()) { 1983 default: 1984 break; 1985 case AArch64::MOVZWi: 1986 case AArch64::MOVZXi: // movz Rd, #0 (LSL #0) 1987 if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) { 1988 assert(MI.getDesc().getNumOperands() == 3 && 1989 MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands"); 1990 return true; 1991 } 1992 break; 1993 case AArch64::ANDWri: // and Rd, Rzr, #imm 1994 return MI.getOperand(1).getReg() == AArch64::WZR; 1995 case AArch64::ANDXri: 1996 return MI.getOperand(1).getReg() == AArch64::XZR; 1997 case TargetOpcode::COPY: 1998 return MI.getOperand(1).getReg() == AArch64::WZR; 1999 } 2000 return false; 2001 } 2002 2003 // Return true if this instruction simply renames a general register without 2004 // modifying bits. 2005 bool AArch64InstrInfo::isGPRCopy(const MachineInstr &MI) { 2006 switch (MI.getOpcode()) { 2007 default: 2008 break; 2009 case TargetOpcode::COPY: { 2010 // GPR32 copies will by lowered to ORRXrs 2011 Register DstReg = MI.getOperand(0).getReg(); 2012 return (AArch64::GPR32RegClass.contains(DstReg) || 2013 AArch64::GPR64RegClass.contains(DstReg)); 2014 } 2015 case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0) 2016 if (MI.getOperand(1).getReg() == AArch64::XZR) { 2017 assert(MI.getDesc().getNumOperands() == 4 && 2018 MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands"); 2019 return true; 2020 } 2021 break; 2022 case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0) 2023 if (MI.getOperand(2).getImm() == 0) { 2024 assert(MI.getDesc().getNumOperands() == 4 && 2025 MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands"); 2026 return true; 2027 } 2028 break; 2029 } 2030 return false; 2031 } 2032 2033 // Return true if this instruction simply renames a general register without 2034 // modifying bits. 2035 bool AArch64InstrInfo::isFPRCopy(const MachineInstr &MI) { 2036 switch (MI.getOpcode()) { 2037 default: 2038 break; 2039 case TargetOpcode::COPY: { 2040 // FPR64 copies will by lowered to ORR.16b 2041 Register DstReg = MI.getOperand(0).getReg(); 2042 return (AArch64::FPR64RegClass.contains(DstReg) || 2043 AArch64::FPR128RegClass.contains(DstReg)); 2044 } 2045 case AArch64::ORRv16i8: 2046 if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) { 2047 assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() && 2048 "invalid ORRv16i8 operands"); 2049 return true; 2050 } 2051 break; 2052 } 2053 return false; 2054 } 2055 2056 unsigned AArch64InstrInfo::isLoadFromStackSlot(const MachineInstr &MI, 2057 int &FrameIndex) const { 2058 switch (MI.getOpcode()) { 2059 default: 2060 break; 2061 case AArch64::LDRWui: 2062 case AArch64::LDRXui: 2063 case AArch64::LDRBui: 2064 case AArch64::LDRHui: 2065 case AArch64::LDRSui: 2066 case AArch64::LDRDui: 2067 case AArch64::LDRQui: 2068 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() && 2069 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) { 2070 FrameIndex = MI.getOperand(1).getIndex(); 2071 return MI.getOperand(0).getReg(); 2072 } 2073 break; 2074 } 2075 2076 return 0; 2077 } 2078 2079 unsigned AArch64InstrInfo::isStoreToStackSlot(const MachineInstr &MI, 2080 int &FrameIndex) const { 2081 switch (MI.getOpcode()) { 2082 default: 2083 break; 2084 case AArch64::STRWui: 2085 case AArch64::STRXui: 2086 case AArch64::STRBui: 2087 case AArch64::STRHui: 2088 case AArch64::STRSui: 2089 case AArch64::STRDui: 2090 case AArch64::STRQui: 2091 case AArch64::LDR_PXI: 2092 case AArch64::STR_PXI: 2093 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() && 2094 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) { 2095 FrameIndex = MI.getOperand(1).getIndex(); 2096 return MI.getOperand(0).getReg(); 2097 } 2098 break; 2099 } 2100 return 0; 2101 } 2102 2103 /// Check all MachineMemOperands for a hint to suppress pairing. 2104 bool AArch64InstrInfo::isLdStPairSuppressed(const MachineInstr &MI) { 2105 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) { 2106 return MMO->getFlags() & MOSuppressPair; 2107 }); 2108 } 2109 2110 /// Set a flag on the first MachineMemOperand to suppress pairing. 2111 void AArch64InstrInfo::suppressLdStPair(MachineInstr &MI) { 2112 if (MI.memoperands_empty()) 2113 return; 2114 (*MI.memoperands_begin())->setFlags(MOSuppressPair); 2115 } 2116 2117 /// Check all MachineMemOperands for a hint that the load/store is strided. 2118 bool AArch64InstrInfo::isStridedAccess(const MachineInstr &MI) { 2119 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) { 2120 return MMO->getFlags() & MOStridedAccess; 2121 }); 2122 } 2123 2124 bool AArch64InstrInfo::hasUnscaledLdStOffset(unsigned Opc) { 2125 switch (Opc) { 2126 default: 2127 return false; 2128 case AArch64::STURSi: 2129 case AArch64::STRSpre: 2130 case AArch64::STURDi: 2131 case AArch64::STRDpre: 2132 case AArch64::STURQi: 2133 case AArch64::STRQpre: 2134 case AArch64::STURBBi: 2135 case AArch64::STURHHi: 2136 case AArch64::STURWi: 2137 case AArch64::STRWpre: 2138 case AArch64::STURXi: 2139 case AArch64::STRXpre: 2140 case AArch64::LDURSi: 2141 case AArch64::LDRSpre: 2142 case AArch64::LDURDi: 2143 case AArch64::LDRDpre: 2144 case AArch64::LDURQi: 2145 case AArch64::LDRQpre: 2146 case AArch64::LDURWi: 2147 case AArch64::LDRWpre: 2148 case AArch64::LDURXi: 2149 case AArch64::LDRXpre: 2150 case AArch64::LDURSWi: 2151 case AArch64::LDURHHi: 2152 case AArch64::LDURBBi: 2153 case AArch64::LDURSBWi: 2154 case AArch64::LDURSHWi: 2155 return true; 2156 } 2157 } 2158 2159 Optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) { 2160 switch (Opc) { 2161 default: return {}; 2162 case AArch64::PRFMui: return AArch64::PRFUMi; 2163 case AArch64::LDRXui: return AArch64::LDURXi; 2164 case AArch64::LDRWui: return AArch64::LDURWi; 2165 case AArch64::LDRBui: return AArch64::LDURBi; 2166 case AArch64::LDRHui: return AArch64::LDURHi; 2167 case AArch64::LDRSui: return AArch64::LDURSi; 2168 case AArch64::LDRDui: return AArch64::LDURDi; 2169 case AArch64::LDRQui: return AArch64::LDURQi; 2170 case AArch64::LDRBBui: return AArch64::LDURBBi; 2171 case AArch64::LDRHHui: return AArch64::LDURHHi; 2172 case AArch64::LDRSBXui: return AArch64::LDURSBXi; 2173 case AArch64::LDRSBWui: return AArch64::LDURSBWi; 2174 case AArch64::LDRSHXui: return AArch64::LDURSHXi; 2175 case AArch64::LDRSHWui: return AArch64::LDURSHWi; 2176 case AArch64::LDRSWui: return AArch64::LDURSWi; 2177 case AArch64::STRXui: return AArch64::STURXi; 2178 case AArch64::STRWui: return AArch64::STURWi; 2179 case AArch64::STRBui: return AArch64::STURBi; 2180 case AArch64::STRHui: return AArch64::STURHi; 2181 case AArch64::STRSui: return AArch64::STURSi; 2182 case AArch64::STRDui: return AArch64::STURDi; 2183 case AArch64::STRQui: return AArch64::STURQi; 2184 case AArch64::STRBBui: return AArch64::STURBBi; 2185 case AArch64::STRHHui: return AArch64::STURHHi; 2186 } 2187 } 2188 2189 unsigned AArch64InstrInfo::getLoadStoreImmIdx(unsigned Opc) { 2190 switch (Opc) { 2191 default: 2192 return 2; 2193 case AArch64::LDPXi: 2194 case AArch64::LDPDi: 2195 case AArch64::STPXi: 2196 case AArch64::STPDi: 2197 case AArch64::LDNPXi: 2198 case AArch64::LDNPDi: 2199 case AArch64::STNPXi: 2200 case AArch64::STNPDi: 2201 case AArch64::LDPQi: 2202 case AArch64::STPQi: 2203 case AArch64::LDNPQi: 2204 case AArch64::STNPQi: 2205 case AArch64::LDPWi: 2206 case AArch64::LDPSi: 2207 case AArch64::STPWi: 2208 case AArch64::STPSi: 2209 case AArch64::LDNPWi: 2210 case AArch64::LDNPSi: 2211 case AArch64::STNPWi: 2212 case AArch64::STNPSi: 2213 case AArch64::LDG: 2214 case AArch64::STGPi: 2215 case AArch64::LD1B_IMM: 2216 case AArch64::LD1H_IMM: 2217 case AArch64::LD1W_IMM: 2218 case AArch64::LD1D_IMM: 2219 case AArch64::ST1B_IMM: 2220 case AArch64::ST1H_IMM: 2221 case AArch64::ST1W_IMM: 2222 case AArch64::ST1D_IMM: 2223 case AArch64::LD1B_H_IMM: 2224 case AArch64::LD1SB_H_IMM: 2225 case AArch64::LD1H_S_IMM: 2226 case AArch64::LD1SH_S_IMM: 2227 case AArch64::LD1W_D_IMM: 2228 case AArch64::LD1SW_D_IMM: 2229 case AArch64::ST1B_H_IMM: 2230 case AArch64::ST1H_S_IMM: 2231 case AArch64::ST1W_D_IMM: 2232 case AArch64::LD1B_S_IMM: 2233 case AArch64::LD1SB_S_IMM: 2234 case AArch64::LD1H_D_IMM: 2235 case AArch64::LD1SH_D_IMM: 2236 case AArch64::ST1B_S_IMM: 2237 case AArch64::ST1H_D_IMM: 2238 case AArch64::LD1B_D_IMM: 2239 case AArch64::LD1SB_D_IMM: 2240 case AArch64::ST1B_D_IMM: 2241 return 3; 2242 case AArch64::ADDG: 2243 case AArch64::STGOffset: 2244 case AArch64::LDR_PXI: 2245 case AArch64::STR_PXI: 2246 return 2; 2247 } 2248 } 2249 2250 bool AArch64InstrInfo::isPairableLdStInst(const MachineInstr &MI) { 2251 switch (MI.getOpcode()) { 2252 default: 2253 return false; 2254 // Scaled instructions. 2255 case AArch64::STRSui: 2256 case AArch64::STRDui: 2257 case AArch64::STRQui: 2258 case AArch64::STRXui: 2259 case AArch64::STRWui: 2260 case AArch64::LDRSui: 2261 case AArch64::LDRDui: 2262 case AArch64::LDRQui: 2263 case AArch64::LDRXui: 2264 case AArch64::LDRWui: 2265 case AArch64::LDRSWui: 2266 // Unscaled instructions. 2267 case AArch64::STURSi: 2268 case AArch64::STRSpre: 2269 case AArch64::STURDi: 2270 case AArch64::STRDpre: 2271 case AArch64::STURQi: 2272 case AArch64::STRQpre: 2273 case AArch64::STURWi: 2274 case AArch64::STRWpre: 2275 case AArch64::STURXi: 2276 case AArch64::STRXpre: 2277 case AArch64::LDURSi: 2278 case AArch64::LDRSpre: 2279 case AArch64::LDURDi: 2280 case AArch64::LDRDpre: 2281 case AArch64::LDURQi: 2282 case AArch64::LDRQpre: 2283 case AArch64::LDURWi: 2284 case AArch64::LDRWpre: 2285 case AArch64::LDURXi: 2286 case AArch64::LDRXpre: 2287 case AArch64::LDURSWi: 2288 return true; 2289 } 2290 } 2291 2292 unsigned AArch64InstrInfo::convertToFlagSettingOpc(unsigned Opc, 2293 bool &Is64Bit) { 2294 switch (Opc) { 2295 default: 2296 llvm_unreachable("Opcode has no flag setting equivalent!"); 2297 // 32-bit cases: 2298 case AArch64::ADDWri: 2299 Is64Bit = false; 2300 return AArch64::ADDSWri; 2301 case AArch64::ADDWrr: 2302 Is64Bit = false; 2303 return AArch64::ADDSWrr; 2304 case AArch64::ADDWrs: 2305 Is64Bit = false; 2306 return AArch64::ADDSWrs; 2307 case AArch64::ADDWrx: 2308 Is64Bit = false; 2309 return AArch64::ADDSWrx; 2310 case AArch64::ANDWri: 2311 Is64Bit = false; 2312 return AArch64::ANDSWri; 2313 case AArch64::ANDWrr: 2314 Is64Bit = false; 2315 return AArch64::ANDSWrr; 2316 case AArch64::ANDWrs: 2317 Is64Bit = false; 2318 return AArch64::ANDSWrs; 2319 case AArch64::BICWrr: 2320 Is64Bit = false; 2321 return AArch64::BICSWrr; 2322 case AArch64::BICWrs: 2323 Is64Bit = false; 2324 return AArch64::BICSWrs; 2325 case AArch64::SUBWri: 2326 Is64Bit = false; 2327 return AArch64::SUBSWri; 2328 case AArch64::SUBWrr: 2329 Is64Bit = false; 2330 return AArch64::SUBSWrr; 2331 case AArch64::SUBWrs: 2332 Is64Bit = false; 2333 return AArch64::SUBSWrs; 2334 case AArch64::SUBWrx: 2335 Is64Bit = false; 2336 return AArch64::SUBSWrx; 2337 // 64-bit cases: 2338 case AArch64::ADDXri: 2339 Is64Bit = true; 2340 return AArch64::ADDSXri; 2341 case AArch64::ADDXrr: 2342 Is64Bit = true; 2343 return AArch64::ADDSXrr; 2344 case AArch64::ADDXrs: 2345 Is64Bit = true; 2346 return AArch64::ADDSXrs; 2347 case AArch64::ADDXrx: 2348 Is64Bit = true; 2349 return AArch64::ADDSXrx; 2350 case AArch64::ANDXri: 2351 Is64Bit = true; 2352 return AArch64::ANDSXri; 2353 case AArch64::ANDXrr: 2354 Is64Bit = true; 2355 return AArch64::ANDSXrr; 2356 case AArch64::ANDXrs: 2357 Is64Bit = true; 2358 return AArch64::ANDSXrs; 2359 case AArch64::BICXrr: 2360 Is64Bit = true; 2361 return AArch64::BICSXrr; 2362 case AArch64::BICXrs: 2363 Is64Bit = true; 2364 return AArch64::BICSXrs; 2365 case AArch64::SUBXri: 2366 Is64Bit = true; 2367 return AArch64::SUBSXri; 2368 case AArch64::SUBXrr: 2369 Is64Bit = true; 2370 return AArch64::SUBSXrr; 2371 case AArch64::SUBXrs: 2372 Is64Bit = true; 2373 return AArch64::SUBSXrs; 2374 case AArch64::SUBXrx: 2375 Is64Bit = true; 2376 return AArch64::SUBSXrx; 2377 } 2378 } 2379 2380 // Is this a candidate for ld/st merging or pairing? For example, we don't 2381 // touch volatiles or load/stores that have a hint to avoid pair formation. 2382 bool AArch64InstrInfo::isCandidateToMergeOrPair(const MachineInstr &MI) const { 2383 2384 bool IsPreLdSt = isPreLdSt(MI); 2385 2386 // If this is a volatile load/store, don't mess with it. 2387 if (MI.hasOrderedMemoryRef()) 2388 return false; 2389 2390 // Make sure this is a reg/fi+imm (as opposed to an address reloc). 2391 // For Pre-inc LD/ST, the operand is shifted by one. 2392 assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() || 2393 MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) && 2394 "Expected a reg or frame index operand."); 2395 2396 // For Pre-indexed addressing quadword instructions, the third operand is the 2397 // immediate value. 2398 bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm(); 2399 2400 if (!MI.getOperand(2).isImm() && !IsImmPreLdSt) 2401 return false; 2402 2403 // Can't merge/pair if the instruction modifies the base register. 2404 // e.g., ldr x0, [x0] 2405 // This case will never occur with an FI base. 2406 // However, if the instruction is an LDR/STR<S,D,Q,W,X>pre, it can be merged. 2407 // For example: 2408 // ldr q0, [x11, #32]! 2409 // ldr q1, [x11, #16] 2410 // to 2411 // ldp q0, q1, [x11, #32]! 2412 if (MI.getOperand(1).isReg() && !IsPreLdSt) { 2413 Register BaseReg = MI.getOperand(1).getReg(); 2414 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2415 if (MI.modifiesRegister(BaseReg, TRI)) 2416 return false; 2417 } 2418 2419 // Check if this load/store has a hint to avoid pair formation. 2420 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass. 2421 if (isLdStPairSuppressed(MI)) 2422 return false; 2423 2424 // Do not pair any callee-save store/reload instructions in the 2425 // prologue/epilogue if the CFI information encoded the operations as separate 2426 // instructions, as that will cause the size of the actual prologue to mismatch 2427 // with the prologue size recorded in the Windows CFI. 2428 const MCAsmInfo *MAI = MI.getMF()->getTarget().getMCAsmInfo(); 2429 bool NeedsWinCFI = MAI->usesWindowsCFI() && 2430 MI.getMF()->getFunction().needsUnwindTableEntry(); 2431 if (NeedsWinCFI && (MI.getFlag(MachineInstr::FrameSetup) || 2432 MI.getFlag(MachineInstr::FrameDestroy))) 2433 return false; 2434 2435 // On some CPUs quad load/store pairs are slower than two single load/stores. 2436 if (Subtarget.isPaired128Slow()) { 2437 switch (MI.getOpcode()) { 2438 default: 2439 break; 2440 case AArch64::LDURQi: 2441 case AArch64::STURQi: 2442 case AArch64::LDRQui: 2443 case AArch64::STRQui: 2444 return false; 2445 } 2446 } 2447 2448 return true; 2449 } 2450 2451 bool AArch64InstrInfo::getMemOperandsWithOffsetWidth( 2452 const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps, 2453 int64_t &Offset, bool &OffsetIsScalable, unsigned &Width, 2454 const TargetRegisterInfo *TRI) const { 2455 if (!LdSt.mayLoadOrStore()) 2456 return false; 2457 2458 const MachineOperand *BaseOp; 2459 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable, 2460 Width, TRI)) 2461 return false; 2462 BaseOps.push_back(BaseOp); 2463 return true; 2464 } 2465 2466 Optional<ExtAddrMode> 2467 AArch64InstrInfo::getAddrModeFromMemoryOp(const MachineInstr &MemI, 2468 const TargetRegisterInfo *TRI) const { 2469 const MachineOperand *Base; // Filled with the base operand of MI. 2470 int64_t Offset; // Filled with the offset of MI. 2471 bool OffsetIsScalable; 2472 if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable, TRI)) 2473 return None; 2474 2475 if (!Base->isReg()) 2476 return None; 2477 ExtAddrMode AM; 2478 AM.BaseReg = Base->getReg(); 2479 AM.Displacement = Offset; 2480 AM.ScaledReg = 0; 2481 return AM; 2482 } 2483 2484 bool AArch64InstrInfo::getMemOperandWithOffsetWidth( 2485 const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset, 2486 bool &OffsetIsScalable, unsigned &Width, 2487 const TargetRegisterInfo *TRI) const { 2488 assert(LdSt.mayLoadOrStore() && "Expected a memory operation."); 2489 // Handle only loads/stores with base register followed by immediate offset. 2490 if (LdSt.getNumExplicitOperands() == 3) { 2491 // Non-paired instruction (e.g., ldr x1, [x0, #8]). 2492 if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) || 2493 !LdSt.getOperand(2).isImm()) 2494 return false; 2495 } else if (LdSt.getNumExplicitOperands() == 4) { 2496 // Paired instruction (e.g., ldp x1, x2, [x0, #8]). 2497 if (!LdSt.getOperand(1).isReg() || 2498 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) || 2499 !LdSt.getOperand(3).isImm()) 2500 return false; 2501 } else 2502 return false; 2503 2504 // Get the scaling factor for the instruction and set the width for the 2505 // instruction. 2506 TypeSize Scale(0U, false); 2507 int64_t Dummy1, Dummy2; 2508 2509 // If this returns false, then it's an instruction we don't want to handle. 2510 if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2)) 2511 return false; 2512 2513 // Compute the offset. Offset is calculated as the immediate operand 2514 // multiplied by the scaling factor. Unscaled instructions have scaling factor 2515 // set to 1. 2516 if (LdSt.getNumExplicitOperands() == 3) { 2517 BaseOp = &LdSt.getOperand(1); 2518 Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinSize(); 2519 } else { 2520 assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands"); 2521 BaseOp = &LdSt.getOperand(2); 2522 Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinSize(); 2523 } 2524 OffsetIsScalable = Scale.isScalable(); 2525 2526 if (!BaseOp->isReg() && !BaseOp->isFI()) 2527 return false; 2528 2529 return true; 2530 } 2531 2532 MachineOperand & 2533 AArch64InstrInfo::getMemOpBaseRegImmOfsOffsetOperand(MachineInstr &LdSt) const { 2534 assert(LdSt.mayLoadOrStore() && "Expected a memory operation."); 2535 MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1); 2536 assert(OfsOp.isImm() && "Offset operand wasn't immediate."); 2537 return OfsOp; 2538 } 2539 2540 bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale, 2541 unsigned &Width, int64_t &MinOffset, 2542 int64_t &MaxOffset) { 2543 const unsigned SVEMaxBytesPerVector = AArch64::SVEMaxBitsPerVector / 8; 2544 switch (Opcode) { 2545 // Not a memory operation or something we want to handle. 2546 default: 2547 Scale = TypeSize::Fixed(0); 2548 Width = 0; 2549 MinOffset = MaxOffset = 0; 2550 return false; 2551 case AArch64::STRWpost: 2552 case AArch64::LDRWpost: 2553 Width = 32; 2554 Scale = TypeSize::Fixed(4); 2555 MinOffset = -256; 2556 MaxOffset = 255; 2557 break; 2558 case AArch64::LDURQi: 2559 case AArch64::STURQi: 2560 Width = 16; 2561 Scale = TypeSize::Fixed(1); 2562 MinOffset = -256; 2563 MaxOffset = 255; 2564 break; 2565 case AArch64::PRFUMi: 2566 case AArch64::LDURXi: 2567 case AArch64::LDURDi: 2568 case AArch64::STURXi: 2569 case AArch64::STURDi: 2570 Width = 8; 2571 Scale = TypeSize::Fixed(1); 2572 MinOffset = -256; 2573 MaxOffset = 255; 2574 break; 2575 case AArch64::LDURWi: 2576 case AArch64::LDURSi: 2577 case AArch64::LDURSWi: 2578 case AArch64::STURWi: 2579 case AArch64::STURSi: 2580 Width = 4; 2581 Scale = TypeSize::Fixed(1); 2582 MinOffset = -256; 2583 MaxOffset = 255; 2584 break; 2585 case AArch64::LDURHi: 2586 case AArch64::LDURHHi: 2587 case AArch64::LDURSHXi: 2588 case AArch64::LDURSHWi: 2589 case AArch64::STURHi: 2590 case AArch64::STURHHi: 2591 Width = 2; 2592 Scale = TypeSize::Fixed(1); 2593 MinOffset = -256; 2594 MaxOffset = 255; 2595 break; 2596 case AArch64::LDURBi: 2597 case AArch64::LDURBBi: 2598 case AArch64::LDURSBXi: 2599 case AArch64::LDURSBWi: 2600 case AArch64::STURBi: 2601 case AArch64::STURBBi: 2602 Width = 1; 2603 Scale = TypeSize::Fixed(1); 2604 MinOffset = -256; 2605 MaxOffset = 255; 2606 break; 2607 case AArch64::LDPQi: 2608 case AArch64::LDNPQi: 2609 case AArch64::STPQi: 2610 case AArch64::STNPQi: 2611 Scale = TypeSize::Fixed(16); 2612 Width = 32; 2613 MinOffset = -64; 2614 MaxOffset = 63; 2615 break; 2616 case AArch64::LDRQui: 2617 case AArch64::STRQui: 2618 Scale = TypeSize::Fixed(16); 2619 Width = 16; 2620 MinOffset = 0; 2621 MaxOffset = 4095; 2622 break; 2623 case AArch64::LDPXi: 2624 case AArch64::LDPDi: 2625 case AArch64::LDNPXi: 2626 case AArch64::LDNPDi: 2627 case AArch64::STPXi: 2628 case AArch64::STPDi: 2629 case AArch64::STNPXi: 2630 case AArch64::STNPDi: 2631 Scale = TypeSize::Fixed(8); 2632 Width = 16; 2633 MinOffset = -64; 2634 MaxOffset = 63; 2635 break; 2636 case AArch64::PRFMui: 2637 case AArch64::LDRXui: 2638 case AArch64::LDRDui: 2639 case AArch64::STRXui: 2640 case AArch64::STRDui: 2641 Scale = TypeSize::Fixed(8); 2642 Width = 8; 2643 MinOffset = 0; 2644 MaxOffset = 4095; 2645 break; 2646 case AArch64::StoreSwiftAsyncContext: 2647 // Store is an STRXui, but there might be an ADDXri in the expansion too. 2648 Scale = TypeSize::Fixed(1); 2649 Width = 8; 2650 MinOffset = 0; 2651 MaxOffset = 4095; 2652 break; 2653 case AArch64::LDPWi: 2654 case AArch64::LDPSi: 2655 case AArch64::LDNPWi: 2656 case AArch64::LDNPSi: 2657 case AArch64::STPWi: 2658 case AArch64::STPSi: 2659 case AArch64::STNPWi: 2660 case AArch64::STNPSi: 2661 Scale = TypeSize::Fixed(4); 2662 Width = 8; 2663 MinOffset = -64; 2664 MaxOffset = 63; 2665 break; 2666 case AArch64::LDRWui: 2667 case AArch64::LDRSui: 2668 case AArch64::LDRSWui: 2669 case AArch64::STRWui: 2670 case AArch64::STRSui: 2671 Scale = TypeSize::Fixed(4); 2672 Width = 4; 2673 MinOffset = 0; 2674 MaxOffset = 4095; 2675 break; 2676 case AArch64::LDRHui: 2677 case AArch64::LDRHHui: 2678 case AArch64::LDRSHWui: 2679 case AArch64::LDRSHXui: 2680 case AArch64::STRHui: 2681 case AArch64::STRHHui: 2682 Scale = TypeSize::Fixed(2); 2683 Width = 2; 2684 MinOffset = 0; 2685 MaxOffset = 4095; 2686 break; 2687 case AArch64::LDRBui: 2688 case AArch64::LDRBBui: 2689 case AArch64::LDRSBWui: 2690 case AArch64::LDRSBXui: 2691 case AArch64::STRBui: 2692 case AArch64::STRBBui: 2693 Scale = TypeSize::Fixed(1); 2694 Width = 1; 2695 MinOffset = 0; 2696 MaxOffset = 4095; 2697 break; 2698 case AArch64::ADDG: 2699 Scale = TypeSize::Fixed(16); 2700 Width = 0; 2701 MinOffset = 0; 2702 MaxOffset = 63; 2703 break; 2704 case AArch64::TAGPstack: 2705 Scale = TypeSize::Fixed(16); 2706 Width = 0; 2707 // TAGP with a negative offset turns into SUBP, which has a maximum offset 2708 // of 63 (not 64!). 2709 MinOffset = -63; 2710 MaxOffset = 63; 2711 break; 2712 case AArch64::LDG: 2713 case AArch64::STGOffset: 2714 case AArch64::STZGOffset: 2715 Scale = TypeSize::Fixed(16); 2716 Width = 16; 2717 MinOffset = -256; 2718 MaxOffset = 255; 2719 break; 2720 case AArch64::STR_ZZZZXI: 2721 case AArch64::LDR_ZZZZXI: 2722 Scale = TypeSize::Scalable(16); 2723 Width = SVEMaxBytesPerVector * 4; 2724 MinOffset = -256; 2725 MaxOffset = 252; 2726 break; 2727 case AArch64::STR_ZZZXI: 2728 case AArch64::LDR_ZZZXI: 2729 Scale = TypeSize::Scalable(16); 2730 Width = SVEMaxBytesPerVector * 3; 2731 MinOffset = -256; 2732 MaxOffset = 253; 2733 break; 2734 case AArch64::STR_ZZXI: 2735 case AArch64::LDR_ZZXI: 2736 Scale = TypeSize::Scalable(16); 2737 Width = SVEMaxBytesPerVector * 2; 2738 MinOffset = -256; 2739 MaxOffset = 254; 2740 break; 2741 case AArch64::LDR_PXI: 2742 case AArch64::STR_PXI: 2743 Scale = TypeSize::Scalable(2); 2744 Width = SVEMaxBytesPerVector / 8; 2745 MinOffset = -256; 2746 MaxOffset = 255; 2747 break; 2748 case AArch64::LDR_ZXI: 2749 case AArch64::STR_ZXI: 2750 Scale = TypeSize::Scalable(16); 2751 Width = SVEMaxBytesPerVector; 2752 MinOffset = -256; 2753 MaxOffset = 255; 2754 break; 2755 case AArch64::LD1B_IMM: 2756 case AArch64::LD1H_IMM: 2757 case AArch64::LD1W_IMM: 2758 case AArch64::LD1D_IMM: 2759 case AArch64::ST1B_IMM: 2760 case AArch64::ST1H_IMM: 2761 case AArch64::ST1W_IMM: 2762 case AArch64::ST1D_IMM: 2763 // A full vectors worth of data 2764 // Width = mbytes * elements 2765 Scale = TypeSize::Scalable(16); 2766 Width = SVEMaxBytesPerVector; 2767 MinOffset = -8; 2768 MaxOffset = 7; 2769 break; 2770 case AArch64::LD1B_H_IMM: 2771 case AArch64::LD1SB_H_IMM: 2772 case AArch64::LD1H_S_IMM: 2773 case AArch64::LD1SH_S_IMM: 2774 case AArch64::LD1W_D_IMM: 2775 case AArch64::LD1SW_D_IMM: 2776 case AArch64::ST1B_H_IMM: 2777 case AArch64::ST1H_S_IMM: 2778 case AArch64::ST1W_D_IMM: 2779 // A half vector worth of data 2780 // Width = mbytes * elements 2781 Scale = TypeSize::Scalable(8); 2782 Width = SVEMaxBytesPerVector / 2; 2783 MinOffset = -8; 2784 MaxOffset = 7; 2785 break; 2786 case AArch64::LD1B_S_IMM: 2787 case AArch64::LD1SB_S_IMM: 2788 case AArch64::LD1H_D_IMM: 2789 case AArch64::LD1SH_D_IMM: 2790 case AArch64::ST1B_S_IMM: 2791 case AArch64::ST1H_D_IMM: 2792 // A quarter vector worth of data 2793 // Width = mbytes * elements 2794 Scale = TypeSize::Scalable(4); 2795 Width = SVEMaxBytesPerVector / 4; 2796 MinOffset = -8; 2797 MaxOffset = 7; 2798 break; 2799 case AArch64::LD1B_D_IMM: 2800 case AArch64::LD1SB_D_IMM: 2801 case AArch64::ST1B_D_IMM: 2802 // A eighth vector worth of data 2803 // Width = mbytes * elements 2804 Scale = TypeSize::Scalable(2); 2805 Width = SVEMaxBytesPerVector / 8; 2806 MinOffset = -8; 2807 MaxOffset = 7; 2808 break; 2809 case AArch64::ST2GOffset: 2810 case AArch64::STZ2GOffset: 2811 Scale = TypeSize::Fixed(16); 2812 Width = 32; 2813 MinOffset = -256; 2814 MaxOffset = 255; 2815 break; 2816 case AArch64::STGPi: 2817 Scale = TypeSize::Fixed(16); 2818 Width = 16; 2819 MinOffset = -64; 2820 MaxOffset = 63; 2821 break; 2822 } 2823 2824 return true; 2825 } 2826 2827 // Scaling factor for unscaled load or store. 2828 int AArch64InstrInfo::getMemScale(unsigned Opc) { 2829 switch (Opc) { 2830 default: 2831 llvm_unreachable("Opcode has unknown scale!"); 2832 case AArch64::LDRBBui: 2833 case AArch64::LDURBBi: 2834 case AArch64::LDRSBWui: 2835 case AArch64::LDURSBWi: 2836 case AArch64::STRBBui: 2837 case AArch64::STURBBi: 2838 return 1; 2839 case AArch64::LDRHHui: 2840 case AArch64::LDURHHi: 2841 case AArch64::LDRSHWui: 2842 case AArch64::LDURSHWi: 2843 case AArch64::STRHHui: 2844 case AArch64::STURHHi: 2845 return 2; 2846 case AArch64::LDRSui: 2847 case AArch64::LDURSi: 2848 case AArch64::LDRSpre: 2849 case AArch64::LDRSWui: 2850 case AArch64::LDURSWi: 2851 case AArch64::LDRWpre: 2852 case AArch64::LDRWui: 2853 case AArch64::LDURWi: 2854 case AArch64::STRSui: 2855 case AArch64::STURSi: 2856 case AArch64::STRSpre: 2857 case AArch64::STRWui: 2858 case AArch64::STURWi: 2859 case AArch64::STRWpre: 2860 case AArch64::LDPSi: 2861 case AArch64::LDPSWi: 2862 case AArch64::LDPWi: 2863 case AArch64::STPSi: 2864 case AArch64::STPWi: 2865 return 4; 2866 case AArch64::LDRDui: 2867 case AArch64::LDURDi: 2868 case AArch64::LDRDpre: 2869 case AArch64::LDRXui: 2870 case AArch64::LDURXi: 2871 case AArch64::LDRXpre: 2872 case AArch64::STRDui: 2873 case AArch64::STURDi: 2874 case AArch64::STRDpre: 2875 case AArch64::STRXui: 2876 case AArch64::STURXi: 2877 case AArch64::STRXpre: 2878 case AArch64::LDPDi: 2879 case AArch64::LDPXi: 2880 case AArch64::STPDi: 2881 case AArch64::STPXi: 2882 return 8; 2883 case AArch64::LDRQui: 2884 case AArch64::LDURQi: 2885 case AArch64::STRQui: 2886 case AArch64::STURQi: 2887 case AArch64::STRQpre: 2888 case AArch64::LDPQi: 2889 case AArch64::LDRQpre: 2890 case AArch64::STPQi: 2891 case AArch64::STGOffset: 2892 case AArch64::STZGOffset: 2893 case AArch64::ST2GOffset: 2894 case AArch64::STZ2GOffset: 2895 case AArch64::STGPi: 2896 return 16; 2897 } 2898 } 2899 2900 bool AArch64InstrInfo::isPreLd(const MachineInstr &MI) { 2901 switch (MI.getOpcode()) { 2902 default: 2903 return false; 2904 case AArch64::LDRWpre: 2905 case AArch64::LDRXpre: 2906 case AArch64::LDRSpre: 2907 case AArch64::LDRDpre: 2908 case AArch64::LDRQpre: 2909 return true; 2910 } 2911 } 2912 2913 bool AArch64InstrInfo::isPreSt(const MachineInstr &MI) { 2914 switch (MI.getOpcode()) { 2915 default: 2916 return false; 2917 case AArch64::STRWpre: 2918 case AArch64::STRXpre: 2919 case AArch64::STRSpre: 2920 case AArch64::STRDpre: 2921 case AArch64::STRQpre: 2922 return true; 2923 } 2924 } 2925 2926 bool AArch64InstrInfo::isPreLdSt(const MachineInstr &MI) { 2927 return isPreLd(MI) || isPreSt(MI); 2928 } 2929 2930 // Scale the unscaled offsets. Returns false if the unscaled offset can't be 2931 // scaled. 2932 static bool scaleOffset(unsigned Opc, int64_t &Offset) { 2933 int Scale = AArch64InstrInfo::getMemScale(Opc); 2934 2935 // If the byte-offset isn't a multiple of the stride, we can't scale this 2936 // offset. 2937 if (Offset % Scale != 0) 2938 return false; 2939 2940 // Convert the byte-offset used by unscaled into an "element" offset used 2941 // by the scaled pair load/store instructions. 2942 Offset /= Scale; 2943 return true; 2944 } 2945 2946 static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) { 2947 if (FirstOpc == SecondOpc) 2948 return true; 2949 // We can also pair sign-ext and zero-ext instructions. 2950 switch (FirstOpc) { 2951 default: 2952 return false; 2953 case AArch64::LDRWui: 2954 case AArch64::LDURWi: 2955 return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi; 2956 case AArch64::LDRSWui: 2957 case AArch64::LDURSWi: 2958 return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi; 2959 } 2960 // These instructions can't be paired based on their opcodes. 2961 return false; 2962 } 2963 2964 static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1, 2965 int64_t Offset1, unsigned Opcode1, int FI2, 2966 int64_t Offset2, unsigned Opcode2) { 2967 // Accesses through fixed stack object frame indices may access a different 2968 // fixed stack slot. Check that the object offsets + offsets match. 2969 if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) { 2970 int64_t ObjectOffset1 = MFI.getObjectOffset(FI1); 2971 int64_t ObjectOffset2 = MFI.getObjectOffset(FI2); 2972 assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered."); 2973 // Convert to scaled object offsets. 2974 int Scale1 = AArch64InstrInfo::getMemScale(Opcode1); 2975 if (ObjectOffset1 % Scale1 != 0) 2976 return false; 2977 ObjectOffset1 /= Scale1; 2978 int Scale2 = AArch64InstrInfo::getMemScale(Opcode2); 2979 if (ObjectOffset2 % Scale2 != 0) 2980 return false; 2981 ObjectOffset2 /= Scale2; 2982 ObjectOffset1 += Offset1; 2983 ObjectOffset2 += Offset2; 2984 return ObjectOffset1 + 1 == ObjectOffset2; 2985 } 2986 2987 return FI1 == FI2; 2988 } 2989 2990 /// Detect opportunities for ldp/stp formation. 2991 /// 2992 /// Only called for LdSt for which getMemOperandWithOffset returns true. 2993 bool AArch64InstrInfo::shouldClusterMemOps( 2994 ArrayRef<const MachineOperand *> BaseOps1, 2995 ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads, 2996 unsigned NumBytes) const { 2997 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1); 2998 const MachineOperand &BaseOp1 = *BaseOps1.front(); 2999 const MachineOperand &BaseOp2 = *BaseOps2.front(); 3000 const MachineInstr &FirstLdSt = *BaseOp1.getParent(); 3001 const MachineInstr &SecondLdSt = *BaseOp2.getParent(); 3002 if (BaseOp1.getType() != BaseOp2.getType()) 3003 return false; 3004 3005 assert((BaseOp1.isReg() || BaseOp1.isFI()) && 3006 "Only base registers and frame indices are supported."); 3007 3008 // Check for both base regs and base FI. 3009 if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg()) 3010 return false; 3011 3012 // Only cluster up to a single pair. 3013 if (NumLoads > 2) 3014 return false; 3015 3016 if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt)) 3017 return false; 3018 3019 // Can we pair these instructions based on their opcodes? 3020 unsigned FirstOpc = FirstLdSt.getOpcode(); 3021 unsigned SecondOpc = SecondLdSt.getOpcode(); 3022 if (!canPairLdStOpc(FirstOpc, SecondOpc)) 3023 return false; 3024 3025 // Can't merge volatiles or load/stores that have a hint to avoid pair 3026 // formation, for example. 3027 if (!isCandidateToMergeOrPair(FirstLdSt) || 3028 !isCandidateToMergeOrPair(SecondLdSt)) 3029 return false; 3030 3031 // isCandidateToMergeOrPair guarantees that operand 2 is an immediate. 3032 int64_t Offset1 = FirstLdSt.getOperand(2).getImm(); 3033 if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1)) 3034 return false; 3035 3036 int64_t Offset2 = SecondLdSt.getOperand(2).getImm(); 3037 if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2)) 3038 return false; 3039 3040 // Pairwise instructions have a 7-bit signed offset field. 3041 if (Offset1 > 63 || Offset1 < -64) 3042 return false; 3043 3044 // The caller should already have ordered First/SecondLdSt by offset. 3045 // Note: except for non-equal frame index bases 3046 if (BaseOp1.isFI()) { 3047 assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) && 3048 "Caller should have ordered offsets."); 3049 3050 const MachineFrameInfo &MFI = 3051 FirstLdSt.getParent()->getParent()->getFrameInfo(); 3052 return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc, 3053 BaseOp2.getIndex(), Offset2, SecondOpc); 3054 } 3055 3056 assert(Offset1 <= Offset2 && "Caller should have ordered offsets."); 3057 3058 return Offset1 + 1 == Offset2; 3059 } 3060 3061 static const MachineInstrBuilder &AddSubReg(const MachineInstrBuilder &MIB, 3062 unsigned Reg, unsigned SubIdx, 3063 unsigned State, 3064 const TargetRegisterInfo *TRI) { 3065 if (!SubIdx) 3066 return MIB.addReg(Reg, State); 3067 3068 if (Register::isPhysicalRegister(Reg)) 3069 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State); 3070 return MIB.addReg(Reg, State, SubIdx); 3071 } 3072 3073 static bool forwardCopyWillClobberTuple(unsigned DestReg, unsigned SrcReg, 3074 unsigned NumRegs) { 3075 // We really want the positive remainder mod 32 here, that happens to be 3076 // easily obtainable with a mask. 3077 return ((DestReg - SrcReg) & 0x1f) < NumRegs; 3078 } 3079 3080 void AArch64InstrInfo::copyPhysRegTuple(MachineBasicBlock &MBB, 3081 MachineBasicBlock::iterator I, 3082 const DebugLoc &DL, MCRegister DestReg, 3083 MCRegister SrcReg, bool KillSrc, 3084 unsigned Opcode, 3085 ArrayRef<unsigned> Indices) const { 3086 assert(Subtarget.hasNEON() && "Unexpected register copy without NEON"); 3087 const TargetRegisterInfo *TRI = &getRegisterInfo(); 3088 uint16_t DestEncoding = TRI->getEncodingValue(DestReg); 3089 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg); 3090 unsigned NumRegs = Indices.size(); 3091 3092 int SubReg = 0, End = NumRegs, Incr = 1; 3093 if (forwardCopyWillClobberTuple(DestEncoding, SrcEncoding, NumRegs)) { 3094 SubReg = NumRegs - 1; 3095 End = -1; 3096 Incr = -1; 3097 } 3098 3099 for (; SubReg != End; SubReg += Incr) { 3100 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode)); 3101 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI); 3102 AddSubReg(MIB, SrcReg, Indices[SubReg], 0, TRI); 3103 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI); 3104 } 3105 } 3106 3107 void AArch64InstrInfo::copyGPRRegTuple(MachineBasicBlock &MBB, 3108 MachineBasicBlock::iterator I, 3109 DebugLoc DL, unsigned DestReg, 3110 unsigned SrcReg, bool KillSrc, 3111 unsigned Opcode, unsigned ZeroReg, 3112 llvm::ArrayRef<unsigned> Indices) const { 3113 const TargetRegisterInfo *TRI = &getRegisterInfo(); 3114 unsigned NumRegs = Indices.size(); 3115 3116 #ifndef NDEBUG 3117 uint16_t DestEncoding = TRI->getEncodingValue(DestReg); 3118 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg); 3119 assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 && 3120 "GPR reg sequences should not be able to overlap"); 3121 #endif 3122 3123 for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) { 3124 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode)); 3125 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI); 3126 MIB.addReg(ZeroReg); 3127 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI); 3128 MIB.addImm(0); 3129 } 3130 } 3131 3132 void AArch64InstrInfo::copyPhysReg(MachineBasicBlock &MBB, 3133 MachineBasicBlock::iterator I, 3134 const DebugLoc &DL, MCRegister DestReg, 3135 MCRegister SrcReg, bool KillSrc) const { 3136 if (AArch64::GPR32spRegClass.contains(DestReg) && 3137 (AArch64::GPR32spRegClass.contains(SrcReg) || SrcReg == AArch64::WZR)) { 3138 const TargetRegisterInfo *TRI = &getRegisterInfo(); 3139 3140 if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) { 3141 // If either operand is WSP, expand to ADD #0. 3142 if (Subtarget.hasZeroCycleRegMove()) { 3143 // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move. 3144 MCRegister DestRegX = TRI->getMatchingSuperReg( 3145 DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass); 3146 MCRegister SrcRegX = TRI->getMatchingSuperReg( 3147 SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass); 3148 // This instruction is reading and writing X registers. This may upset 3149 // the register scavenger and machine verifier, so we need to indicate 3150 // that we are reading an undefined value from SrcRegX, but a proper 3151 // value from SrcReg. 3152 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX) 3153 .addReg(SrcRegX, RegState::Undef) 3154 .addImm(0) 3155 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)) 3156 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc)); 3157 } else { 3158 BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg) 3159 .addReg(SrcReg, getKillRegState(KillSrc)) 3160 .addImm(0) 3161 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)); 3162 } 3163 } else if (SrcReg == AArch64::WZR && Subtarget.hasZeroCycleZeroingGP()) { 3164 BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg) 3165 .addImm(0) 3166 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)); 3167 } else { 3168 if (Subtarget.hasZeroCycleRegMove()) { 3169 // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move. 3170 MCRegister DestRegX = TRI->getMatchingSuperReg( 3171 DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass); 3172 MCRegister SrcRegX = TRI->getMatchingSuperReg( 3173 SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass); 3174 // This instruction is reading and writing X registers. This may upset 3175 // the register scavenger and machine verifier, so we need to indicate 3176 // that we are reading an undefined value from SrcRegX, but a proper 3177 // value from SrcReg. 3178 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX) 3179 .addReg(AArch64::XZR) 3180 .addReg(SrcRegX, RegState::Undef) 3181 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc)); 3182 } else { 3183 // Otherwise, expand to ORR WZR. 3184 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg) 3185 .addReg(AArch64::WZR) 3186 .addReg(SrcReg, getKillRegState(KillSrc)); 3187 } 3188 } 3189 return; 3190 } 3191 3192 // Copy a Predicate register by ORRing with itself. 3193 if (AArch64::PPRRegClass.contains(DestReg) && 3194 AArch64::PPRRegClass.contains(SrcReg)) { 3195 assert(Subtarget.hasSVE() && "Unexpected SVE register."); 3196 BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg) 3197 .addReg(SrcReg) // Pg 3198 .addReg(SrcReg) 3199 .addReg(SrcReg, getKillRegState(KillSrc)); 3200 return; 3201 } 3202 3203 // Copy a Z register by ORRing with itself. 3204 if (AArch64::ZPRRegClass.contains(DestReg) && 3205 AArch64::ZPRRegClass.contains(SrcReg)) { 3206 assert(Subtarget.hasSVE() && "Unexpected SVE register."); 3207 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg) 3208 .addReg(SrcReg) 3209 .addReg(SrcReg, getKillRegState(KillSrc)); 3210 return; 3211 } 3212 3213 // Copy a Z register pair by copying the individual sub-registers. 3214 if (AArch64::ZPR2RegClass.contains(DestReg) && 3215 AArch64::ZPR2RegClass.contains(SrcReg)) { 3216 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1}; 3217 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ, 3218 Indices); 3219 return; 3220 } 3221 3222 // Copy a Z register triple by copying the individual sub-registers. 3223 if (AArch64::ZPR3RegClass.contains(DestReg) && 3224 AArch64::ZPR3RegClass.contains(SrcReg)) { 3225 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1, 3226 AArch64::zsub2}; 3227 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ, 3228 Indices); 3229 return; 3230 } 3231 3232 // Copy a Z register quad by copying the individual sub-registers. 3233 if (AArch64::ZPR4RegClass.contains(DestReg) && 3234 AArch64::ZPR4RegClass.contains(SrcReg)) { 3235 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1, 3236 AArch64::zsub2, AArch64::zsub3}; 3237 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ, 3238 Indices); 3239 return; 3240 } 3241 3242 if (AArch64::GPR64spRegClass.contains(DestReg) && 3243 (AArch64::GPR64spRegClass.contains(SrcReg) || SrcReg == AArch64::XZR)) { 3244 if (DestReg == AArch64::SP || SrcReg == AArch64::SP) { 3245 // If either operand is SP, expand to ADD #0. 3246 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg) 3247 .addReg(SrcReg, getKillRegState(KillSrc)) 3248 .addImm(0) 3249 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)); 3250 } else if (SrcReg == AArch64::XZR && Subtarget.hasZeroCycleZeroingGP()) { 3251 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg) 3252 .addImm(0) 3253 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)); 3254 } else { 3255 // Otherwise, expand to ORR XZR. 3256 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg) 3257 .addReg(AArch64::XZR) 3258 .addReg(SrcReg, getKillRegState(KillSrc)); 3259 } 3260 return; 3261 } 3262 3263 // Copy a DDDD register quad by copying the individual sub-registers. 3264 if (AArch64::DDDDRegClass.contains(DestReg) && 3265 AArch64::DDDDRegClass.contains(SrcReg)) { 3266 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1, 3267 AArch64::dsub2, AArch64::dsub3}; 3268 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8, 3269 Indices); 3270 return; 3271 } 3272 3273 // Copy a DDD register triple by copying the individual sub-registers. 3274 if (AArch64::DDDRegClass.contains(DestReg) && 3275 AArch64::DDDRegClass.contains(SrcReg)) { 3276 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1, 3277 AArch64::dsub2}; 3278 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8, 3279 Indices); 3280 return; 3281 } 3282 3283 // Copy a DD register pair by copying the individual sub-registers. 3284 if (AArch64::DDRegClass.contains(DestReg) && 3285 AArch64::DDRegClass.contains(SrcReg)) { 3286 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1}; 3287 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8, 3288 Indices); 3289 return; 3290 } 3291 3292 // Copy a QQQQ register quad by copying the individual sub-registers. 3293 if (AArch64::QQQQRegClass.contains(DestReg) && 3294 AArch64::QQQQRegClass.contains(SrcReg)) { 3295 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1, 3296 AArch64::qsub2, AArch64::qsub3}; 3297 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8, 3298 Indices); 3299 return; 3300 } 3301 3302 // Copy a QQQ register triple by copying the individual sub-registers. 3303 if (AArch64::QQQRegClass.contains(DestReg) && 3304 AArch64::QQQRegClass.contains(SrcReg)) { 3305 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1, 3306 AArch64::qsub2}; 3307 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8, 3308 Indices); 3309 return; 3310 } 3311 3312 // Copy a QQ register pair by copying the individual sub-registers. 3313 if (AArch64::QQRegClass.contains(DestReg) && 3314 AArch64::QQRegClass.contains(SrcReg)) { 3315 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1}; 3316 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8, 3317 Indices); 3318 return; 3319 } 3320 3321 if (AArch64::XSeqPairsClassRegClass.contains(DestReg) && 3322 AArch64::XSeqPairsClassRegClass.contains(SrcReg)) { 3323 static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64}; 3324 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs, 3325 AArch64::XZR, Indices); 3326 return; 3327 } 3328 3329 if (AArch64::WSeqPairsClassRegClass.contains(DestReg) && 3330 AArch64::WSeqPairsClassRegClass.contains(SrcReg)) { 3331 static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32}; 3332 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs, 3333 AArch64::WZR, Indices); 3334 return; 3335 } 3336 3337 if (AArch64::FPR128RegClass.contains(DestReg) && 3338 AArch64::FPR128RegClass.contains(SrcReg)) { 3339 if (Subtarget.hasNEON()) { 3340 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg) 3341 .addReg(SrcReg) 3342 .addReg(SrcReg, getKillRegState(KillSrc)); 3343 } else { 3344 BuildMI(MBB, I, DL, get(AArch64::STRQpre)) 3345 .addReg(AArch64::SP, RegState::Define) 3346 .addReg(SrcReg, getKillRegState(KillSrc)) 3347 .addReg(AArch64::SP) 3348 .addImm(-16); 3349 BuildMI(MBB, I, DL, get(AArch64::LDRQpre)) 3350 .addReg(AArch64::SP, RegState::Define) 3351 .addReg(DestReg, RegState::Define) 3352 .addReg(AArch64::SP) 3353 .addImm(16); 3354 } 3355 return; 3356 } 3357 3358 if (AArch64::FPR64RegClass.contains(DestReg) && 3359 AArch64::FPR64RegClass.contains(SrcReg)) { 3360 if (Subtarget.hasNEON()) { 3361 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::dsub, 3362 &AArch64::FPR128RegClass); 3363 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::dsub, 3364 &AArch64::FPR128RegClass); 3365 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg) 3366 .addReg(SrcReg) 3367 .addReg(SrcReg, getKillRegState(KillSrc)); 3368 } else { 3369 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg) 3370 .addReg(SrcReg, getKillRegState(KillSrc)); 3371 } 3372 return; 3373 } 3374 3375 if (AArch64::FPR32RegClass.contains(DestReg) && 3376 AArch64::FPR32RegClass.contains(SrcReg)) { 3377 if (Subtarget.hasNEON()) { 3378 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::ssub, 3379 &AArch64::FPR128RegClass); 3380 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::ssub, 3381 &AArch64::FPR128RegClass); 3382 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg) 3383 .addReg(SrcReg) 3384 .addReg(SrcReg, getKillRegState(KillSrc)); 3385 } else { 3386 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg) 3387 .addReg(SrcReg, getKillRegState(KillSrc)); 3388 } 3389 return; 3390 } 3391 3392 if (AArch64::FPR16RegClass.contains(DestReg) && 3393 AArch64::FPR16RegClass.contains(SrcReg)) { 3394 if (Subtarget.hasNEON()) { 3395 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub, 3396 &AArch64::FPR128RegClass); 3397 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub, 3398 &AArch64::FPR128RegClass); 3399 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg) 3400 .addReg(SrcReg) 3401 .addReg(SrcReg, getKillRegState(KillSrc)); 3402 } else { 3403 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub, 3404 &AArch64::FPR32RegClass); 3405 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub, 3406 &AArch64::FPR32RegClass); 3407 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg) 3408 .addReg(SrcReg, getKillRegState(KillSrc)); 3409 } 3410 return; 3411 } 3412 3413 if (AArch64::FPR8RegClass.contains(DestReg) && 3414 AArch64::FPR8RegClass.contains(SrcReg)) { 3415 if (Subtarget.hasNEON()) { 3416 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub, 3417 &AArch64::FPR128RegClass); 3418 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub, 3419 &AArch64::FPR128RegClass); 3420 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg) 3421 .addReg(SrcReg) 3422 .addReg(SrcReg, getKillRegState(KillSrc)); 3423 } else { 3424 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub, 3425 &AArch64::FPR32RegClass); 3426 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub, 3427 &AArch64::FPR32RegClass); 3428 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg) 3429 .addReg(SrcReg, getKillRegState(KillSrc)); 3430 } 3431 return; 3432 } 3433 3434 // Copies between GPR64 and FPR64. 3435 if (AArch64::FPR64RegClass.contains(DestReg) && 3436 AArch64::GPR64RegClass.contains(SrcReg)) { 3437 BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg) 3438 .addReg(SrcReg, getKillRegState(KillSrc)); 3439 return; 3440 } 3441 if (AArch64::GPR64RegClass.contains(DestReg) && 3442 AArch64::FPR64RegClass.contains(SrcReg)) { 3443 BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg) 3444 .addReg(SrcReg, getKillRegState(KillSrc)); 3445 return; 3446 } 3447 // Copies between GPR32 and FPR32. 3448 if (AArch64::FPR32RegClass.contains(DestReg) && 3449 AArch64::GPR32RegClass.contains(SrcReg)) { 3450 BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg) 3451 .addReg(SrcReg, getKillRegState(KillSrc)); 3452 return; 3453 } 3454 if (AArch64::GPR32RegClass.contains(DestReg) && 3455 AArch64::FPR32RegClass.contains(SrcReg)) { 3456 BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg) 3457 .addReg(SrcReg, getKillRegState(KillSrc)); 3458 return; 3459 } 3460 3461 if (DestReg == AArch64::NZCV) { 3462 assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy"); 3463 BuildMI(MBB, I, DL, get(AArch64::MSR)) 3464 .addImm(AArch64SysReg::NZCV) 3465 .addReg(SrcReg, getKillRegState(KillSrc)) 3466 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define); 3467 return; 3468 } 3469 3470 if (SrcReg == AArch64::NZCV) { 3471 assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy"); 3472 BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg) 3473 .addImm(AArch64SysReg::NZCV) 3474 .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc)); 3475 return; 3476 } 3477 3478 llvm_unreachable("unimplemented reg-to-reg copy"); 3479 } 3480 3481 static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI, 3482 MachineBasicBlock &MBB, 3483 MachineBasicBlock::iterator InsertBefore, 3484 const MCInstrDesc &MCID, 3485 Register SrcReg, bool IsKill, 3486 unsigned SubIdx0, unsigned SubIdx1, int FI, 3487 MachineMemOperand *MMO) { 3488 Register SrcReg0 = SrcReg; 3489 Register SrcReg1 = SrcReg; 3490 if (Register::isPhysicalRegister(SrcReg)) { 3491 SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0); 3492 SubIdx0 = 0; 3493 SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1); 3494 SubIdx1 = 0; 3495 } 3496 BuildMI(MBB, InsertBefore, DebugLoc(), MCID) 3497 .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0) 3498 .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1) 3499 .addFrameIndex(FI) 3500 .addImm(0) 3501 .addMemOperand(MMO); 3502 } 3503 3504 void AArch64InstrInfo::storeRegToStackSlot( 3505 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, 3506 bool isKill, int FI, const TargetRegisterClass *RC, 3507 const TargetRegisterInfo *TRI) const { 3508 MachineFunction &MF = *MBB.getParent(); 3509 MachineFrameInfo &MFI = MF.getFrameInfo(); 3510 3511 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI); 3512 MachineMemOperand *MMO = 3513 MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore, 3514 MFI.getObjectSize(FI), MFI.getObjectAlign(FI)); 3515 unsigned Opc = 0; 3516 bool Offset = true; 3517 unsigned StackID = TargetStackID::Default; 3518 switch (TRI->getSpillSize(*RC)) { 3519 case 1: 3520 if (AArch64::FPR8RegClass.hasSubClassEq(RC)) 3521 Opc = AArch64::STRBui; 3522 break; 3523 case 2: 3524 if (AArch64::FPR16RegClass.hasSubClassEq(RC)) 3525 Opc = AArch64::STRHui; 3526 else if (AArch64::PPRRegClass.hasSubClassEq(RC)) { 3527 assert(Subtarget.hasSVE() && "Unexpected register store without SVE"); 3528 Opc = AArch64::STR_PXI; 3529 StackID = TargetStackID::ScalableVector; 3530 } 3531 break; 3532 case 4: 3533 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) { 3534 Opc = AArch64::STRWui; 3535 if (Register::isVirtualRegister(SrcReg)) 3536 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass); 3537 else 3538 assert(SrcReg != AArch64::WSP); 3539 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC)) 3540 Opc = AArch64::STRSui; 3541 break; 3542 case 8: 3543 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) { 3544 Opc = AArch64::STRXui; 3545 if (Register::isVirtualRegister(SrcReg)) 3546 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass); 3547 else 3548 assert(SrcReg != AArch64::SP); 3549 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) { 3550 Opc = AArch64::STRDui; 3551 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) { 3552 storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI, 3553 get(AArch64::STPWi), SrcReg, isKill, 3554 AArch64::sube32, AArch64::subo32, FI, MMO); 3555 return; 3556 } 3557 break; 3558 case 16: 3559 if (AArch64::FPR128RegClass.hasSubClassEq(RC)) 3560 Opc = AArch64::STRQui; 3561 else if (AArch64::DDRegClass.hasSubClassEq(RC)) { 3562 assert(Subtarget.hasNEON() && "Unexpected register store without NEON"); 3563 Opc = AArch64::ST1Twov1d; 3564 Offset = false; 3565 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) { 3566 storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI, 3567 get(AArch64::STPXi), SrcReg, isKill, 3568 AArch64::sube64, AArch64::subo64, FI, MMO); 3569 return; 3570 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) { 3571 assert(Subtarget.hasSVE() && "Unexpected register store without SVE"); 3572 Opc = AArch64::STR_ZXI; 3573 StackID = TargetStackID::ScalableVector; 3574 } 3575 break; 3576 case 24: 3577 if (AArch64::DDDRegClass.hasSubClassEq(RC)) { 3578 assert(Subtarget.hasNEON() && "Unexpected register store without NEON"); 3579 Opc = AArch64::ST1Threev1d; 3580 Offset = false; 3581 } 3582 break; 3583 case 32: 3584 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) { 3585 assert(Subtarget.hasNEON() && "Unexpected register store without NEON"); 3586 Opc = AArch64::ST1Fourv1d; 3587 Offset = false; 3588 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) { 3589 assert(Subtarget.hasNEON() && "Unexpected register store without NEON"); 3590 Opc = AArch64::ST1Twov2d; 3591 Offset = false; 3592 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) { 3593 assert(Subtarget.hasSVE() && "Unexpected register store without SVE"); 3594 Opc = AArch64::STR_ZZXI; 3595 StackID = TargetStackID::ScalableVector; 3596 } 3597 break; 3598 case 48: 3599 if (AArch64::QQQRegClass.hasSubClassEq(RC)) { 3600 assert(Subtarget.hasNEON() && "Unexpected register store without NEON"); 3601 Opc = AArch64::ST1Threev2d; 3602 Offset = false; 3603 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) { 3604 assert(Subtarget.hasSVE() && "Unexpected register store without SVE"); 3605 Opc = AArch64::STR_ZZZXI; 3606 StackID = TargetStackID::ScalableVector; 3607 } 3608 break; 3609 case 64: 3610 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) { 3611 assert(Subtarget.hasNEON() && "Unexpected register store without NEON"); 3612 Opc = AArch64::ST1Fourv2d; 3613 Offset = false; 3614 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) { 3615 assert(Subtarget.hasSVE() && "Unexpected register store without SVE"); 3616 Opc = AArch64::STR_ZZZZXI; 3617 StackID = TargetStackID::ScalableVector; 3618 } 3619 break; 3620 } 3621 assert(Opc && "Unknown register class"); 3622 MFI.setStackID(FI, StackID); 3623 3624 const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc)) 3625 .addReg(SrcReg, getKillRegState(isKill)) 3626 .addFrameIndex(FI); 3627 3628 if (Offset) 3629 MI.addImm(0); 3630 MI.addMemOperand(MMO); 3631 } 3632 3633 static void loadRegPairFromStackSlot(const TargetRegisterInfo &TRI, 3634 MachineBasicBlock &MBB, 3635 MachineBasicBlock::iterator InsertBefore, 3636 const MCInstrDesc &MCID, 3637 Register DestReg, unsigned SubIdx0, 3638 unsigned SubIdx1, int FI, 3639 MachineMemOperand *MMO) { 3640 Register DestReg0 = DestReg; 3641 Register DestReg1 = DestReg; 3642 bool IsUndef = true; 3643 if (Register::isPhysicalRegister(DestReg)) { 3644 DestReg0 = TRI.getSubReg(DestReg, SubIdx0); 3645 SubIdx0 = 0; 3646 DestReg1 = TRI.getSubReg(DestReg, SubIdx1); 3647 SubIdx1 = 0; 3648 IsUndef = false; 3649 } 3650 BuildMI(MBB, InsertBefore, DebugLoc(), MCID) 3651 .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0) 3652 .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1) 3653 .addFrameIndex(FI) 3654 .addImm(0) 3655 .addMemOperand(MMO); 3656 } 3657 3658 void AArch64InstrInfo::loadRegFromStackSlot( 3659 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, 3660 int FI, const TargetRegisterClass *RC, 3661 const TargetRegisterInfo *TRI) const { 3662 MachineFunction &MF = *MBB.getParent(); 3663 MachineFrameInfo &MFI = MF.getFrameInfo(); 3664 MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI); 3665 MachineMemOperand *MMO = 3666 MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad, 3667 MFI.getObjectSize(FI), MFI.getObjectAlign(FI)); 3668 3669 unsigned Opc = 0; 3670 bool Offset = true; 3671 unsigned StackID = TargetStackID::Default; 3672 switch (TRI->getSpillSize(*RC)) { 3673 case 1: 3674 if (AArch64::FPR8RegClass.hasSubClassEq(RC)) 3675 Opc = AArch64::LDRBui; 3676 break; 3677 case 2: 3678 if (AArch64::FPR16RegClass.hasSubClassEq(RC)) 3679 Opc = AArch64::LDRHui; 3680 else if (AArch64::PPRRegClass.hasSubClassEq(RC)) { 3681 assert(Subtarget.hasSVE() && "Unexpected register load without SVE"); 3682 Opc = AArch64::LDR_PXI; 3683 StackID = TargetStackID::ScalableVector; 3684 } 3685 break; 3686 case 4: 3687 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) { 3688 Opc = AArch64::LDRWui; 3689 if (Register::isVirtualRegister(DestReg)) 3690 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass); 3691 else 3692 assert(DestReg != AArch64::WSP); 3693 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC)) 3694 Opc = AArch64::LDRSui; 3695 break; 3696 case 8: 3697 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) { 3698 Opc = AArch64::LDRXui; 3699 if (Register::isVirtualRegister(DestReg)) 3700 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass); 3701 else 3702 assert(DestReg != AArch64::SP); 3703 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) { 3704 Opc = AArch64::LDRDui; 3705 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) { 3706 loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI, 3707 get(AArch64::LDPWi), DestReg, AArch64::sube32, 3708 AArch64::subo32, FI, MMO); 3709 return; 3710 } 3711 break; 3712 case 16: 3713 if (AArch64::FPR128RegClass.hasSubClassEq(RC)) 3714 Opc = AArch64::LDRQui; 3715 else if (AArch64::DDRegClass.hasSubClassEq(RC)) { 3716 assert(Subtarget.hasNEON() && "Unexpected register load without NEON"); 3717 Opc = AArch64::LD1Twov1d; 3718 Offset = false; 3719 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) { 3720 loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI, 3721 get(AArch64::LDPXi), DestReg, AArch64::sube64, 3722 AArch64::subo64, FI, MMO); 3723 return; 3724 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) { 3725 assert(Subtarget.hasSVE() && "Unexpected register load without SVE"); 3726 Opc = AArch64::LDR_ZXI; 3727 StackID = TargetStackID::ScalableVector; 3728 } 3729 break; 3730 case 24: 3731 if (AArch64::DDDRegClass.hasSubClassEq(RC)) { 3732 assert(Subtarget.hasNEON() && "Unexpected register load without NEON"); 3733 Opc = AArch64::LD1Threev1d; 3734 Offset = false; 3735 } 3736 break; 3737 case 32: 3738 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) { 3739 assert(Subtarget.hasNEON() && "Unexpected register load without NEON"); 3740 Opc = AArch64::LD1Fourv1d; 3741 Offset = false; 3742 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) { 3743 assert(Subtarget.hasNEON() && "Unexpected register load without NEON"); 3744 Opc = AArch64::LD1Twov2d; 3745 Offset = false; 3746 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) { 3747 assert(Subtarget.hasSVE() && "Unexpected register load without SVE"); 3748 Opc = AArch64::LDR_ZZXI; 3749 StackID = TargetStackID::ScalableVector; 3750 } 3751 break; 3752 case 48: 3753 if (AArch64::QQQRegClass.hasSubClassEq(RC)) { 3754 assert(Subtarget.hasNEON() && "Unexpected register load without NEON"); 3755 Opc = AArch64::LD1Threev2d; 3756 Offset = false; 3757 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) { 3758 assert(Subtarget.hasSVE() && "Unexpected register load without SVE"); 3759 Opc = AArch64::LDR_ZZZXI; 3760 StackID = TargetStackID::ScalableVector; 3761 } 3762 break; 3763 case 64: 3764 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) { 3765 assert(Subtarget.hasNEON() && "Unexpected register load without NEON"); 3766 Opc = AArch64::LD1Fourv2d; 3767 Offset = false; 3768 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) { 3769 assert(Subtarget.hasSVE() && "Unexpected register load without SVE"); 3770 Opc = AArch64::LDR_ZZZZXI; 3771 StackID = TargetStackID::ScalableVector; 3772 } 3773 break; 3774 } 3775 3776 assert(Opc && "Unknown register class"); 3777 MFI.setStackID(FI, StackID); 3778 3779 const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc)) 3780 .addReg(DestReg, getDefRegState(true)) 3781 .addFrameIndex(FI); 3782 if (Offset) 3783 MI.addImm(0); 3784 MI.addMemOperand(MMO); 3785 } 3786 3787 bool llvm::isNZCVTouchedInInstructionRange(const MachineInstr &DefMI, 3788 const MachineInstr &UseMI, 3789 const TargetRegisterInfo *TRI) { 3790 return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()), 3791 UseMI.getIterator()), 3792 [TRI](const MachineInstr &I) { 3793 return I.modifiesRegister(AArch64::NZCV, TRI) || 3794 I.readsRegister(AArch64::NZCV, TRI); 3795 }); 3796 } 3797 3798 void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets( 3799 const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) { 3800 // The smallest scalable element supported by scaled SVE addressing 3801 // modes are predicates, which are 2 scalable bytes in size. So the scalable 3802 // byte offset must always be a multiple of 2. 3803 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset"); 3804 3805 // VGSized offsets are divided by '2', because the VG register is the 3806 // the number of 64bit granules as opposed to 128bit vector chunks, 3807 // which is how the 'n' in e.g. MVT::nxv1i8 is modelled. 3808 // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes. 3809 // VG = n * 2 and the dwarf offset must be VG * 8 bytes. 3810 ByteSized = Offset.getFixed(); 3811 VGSized = Offset.getScalable() / 2; 3812 } 3813 3814 /// Returns the offset in parts to which this frame offset can be 3815 /// decomposed for the purpose of describing a frame offset. 3816 /// For non-scalable offsets this is simply its byte size. 3817 void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets( 3818 const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors, 3819 int64_t &NumDataVectors) { 3820 // The smallest scalable element supported by scaled SVE addressing 3821 // modes are predicates, which are 2 scalable bytes in size. So the scalable 3822 // byte offset must always be a multiple of 2. 3823 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset"); 3824 3825 NumBytes = Offset.getFixed(); 3826 NumDataVectors = 0; 3827 NumPredicateVectors = Offset.getScalable() / 2; 3828 // This method is used to get the offsets to adjust the frame offset. 3829 // If the function requires ADDPL to be used and needs more than two ADDPL 3830 // instructions, part of the offset is folded into NumDataVectors so that it 3831 // uses ADDVL for part of it, reducing the number of ADDPL instructions. 3832 if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 || 3833 NumPredicateVectors > 62) { 3834 NumDataVectors = NumPredicateVectors / 8; 3835 NumPredicateVectors -= NumDataVectors * 8; 3836 } 3837 } 3838 3839 // Helper function to emit a frame offset adjustment from a given 3840 // pointer (SrcReg), stored into DestReg. This function is explicit 3841 // in that it requires the opcode. 3842 static void emitFrameOffsetAdj(MachineBasicBlock &MBB, 3843 MachineBasicBlock::iterator MBBI, 3844 const DebugLoc &DL, unsigned DestReg, 3845 unsigned SrcReg, int64_t Offset, unsigned Opc, 3846 const TargetInstrInfo *TII, 3847 MachineInstr::MIFlag Flag, bool NeedsWinCFI, 3848 bool *HasWinCFI) { 3849 int Sign = 1; 3850 unsigned MaxEncoding, ShiftSize; 3851 switch (Opc) { 3852 case AArch64::ADDXri: 3853 case AArch64::ADDSXri: 3854 case AArch64::SUBXri: 3855 case AArch64::SUBSXri: 3856 MaxEncoding = 0xfff; 3857 ShiftSize = 12; 3858 break; 3859 case AArch64::ADDVL_XXI: 3860 case AArch64::ADDPL_XXI: 3861 MaxEncoding = 31; 3862 ShiftSize = 0; 3863 if (Offset < 0) { 3864 MaxEncoding = 32; 3865 Sign = -1; 3866 Offset = -Offset; 3867 } 3868 break; 3869 default: 3870 llvm_unreachable("Unsupported opcode"); 3871 } 3872 3873 // FIXME: If the offset won't fit in 24-bits, compute the offset into a 3874 // scratch register. If DestReg is a virtual register, use it as the 3875 // scratch register; otherwise, create a new virtual register (to be 3876 // replaced by the scavenger at the end of PEI). That case can be optimized 3877 // slightly if DestReg is SP which is always 16-byte aligned, so the scratch 3878 // register can be loaded with offset%8 and the add/sub can use an extending 3879 // instruction with LSL#3. 3880 // Currently the function handles any offsets but generates a poor sequence 3881 // of code. 3882 // assert(Offset < (1 << 24) && "unimplemented reg plus immediate"); 3883 3884 const unsigned MaxEncodableValue = MaxEncoding << ShiftSize; 3885 Register TmpReg = DestReg; 3886 if (TmpReg == AArch64::XZR) 3887 TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister( 3888 &AArch64::GPR64RegClass); 3889 do { 3890 uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue); 3891 unsigned LocalShiftSize = 0; 3892 if (ThisVal > MaxEncoding) { 3893 ThisVal = ThisVal >> ShiftSize; 3894 LocalShiftSize = ShiftSize; 3895 } 3896 assert((ThisVal >> ShiftSize) <= MaxEncoding && 3897 "Encoding cannot handle value that big"); 3898 3899 Offset -= ThisVal << LocalShiftSize; 3900 if (Offset == 0) 3901 TmpReg = DestReg; 3902 auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg) 3903 .addReg(SrcReg) 3904 .addImm(Sign * (int)ThisVal); 3905 if (ShiftSize) 3906 MBI = MBI.addImm( 3907 AArch64_AM::getShifterImm(AArch64_AM::LSL, LocalShiftSize)); 3908 MBI = MBI.setMIFlag(Flag); 3909 3910 if (NeedsWinCFI) { 3911 assert(Sign == 1 && "SEH directives should always have a positive sign"); 3912 int Imm = (int)(ThisVal << LocalShiftSize); 3913 if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) || 3914 (SrcReg == AArch64::FP && DestReg == AArch64::SP)) { 3915 if (HasWinCFI) 3916 *HasWinCFI = true; 3917 if (Imm == 0) 3918 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag); 3919 else 3920 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP)) 3921 .addImm(Imm) 3922 .setMIFlag(Flag); 3923 assert(Offset == 0 && "Expected remaining offset to be zero to " 3924 "emit a single SEH directive"); 3925 } else if (DestReg == AArch64::SP) { 3926 if (HasWinCFI) 3927 *HasWinCFI = true; 3928 assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc"); 3929 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc)) 3930 .addImm(Imm) 3931 .setMIFlag(Flag); 3932 } 3933 if (HasWinCFI) 3934 *HasWinCFI = true; 3935 } 3936 3937 SrcReg = TmpReg; 3938 } while (Offset); 3939 } 3940 3941 void llvm::emitFrameOffset(MachineBasicBlock &MBB, 3942 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, 3943 unsigned DestReg, unsigned SrcReg, 3944 StackOffset Offset, const TargetInstrInfo *TII, 3945 MachineInstr::MIFlag Flag, bool SetNZCV, 3946 bool NeedsWinCFI, bool *HasWinCFI) { 3947 int64_t Bytes, NumPredicateVectors, NumDataVectors; 3948 AArch64InstrInfo::decomposeStackOffsetForFrameOffsets( 3949 Offset, Bytes, NumPredicateVectors, NumDataVectors); 3950 3951 // First emit non-scalable frame offsets, or a simple 'mov'. 3952 if (Bytes || (!Offset && SrcReg != DestReg)) { 3953 assert((DestReg != AArch64::SP || Bytes % 8 == 0) && 3954 "SP increment/decrement not 8-byte aligned"); 3955 unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri; 3956 if (Bytes < 0) { 3957 Bytes = -Bytes; 3958 Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri; 3959 } 3960 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag, 3961 NeedsWinCFI, HasWinCFI); 3962 SrcReg = DestReg; 3963 } 3964 3965 assert(!(SetNZCV && (NumPredicateVectors || NumDataVectors)) && 3966 "SetNZCV not supported with SVE vectors"); 3967 assert(!(NeedsWinCFI && (NumPredicateVectors || NumDataVectors)) && 3968 "WinCFI not supported with SVE vectors"); 3969 3970 if (NumDataVectors) { 3971 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors, 3972 AArch64::ADDVL_XXI, TII, Flag, NeedsWinCFI, nullptr); 3973 SrcReg = DestReg; 3974 } 3975 3976 if (NumPredicateVectors) { 3977 assert(DestReg != AArch64::SP && "Unaligned access to SP"); 3978 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors, 3979 AArch64::ADDPL_XXI, TII, Flag, NeedsWinCFI, nullptr); 3980 } 3981 } 3982 3983 MachineInstr *AArch64InstrInfo::foldMemoryOperandImpl( 3984 MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops, 3985 MachineBasicBlock::iterator InsertPt, int FrameIndex, 3986 LiveIntervals *LIS, VirtRegMap *VRM) const { 3987 // This is a bit of a hack. Consider this instruction: 3988 // 3989 // %0 = COPY %sp; GPR64all:%0 3990 // 3991 // We explicitly chose GPR64all for the virtual register so such a copy might 3992 // be eliminated by RegisterCoalescer. However, that may not be possible, and 3993 // %0 may even spill. We can't spill %sp, and since it is in the GPR64all 3994 // register class, TargetInstrInfo::foldMemoryOperand() is going to try. 3995 // 3996 // To prevent that, we are going to constrain the %0 register class here. 3997 // 3998 // <rdar://problem/11522048> 3999 // 4000 if (MI.isFullCopy()) { 4001 Register DstReg = MI.getOperand(0).getReg(); 4002 Register SrcReg = MI.getOperand(1).getReg(); 4003 if (SrcReg == AArch64::SP && Register::isVirtualRegister(DstReg)) { 4004 MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass); 4005 return nullptr; 4006 } 4007 if (DstReg == AArch64::SP && Register::isVirtualRegister(SrcReg)) { 4008 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass); 4009 return nullptr; 4010 } 4011 } 4012 4013 // Handle the case where a copy is being spilled or filled but the source 4014 // and destination register class don't match. For example: 4015 // 4016 // %0 = COPY %xzr; GPR64common:%0 4017 // 4018 // In this case we can still safely fold away the COPY and generate the 4019 // following spill code: 4020 // 4021 // STRXui %xzr, %stack.0 4022 // 4023 // This also eliminates spilled cross register class COPYs (e.g. between x and 4024 // d regs) of the same size. For example: 4025 // 4026 // %0 = COPY %1; GPR64:%0, FPR64:%1 4027 // 4028 // will be filled as 4029 // 4030 // LDRDui %0, fi<#0> 4031 // 4032 // instead of 4033 // 4034 // LDRXui %Temp, fi<#0> 4035 // %0 = FMOV %Temp 4036 // 4037 if (MI.isCopy() && Ops.size() == 1 && 4038 // Make sure we're only folding the explicit COPY defs/uses. 4039 (Ops[0] == 0 || Ops[0] == 1)) { 4040 bool IsSpill = Ops[0] == 0; 4041 bool IsFill = !IsSpill; 4042 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 4043 const MachineRegisterInfo &MRI = MF.getRegInfo(); 4044 MachineBasicBlock &MBB = *MI.getParent(); 4045 const MachineOperand &DstMO = MI.getOperand(0); 4046 const MachineOperand &SrcMO = MI.getOperand(1); 4047 Register DstReg = DstMO.getReg(); 4048 Register SrcReg = SrcMO.getReg(); 4049 // This is slightly expensive to compute for physical regs since 4050 // getMinimalPhysRegClass is slow. 4051 auto getRegClass = [&](unsigned Reg) { 4052 return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg) 4053 : TRI.getMinimalPhysRegClass(Reg); 4054 }; 4055 4056 if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) { 4057 assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) == 4058 TRI.getRegSizeInBits(*getRegClass(SrcReg)) && 4059 "Mismatched register size in non subreg COPY"); 4060 if (IsSpill) 4061 storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex, 4062 getRegClass(SrcReg), &TRI); 4063 else 4064 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, 4065 getRegClass(DstReg), &TRI); 4066 return &*--InsertPt; 4067 } 4068 4069 // Handle cases like spilling def of: 4070 // 4071 // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0 4072 // 4073 // where the physical register source can be widened and stored to the full 4074 // virtual reg destination stack slot, in this case producing: 4075 // 4076 // STRXui %xzr, %stack.0 4077 // 4078 if (IsSpill && DstMO.isUndef() && Register::isPhysicalRegister(SrcReg)) { 4079 assert(SrcMO.getSubReg() == 0 && 4080 "Unexpected subreg on physical register"); 4081 const TargetRegisterClass *SpillRC; 4082 unsigned SpillSubreg; 4083 switch (DstMO.getSubReg()) { 4084 default: 4085 SpillRC = nullptr; 4086 break; 4087 case AArch64::sub_32: 4088 case AArch64::ssub: 4089 if (AArch64::GPR32RegClass.contains(SrcReg)) { 4090 SpillRC = &AArch64::GPR64RegClass; 4091 SpillSubreg = AArch64::sub_32; 4092 } else if (AArch64::FPR32RegClass.contains(SrcReg)) { 4093 SpillRC = &AArch64::FPR64RegClass; 4094 SpillSubreg = AArch64::ssub; 4095 } else 4096 SpillRC = nullptr; 4097 break; 4098 case AArch64::dsub: 4099 if (AArch64::FPR64RegClass.contains(SrcReg)) { 4100 SpillRC = &AArch64::FPR128RegClass; 4101 SpillSubreg = AArch64::dsub; 4102 } else 4103 SpillRC = nullptr; 4104 break; 4105 } 4106 4107 if (SpillRC) 4108 if (unsigned WidenedSrcReg = 4109 TRI.getMatchingSuperReg(SrcReg, SpillSubreg, SpillRC)) { 4110 storeRegToStackSlot(MBB, InsertPt, WidenedSrcReg, SrcMO.isKill(), 4111 FrameIndex, SpillRC, &TRI); 4112 return &*--InsertPt; 4113 } 4114 } 4115 4116 // Handle cases like filling use of: 4117 // 4118 // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1 4119 // 4120 // where we can load the full virtual reg source stack slot, into the subreg 4121 // destination, in this case producing: 4122 // 4123 // LDRWui %0:sub_32<def,read-undef>, %stack.0 4124 // 4125 if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) { 4126 const TargetRegisterClass *FillRC; 4127 switch (DstMO.getSubReg()) { 4128 default: 4129 FillRC = nullptr; 4130 break; 4131 case AArch64::sub_32: 4132 FillRC = &AArch64::GPR32RegClass; 4133 break; 4134 case AArch64::ssub: 4135 FillRC = &AArch64::FPR32RegClass; 4136 break; 4137 case AArch64::dsub: 4138 FillRC = &AArch64::FPR64RegClass; 4139 break; 4140 } 4141 4142 if (FillRC) { 4143 assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) == 4144 TRI.getRegSizeInBits(*FillRC) && 4145 "Mismatched regclass size on folded subreg COPY"); 4146 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC, &TRI); 4147 MachineInstr &LoadMI = *--InsertPt; 4148 MachineOperand &LoadDst = LoadMI.getOperand(0); 4149 assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load"); 4150 LoadDst.setSubReg(DstMO.getSubReg()); 4151 LoadDst.setIsUndef(); 4152 return &LoadMI; 4153 } 4154 } 4155 } 4156 4157 // Cannot fold. 4158 return nullptr; 4159 } 4160 4161 int llvm::isAArch64FrameOffsetLegal(const MachineInstr &MI, 4162 StackOffset &SOffset, 4163 bool *OutUseUnscaledOp, 4164 unsigned *OutUnscaledOp, 4165 int64_t *EmittableOffset) { 4166 // Set output values in case of early exit. 4167 if (EmittableOffset) 4168 *EmittableOffset = 0; 4169 if (OutUseUnscaledOp) 4170 *OutUseUnscaledOp = false; 4171 if (OutUnscaledOp) 4172 *OutUnscaledOp = 0; 4173 4174 // Exit early for structured vector spills/fills as they can't take an 4175 // immediate offset. 4176 switch (MI.getOpcode()) { 4177 default: 4178 break; 4179 case AArch64::LD1Twov2d: 4180 case AArch64::LD1Threev2d: 4181 case AArch64::LD1Fourv2d: 4182 case AArch64::LD1Twov1d: 4183 case AArch64::LD1Threev1d: 4184 case AArch64::LD1Fourv1d: 4185 case AArch64::ST1Twov2d: 4186 case AArch64::ST1Threev2d: 4187 case AArch64::ST1Fourv2d: 4188 case AArch64::ST1Twov1d: 4189 case AArch64::ST1Threev1d: 4190 case AArch64::ST1Fourv1d: 4191 case AArch64::IRG: 4192 case AArch64::IRGstack: 4193 case AArch64::STGloop: 4194 case AArch64::STZGloop: 4195 return AArch64FrameOffsetCannotUpdate; 4196 } 4197 4198 // Get the min/max offset and the scale. 4199 TypeSize ScaleValue(0U, false); 4200 unsigned Width; 4201 int64_t MinOff, MaxOff; 4202 if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff, 4203 MaxOff)) 4204 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal"); 4205 4206 // Construct the complete offset. 4207 bool IsMulVL = ScaleValue.isScalable(); 4208 unsigned Scale = ScaleValue.getKnownMinSize(); 4209 int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed(); 4210 4211 const MachineOperand &ImmOpnd = 4212 MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode())); 4213 Offset += ImmOpnd.getImm() * Scale; 4214 4215 // If the offset doesn't match the scale, we rewrite the instruction to 4216 // use the unscaled instruction instead. Likewise, if we have a negative 4217 // offset and there is an unscaled op to use. 4218 Optional<unsigned> UnscaledOp = 4219 AArch64InstrInfo::getUnscaledLdSt(MI.getOpcode()); 4220 bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0); 4221 if (useUnscaledOp && 4222 !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff, 4223 MaxOff)) 4224 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal"); 4225 4226 Scale = ScaleValue.getKnownMinSize(); 4227 assert(IsMulVL == ScaleValue.isScalable() && 4228 "Unscaled opcode has different value for scalable"); 4229 4230 int64_t Remainder = Offset % Scale; 4231 assert(!(Remainder && useUnscaledOp) && 4232 "Cannot have remainder when using unscaled op"); 4233 4234 assert(MinOff < MaxOff && "Unexpected Min/Max offsets"); 4235 int64_t NewOffset = Offset / Scale; 4236 if (MinOff <= NewOffset && NewOffset <= MaxOff) 4237 Offset = Remainder; 4238 else { 4239 NewOffset = NewOffset < 0 ? MinOff : MaxOff; 4240 Offset = Offset - NewOffset * Scale + Remainder; 4241 } 4242 4243 if (EmittableOffset) 4244 *EmittableOffset = NewOffset; 4245 if (OutUseUnscaledOp) 4246 *OutUseUnscaledOp = useUnscaledOp; 4247 if (OutUnscaledOp && UnscaledOp) 4248 *OutUnscaledOp = *UnscaledOp; 4249 4250 if (IsMulVL) 4251 SOffset = StackOffset::get(SOffset.getFixed(), Offset); 4252 else 4253 SOffset = StackOffset::get(Offset, SOffset.getScalable()); 4254 return AArch64FrameOffsetCanUpdate | 4255 (SOffset ? 0 : AArch64FrameOffsetIsLegal); 4256 } 4257 4258 bool llvm::rewriteAArch64FrameIndex(MachineInstr &MI, unsigned FrameRegIdx, 4259 unsigned FrameReg, StackOffset &Offset, 4260 const AArch64InstrInfo *TII) { 4261 unsigned Opcode = MI.getOpcode(); 4262 unsigned ImmIdx = FrameRegIdx + 1; 4263 4264 if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) { 4265 Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm()); 4266 emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(), 4267 MI.getOperand(0).getReg(), FrameReg, Offset, TII, 4268 MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri)); 4269 MI.eraseFromParent(); 4270 Offset = StackOffset(); 4271 return true; 4272 } 4273 4274 int64_t NewOffset; 4275 unsigned UnscaledOp; 4276 bool UseUnscaledOp; 4277 int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp, 4278 &UnscaledOp, &NewOffset); 4279 if (Status & AArch64FrameOffsetCanUpdate) { 4280 if (Status & AArch64FrameOffsetIsLegal) 4281 // Replace the FrameIndex with FrameReg. 4282 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false); 4283 if (UseUnscaledOp) 4284 MI.setDesc(TII->get(UnscaledOp)); 4285 4286 MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset); 4287 return !Offset; 4288 } 4289 4290 return false; 4291 } 4292 4293 MCInst AArch64InstrInfo::getNop() const { 4294 return MCInstBuilder(AArch64::HINT).addImm(0); 4295 } 4296 4297 // AArch64 supports MachineCombiner. 4298 bool AArch64InstrInfo::useMachineCombiner() const { return true; } 4299 4300 // True when Opc sets flag 4301 static bool isCombineInstrSettingFlag(unsigned Opc) { 4302 switch (Opc) { 4303 case AArch64::ADDSWrr: 4304 case AArch64::ADDSWri: 4305 case AArch64::ADDSXrr: 4306 case AArch64::ADDSXri: 4307 case AArch64::SUBSWrr: 4308 case AArch64::SUBSXrr: 4309 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi. 4310 case AArch64::SUBSWri: 4311 case AArch64::SUBSXri: 4312 return true; 4313 default: 4314 break; 4315 } 4316 return false; 4317 } 4318 4319 // 32b Opcodes that can be combined with a MUL 4320 static bool isCombineInstrCandidate32(unsigned Opc) { 4321 switch (Opc) { 4322 case AArch64::ADDWrr: 4323 case AArch64::ADDWri: 4324 case AArch64::SUBWrr: 4325 case AArch64::ADDSWrr: 4326 case AArch64::ADDSWri: 4327 case AArch64::SUBSWrr: 4328 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi. 4329 case AArch64::SUBWri: 4330 case AArch64::SUBSWri: 4331 return true; 4332 default: 4333 break; 4334 } 4335 return false; 4336 } 4337 4338 // 64b Opcodes that can be combined with a MUL 4339 static bool isCombineInstrCandidate64(unsigned Opc) { 4340 switch (Opc) { 4341 case AArch64::ADDXrr: 4342 case AArch64::ADDXri: 4343 case AArch64::SUBXrr: 4344 case AArch64::ADDSXrr: 4345 case AArch64::ADDSXri: 4346 case AArch64::SUBSXrr: 4347 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi. 4348 case AArch64::SUBXri: 4349 case AArch64::SUBSXri: 4350 case AArch64::ADDv8i8: 4351 case AArch64::ADDv16i8: 4352 case AArch64::ADDv4i16: 4353 case AArch64::ADDv8i16: 4354 case AArch64::ADDv2i32: 4355 case AArch64::ADDv4i32: 4356 case AArch64::SUBv8i8: 4357 case AArch64::SUBv16i8: 4358 case AArch64::SUBv4i16: 4359 case AArch64::SUBv8i16: 4360 case AArch64::SUBv2i32: 4361 case AArch64::SUBv4i32: 4362 return true; 4363 default: 4364 break; 4365 } 4366 return false; 4367 } 4368 4369 // FP Opcodes that can be combined with a FMUL. 4370 static bool isCombineInstrCandidateFP(const MachineInstr &Inst) { 4371 switch (Inst.getOpcode()) { 4372 default: 4373 break; 4374 case AArch64::FADDHrr: 4375 case AArch64::FADDSrr: 4376 case AArch64::FADDDrr: 4377 case AArch64::FADDv4f16: 4378 case AArch64::FADDv8f16: 4379 case AArch64::FADDv2f32: 4380 case AArch64::FADDv2f64: 4381 case AArch64::FADDv4f32: 4382 case AArch64::FSUBHrr: 4383 case AArch64::FSUBSrr: 4384 case AArch64::FSUBDrr: 4385 case AArch64::FSUBv4f16: 4386 case AArch64::FSUBv8f16: 4387 case AArch64::FSUBv2f32: 4388 case AArch64::FSUBv2f64: 4389 case AArch64::FSUBv4f32: 4390 TargetOptions Options = Inst.getParent()->getParent()->getTarget().Options; 4391 // We can fuse FADD/FSUB with FMUL, if fusion is either allowed globally by 4392 // the target options or if FADD/FSUB has the contract fast-math flag. 4393 return Options.UnsafeFPMath || 4394 Options.AllowFPOpFusion == FPOpFusion::Fast || 4395 Inst.getFlag(MachineInstr::FmContract); 4396 return true; 4397 } 4398 return false; 4399 } 4400 4401 // Opcodes that can be combined with a MUL 4402 static bool isCombineInstrCandidate(unsigned Opc) { 4403 return (isCombineInstrCandidate32(Opc) || isCombineInstrCandidate64(Opc)); 4404 } 4405 4406 // 4407 // Utility routine that checks if \param MO is defined by an 4408 // \param CombineOpc instruction in the basic block \param MBB 4409 static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, 4410 unsigned CombineOpc, unsigned ZeroReg = 0, 4411 bool CheckZeroReg = false) { 4412 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 4413 MachineInstr *MI = nullptr; 4414 4415 if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) 4416 MI = MRI.getUniqueVRegDef(MO.getReg()); 4417 // And it needs to be in the trace (otherwise, it won't have a depth). 4418 if (!MI || MI->getParent() != &MBB || (unsigned)MI->getOpcode() != CombineOpc) 4419 return false; 4420 // Must only used by the user we combine with. 4421 if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg())) 4422 return false; 4423 4424 if (CheckZeroReg) { 4425 assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() && 4426 MI->getOperand(1).isReg() && MI->getOperand(2).isReg() && 4427 MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs"); 4428 // The third input reg must be zero. 4429 if (MI->getOperand(3).getReg() != ZeroReg) 4430 return false; 4431 } 4432 4433 return true; 4434 } 4435 4436 // 4437 // Is \param MO defined by an integer multiply and can be combined? 4438 static bool canCombineWithMUL(MachineBasicBlock &MBB, MachineOperand &MO, 4439 unsigned MulOpc, unsigned ZeroReg) { 4440 return canCombine(MBB, MO, MulOpc, ZeroReg, true); 4441 } 4442 4443 // 4444 // Is \param MO defined by a floating-point multiply and can be combined? 4445 static bool canCombineWithFMUL(MachineBasicBlock &MBB, MachineOperand &MO, 4446 unsigned MulOpc) { 4447 return canCombine(MBB, MO, MulOpc); 4448 } 4449 4450 // TODO: There are many more machine instruction opcodes to match: 4451 // 1. Other data types (integer, vectors) 4452 // 2. Other math / logic operations (xor, or) 4453 // 3. Other forms of the same operation (intrinsics and other variants) 4454 bool AArch64InstrInfo::isAssociativeAndCommutative( 4455 const MachineInstr &Inst) const { 4456 switch (Inst.getOpcode()) { 4457 case AArch64::FADDDrr: 4458 case AArch64::FADDSrr: 4459 case AArch64::FADDv2f32: 4460 case AArch64::FADDv2f64: 4461 case AArch64::FADDv4f32: 4462 case AArch64::FMULDrr: 4463 case AArch64::FMULSrr: 4464 case AArch64::FMULX32: 4465 case AArch64::FMULX64: 4466 case AArch64::FMULXv2f32: 4467 case AArch64::FMULXv2f64: 4468 case AArch64::FMULXv4f32: 4469 case AArch64::FMULv2f32: 4470 case AArch64::FMULv2f64: 4471 case AArch64::FMULv4f32: 4472 return Inst.getParent()->getParent()->getTarget().Options.UnsafeFPMath; 4473 default: 4474 return false; 4475 } 4476 } 4477 4478 /// Find instructions that can be turned into madd. 4479 static bool getMaddPatterns(MachineInstr &Root, 4480 SmallVectorImpl<MachineCombinerPattern> &Patterns) { 4481 unsigned Opc = Root.getOpcode(); 4482 MachineBasicBlock &MBB = *Root.getParent(); 4483 bool Found = false; 4484 4485 if (!isCombineInstrCandidate(Opc)) 4486 return false; 4487 if (isCombineInstrSettingFlag(Opc)) { 4488 int Cmp_NZCV = Root.findRegisterDefOperandIdx(AArch64::NZCV, true); 4489 // When NZCV is live bail out. 4490 if (Cmp_NZCV == -1) 4491 return false; 4492 unsigned NewOpc = convertToNonFlagSettingOpc(Root); 4493 // When opcode can't change bail out. 4494 // CHECKME: do we miss any cases for opcode conversion? 4495 if (NewOpc == Opc) 4496 return false; 4497 Opc = NewOpc; 4498 } 4499 4500 auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg, 4501 MachineCombinerPattern Pattern) { 4502 if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) { 4503 Patterns.push_back(Pattern); 4504 Found = true; 4505 } 4506 }; 4507 4508 auto setVFound = [&](int Opcode, int Operand, MachineCombinerPattern Pattern) { 4509 if (canCombine(MBB, Root.getOperand(Operand), Opcode)) { 4510 Patterns.push_back(Pattern); 4511 Found = true; 4512 } 4513 }; 4514 4515 typedef MachineCombinerPattern MCP; 4516 4517 switch (Opc) { 4518 default: 4519 break; 4520 case AArch64::ADDWrr: 4521 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() && 4522 "ADDWrr does not have register operands"); 4523 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1); 4524 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2); 4525 break; 4526 case AArch64::ADDXrr: 4527 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1); 4528 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2); 4529 break; 4530 case AArch64::SUBWrr: 4531 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1); 4532 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2); 4533 break; 4534 case AArch64::SUBXrr: 4535 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1); 4536 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2); 4537 break; 4538 case AArch64::ADDWri: 4539 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1); 4540 break; 4541 case AArch64::ADDXri: 4542 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1); 4543 break; 4544 case AArch64::SUBWri: 4545 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1); 4546 break; 4547 case AArch64::SUBXri: 4548 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1); 4549 break; 4550 case AArch64::ADDv8i8: 4551 setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1); 4552 setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2); 4553 break; 4554 case AArch64::ADDv16i8: 4555 setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1); 4556 setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2); 4557 break; 4558 case AArch64::ADDv4i16: 4559 setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1); 4560 setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2); 4561 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1); 4562 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2); 4563 break; 4564 case AArch64::ADDv8i16: 4565 setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1); 4566 setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2); 4567 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1); 4568 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2); 4569 break; 4570 case AArch64::ADDv2i32: 4571 setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1); 4572 setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2); 4573 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1); 4574 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2); 4575 break; 4576 case AArch64::ADDv4i32: 4577 setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1); 4578 setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2); 4579 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1); 4580 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2); 4581 break; 4582 case AArch64::SUBv8i8: 4583 setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1); 4584 setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2); 4585 break; 4586 case AArch64::SUBv16i8: 4587 setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1); 4588 setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2); 4589 break; 4590 case AArch64::SUBv4i16: 4591 setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1); 4592 setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2); 4593 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1); 4594 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2); 4595 break; 4596 case AArch64::SUBv8i16: 4597 setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1); 4598 setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2); 4599 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1); 4600 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2); 4601 break; 4602 case AArch64::SUBv2i32: 4603 setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1); 4604 setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2); 4605 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1); 4606 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2); 4607 break; 4608 case AArch64::SUBv4i32: 4609 setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1); 4610 setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2); 4611 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1); 4612 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2); 4613 break; 4614 } 4615 return Found; 4616 } 4617 /// Floating-Point Support 4618 4619 /// Find instructions that can be turned into madd. 4620 static bool getFMAPatterns(MachineInstr &Root, 4621 SmallVectorImpl<MachineCombinerPattern> &Patterns) { 4622 4623 if (!isCombineInstrCandidateFP(Root)) 4624 return false; 4625 4626 MachineBasicBlock &MBB = *Root.getParent(); 4627 bool Found = false; 4628 4629 auto Match = [&](int Opcode, int Operand, 4630 MachineCombinerPattern Pattern) -> bool { 4631 if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) { 4632 Patterns.push_back(Pattern); 4633 return true; 4634 } 4635 return false; 4636 }; 4637 4638 typedef MachineCombinerPattern MCP; 4639 4640 switch (Root.getOpcode()) { 4641 default: 4642 assert(false && "Unsupported FP instruction in combiner\n"); 4643 break; 4644 case AArch64::FADDHrr: 4645 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() && 4646 "FADDHrr does not have register operands"); 4647 4648 Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1); 4649 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2); 4650 break; 4651 case AArch64::FADDSrr: 4652 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() && 4653 "FADDSrr does not have register operands"); 4654 4655 Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) || 4656 Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1); 4657 4658 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) || 4659 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2); 4660 break; 4661 case AArch64::FADDDrr: 4662 Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) || 4663 Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1); 4664 4665 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) || 4666 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2); 4667 break; 4668 case AArch64::FADDv4f16: 4669 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) || 4670 Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1); 4671 4672 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) || 4673 Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2); 4674 break; 4675 case AArch64::FADDv8f16: 4676 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) || 4677 Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1); 4678 4679 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) || 4680 Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2); 4681 break; 4682 case AArch64::FADDv2f32: 4683 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) || 4684 Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1); 4685 4686 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) || 4687 Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2); 4688 break; 4689 case AArch64::FADDv2f64: 4690 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) || 4691 Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1); 4692 4693 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) || 4694 Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2); 4695 break; 4696 case AArch64::FADDv4f32: 4697 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) || 4698 Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1); 4699 4700 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) || 4701 Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2); 4702 break; 4703 case AArch64::FSUBHrr: 4704 Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1); 4705 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2); 4706 Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1); 4707 break; 4708 case AArch64::FSUBSrr: 4709 Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1); 4710 4711 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) || 4712 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2); 4713 4714 Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1); 4715 break; 4716 case AArch64::FSUBDrr: 4717 Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1); 4718 4719 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) || 4720 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2); 4721 4722 Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1); 4723 break; 4724 case AArch64::FSUBv4f16: 4725 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) || 4726 Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2); 4727 4728 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) || 4729 Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1); 4730 break; 4731 case AArch64::FSUBv8f16: 4732 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) || 4733 Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2); 4734 4735 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) || 4736 Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1); 4737 break; 4738 case AArch64::FSUBv2f32: 4739 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) || 4740 Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2); 4741 4742 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) || 4743 Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1); 4744 break; 4745 case AArch64::FSUBv2f64: 4746 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) || 4747 Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2); 4748 4749 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) || 4750 Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1); 4751 break; 4752 case AArch64::FSUBv4f32: 4753 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) || 4754 Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2); 4755 4756 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) || 4757 Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1); 4758 break; 4759 } 4760 return Found; 4761 } 4762 4763 /// Return true when a code sequence can improve throughput. It 4764 /// should be called only for instructions in loops. 4765 /// \param Pattern - combiner pattern 4766 bool AArch64InstrInfo::isThroughputPattern( 4767 MachineCombinerPattern Pattern) const { 4768 switch (Pattern) { 4769 default: 4770 break; 4771 case MachineCombinerPattern::FMULADDH_OP1: 4772 case MachineCombinerPattern::FMULADDH_OP2: 4773 case MachineCombinerPattern::FMULSUBH_OP1: 4774 case MachineCombinerPattern::FMULSUBH_OP2: 4775 case MachineCombinerPattern::FMULADDS_OP1: 4776 case MachineCombinerPattern::FMULADDS_OP2: 4777 case MachineCombinerPattern::FMULSUBS_OP1: 4778 case MachineCombinerPattern::FMULSUBS_OP2: 4779 case MachineCombinerPattern::FMULADDD_OP1: 4780 case MachineCombinerPattern::FMULADDD_OP2: 4781 case MachineCombinerPattern::FMULSUBD_OP1: 4782 case MachineCombinerPattern::FMULSUBD_OP2: 4783 case MachineCombinerPattern::FNMULSUBH_OP1: 4784 case MachineCombinerPattern::FNMULSUBS_OP1: 4785 case MachineCombinerPattern::FNMULSUBD_OP1: 4786 case MachineCombinerPattern::FMLAv4i16_indexed_OP1: 4787 case MachineCombinerPattern::FMLAv4i16_indexed_OP2: 4788 case MachineCombinerPattern::FMLAv8i16_indexed_OP1: 4789 case MachineCombinerPattern::FMLAv8i16_indexed_OP2: 4790 case MachineCombinerPattern::FMLAv1i32_indexed_OP1: 4791 case MachineCombinerPattern::FMLAv1i32_indexed_OP2: 4792 case MachineCombinerPattern::FMLAv1i64_indexed_OP1: 4793 case MachineCombinerPattern::FMLAv1i64_indexed_OP2: 4794 case MachineCombinerPattern::FMLAv4f16_OP2: 4795 case MachineCombinerPattern::FMLAv4f16_OP1: 4796 case MachineCombinerPattern::FMLAv8f16_OP1: 4797 case MachineCombinerPattern::FMLAv8f16_OP2: 4798 case MachineCombinerPattern::FMLAv2f32_OP2: 4799 case MachineCombinerPattern::FMLAv2f32_OP1: 4800 case MachineCombinerPattern::FMLAv2f64_OP1: 4801 case MachineCombinerPattern::FMLAv2f64_OP2: 4802 case MachineCombinerPattern::FMLAv2i32_indexed_OP1: 4803 case MachineCombinerPattern::FMLAv2i32_indexed_OP2: 4804 case MachineCombinerPattern::FMLAv2i64_indexed_OP1: 4805 case MachineCombinerPattern::FMLAv2i64_indexed_OP2: 4806 case MachineCombinerPattern::FMLAv4f32_OP1: 4807 case MachineCombinerPattern::FMLAv4f32_OP2: 4808 case MachineCombinerPattern::FMLAv4i32_indexed_OP1: 4809 case MachineCombinerPattern::FMLAv4i32_indexed_OP2: 4810 case MachineCombinerPattern::FMLSv4i16_indexed_OP1: 4811 case MachineCombinerPattern::FMLSv4i16_indexed_OP2: 4812 case MachineCombinerPattern::FMLSv8i16_indexed_OP1: 4813 case MachineCombinerPattern::FMLSv8i16_indexed_OP2: 4814 case MachineCombinerPattern::FMLSv1i32_indexed_OP2: 4815 case MachineCombinerPattern::FMLSv1i64_indexed_OP2: 4816 case MachineCombinerPattern::FMLSv2i32_indexed_OP2: 4817 case MachineCombinerPattern::FMLSv2i64_indexed_OP2: 4818 case MachineCombinerPattern::FMLSv4f16_OP1: 4819 case MachineCombinerPattern::FMLSv4f16_OP2: 4820 case MachineCombinerPattern::FMLSv8f16_OP1: 4821 case MachineCombinerPattern::FMLSv8f16_OP2: 4822 case MachineCombinerPattern::FMLSv2f32_OP2: 4823 case MachineCombinerPattern::FMLSv2f64_OP2: 4824 case MachineCombinerPattern::FMLSv4i32_indexed_OP2: 4825 case MachineCombinerPattern::FMLSv4f32_OP2: 4826 case MachineCombinerPattern::MULADDv8i8_OP1: 4827 case MachineCombinerPattern::MULADDv8i8_OP2: 4828 case MachineCombinerPattern::MULADDv16i8_OP1: 4829 case MachineCombinerPattern::MULADDv16i8_OP2: 4830 case MachineCombinerPattern::MULADDv4i16_OP1: 4831 case MachineCombinerPattern::MULADDv4i16_OP2: 4832 case MachineCombinerPattern::MULADDv8i16_OP1: 4833 case MachineCombinerPattern::MULADDv8i16_OP2: 4834 case MachineCombinerPattern::MULADDv2i32_OP1: 4835 case MachineCombinerPattern::MULADDv2i32_OP2: 4836 case MachineCombinerPattern::MULADDv4i32_OP1: 4837 case MachineCombinerPattern::MULADDv4i32_OP2: 4838 case MachineCombinerPattern::MULSUBv8i8_OP1: 4839 case MachineCombinerPattern::MULSUBv8i8_OP2: 4840 case MachineCombinerPattern::MULSUBv16i8_OP1: 4841 case MachineCombinerPattern::MULSUBv16i8_OP2: 4842 case MachineCombinerPattern::MULSUBv4i16_OP1: 4843 case MachineCombinerPattern::MULSUBv4i16_OP2: 4844 case MachineCombinerPattern::MULSUBv8i16_OP1: 4845 case MachineCombinerPattern::MULSUBv8i16_OP2: 4846 case MachineCombinerPattern::MULSUBv2i32_OP1: 4847 case MachineCombinerPattern::MULSUBv2i32_OP2: 4848 case MachineCombinerPattern::MULSUBv4i32_OP1: 4849 case MachineCombinerPattern::MULSUBv4i32_OP2: 4850 case MachineCombinerPattern::MULADDv4i16_indexed_OP1: 4851 case MachineCombinerPattern::MULADDv4i16_indexed_OP2: 4852 case MachineCombinerPattern::MULADDv8i16_indexed_OP1: 4853 case MachineCombinerPattern::MULADDv8i16_indexed_OP2: 4854 case MachineCombinerPattern::MULADDv2i32_indexed_OP1: 4855 case MachineCombinerPattern::MULADDv2i32_indexed_OP2: 4856 case MachineCombinerPattern::MULADDv4i32_indexed_OP1: 4857 case MachineCombinerPattern::MULADDv4i32_indexed_OP2: 4858 case MachineCombinerPattern::MULSUBv4i16_indexed_OP1: 4859 case MachineCombinerPattern::MULSUBv4i16_indexed_OP2: 4860 case MachineCombinerPattern::MULSUBv8i16_indexed_OP1: 4861 case MachineCombinerPattern::MULSUBv8i16_indexed_OP2: 4862 case MachineCombinerPattern::MULSUBv2i32_indexed_OP1: 4863 case MachineCombinerPattern::MULSUBv2i32_indexed_OP2: 4864 case MachineCombinerPattern::MULSUBv4i32_indexed_OP1: 4865 case MachineCombinerPattern::MULSUBv4i32_indexed_OP2: 4866 return true; 4867 } // end switch (Pattern) 4868 return false; 4869 } 4870 /// Return true when there is potentially a faster code sequence for an 4871 /// instruction chain ending in \p Root. All potential patterns are listed in 4872 /// the \p Pattern vector. Pattern should be sorted in priority order since the 4873 /// pattern evaluator stops checking as soon as it finds a faster sequence. 4874 4875 bool AArch64InstrInfo::getMachineCombinerPatterns( 4876 MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns, 4877 bool DoRegPressureReduce) const { 4878 // Integer patterns 4879 if (getMaddPatterns(Root, Patterns)) 4880 return true; 4881 // Floating point patterns 4882 if (getFMAPatterns(Root, Patterns)) 4883 return true; 4884 4885 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns, 4886 DoRegPressureReduce); 4887 } 4888 4889 enum class FMAInstKind { Default, Indexed, Accumulator }; 4890 /// genFusedMultiply - Generate fused multiply instructions. 4891 /// This function supports both integer and floating point instructions. 4892 /// A typical example: 4893 /// F|MUL I=A,B,0 4894 /// F|ADD R,I,C 4895 /// ==> F|MADD R,A,B,C 4896 /// \param MF Containing MachineFunction 4897 /// \param MRI Register information 4898 /// \param TII Target information 4899 /// \param Root is the F|ADD instruction 4900 /// \param [out] InsInstrs is a vector of machine instructions and will 4901 /// contain the generated madd instruction 4902 /// \param IdxMulOpd is index of operand in Root that is the result of 4903 /// the F|MUL. In the example above IdxMulOpd is 1. 4904 /// \param MaddOpc the opcode fo the f|madd instruction 4905 /// \param RC Register class of operands 4906 /// \param kind of fma instruction (addressing mode) to be generated 4907 /// \param ReplacedAddend is the result register from the instruction 4908 /// replacing the non-combined operand, if any. 4909 static MachineInstr * 4910 genFusedMultiply(MachineFunction &MF, MachineRegisterInfo &MRI, 4911 const TargetInstrInfo *TII, MachineInstr &Root, 4912 SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd, 4913 unsigned MaddOpc, const TargetRegisterClass *RC, 4914 FMAInstKind kind = FMAInstKind::Default, 4915 const Register *ReplacedAddend = nullptr) { 4916 assert(IdxMulOpd == 1 || IdxMulOpd == 2); 4917 4918 unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1; 4919 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg()); 4920 Register ResultReg = Root.getOperand(0).getReg(); 4921 Register SrcReg0 = MUL->getOperand(1).getReg(); 4922 bool Src0IsKill = MUL->getOperand(1).isKill(); 4923 Register SrcReg1 = MUL->getOperand(2).getReg(); 4924 bool Src1IsKill = MUL->getOperand(2).isKill(); 4925 4926 unsigned SrcReg2; 4927 bool Src2IsKill; 4928 if (ReplacedAddend) { 4929 // If we just generated a new addend, we must be it's only use. 4930 SrcReg2 = *ReplacedAddend; 4931 Src2IsKill = true; 4932 } else { 4933 SrcReg2 = Root.getOperand(IdxOtherOpd).getReg(); 4934 Src2IsKill = Root.getOperand(IdxOtherOpd).isKill(); 4935 } 4936 4937 if (Register::isVirtualRegister(ResultReg)) 4938 MRI.constrainRegClass(ResultReg, RC); 4939 if (Register::isVirtualRegister(SrcReg0)) 4940 MRI.constrainRegClass(SrcReg0, RC); 4941 if (Register::isVirtualRegister(SrcReg1)) 4942 MRI.constrainRegClass(SrcReg1, RC); 4943 if (Register::isVirtualRegister(SrcReg2)) 4944 MRI.constrainRegClass(SrcReg2, RC); 4945 4946 MachineInstrBuilder MIB; 4947 if (kind == FMAInstKind::Default) 4948 MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg) 4949 .addReg(SrcReg0, getKillRegState(Src0IsKill)) 4950 .addReg(SrcReg1, getKillRegState(Src1IsKill)) 4951 .addReg(SrcReg2, getKillRegState(Src2IsKill)); 4952 else if (kind == FMAInstKind::Indexed) 4953 MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg) 4954 .addReg(SrcReg2, getKillRegState(Src2IsKill)) 4955 .addReg(SrcReg0, getKillRegState(Src0IsKill)) 4956 .addReg(SrcReg1, getKillRegState(Src1IsKill)) 4957 .addImm(MUL->getOperand(3).getImm()); 4958 else if (kind == FMAInstKind::Accumulator) 4959 MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg) 4960 .addReg(SrcReg2, getKillRegState(Src2IsKill)) 4961 .addReg(SrcReg0, getKillRegState(Src0IsKill)) 4962 .addReg(SrcReg1, getKillRegState(Src1IsKill)); 4963 else 4964 assert(false && "Invalid FMA instruction kind \n"); 4965 // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL) 4966 InsInstrs.push_back(MIB); 4967 return MUL; 4968 } 4969 4970 /// genFusedMultiplyAcc - Helper to generate fused multiply accumulate 4971 /// instructions. 4972 /// 4973 /// \see genFusedMultiply 4974 static MachineInstr *genFusedMultiplyAcc( 4975 MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, 4976 MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs, 4977 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) { 4978 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC, 4979 FMAInstKind::Accumulator); 4980 } 4981 4982 /// genNeg - Helper to generate an intermediate negation of the second operand 4983 /// of Root 4984 static Register genNeg(MachineFunction &MF, MachineRegisterInfo &MRI, 4985 const TargetInstrInfo *TII, MachineInstr &Root, 4986 SmallVectorImpl<MachineInstr *> &InsInstrs, 4987 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, 4988 unsigned MnegOpc, const TargetRegisterClass *RC) { 4989 Register NewVR = MRI.createVirtualRegister(RC); 4990 MachineInstrBuilder MIB = 4991 BuildMI(MF, Root.getDebugLoc(), TII->get(MnegOpc), NewVR) 4992 .add(Root.getOperand(2)); 4993 InsInstrs.push_back(MIB); 4994 4995 assert(InstrIdxForVirtReg.empty()); 4996 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 4997 4998 return NewVR; 4999 } 5000 5001 /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate 5002 /// instructions with an additional negation of the accumulator 5003 static MachineInstr *genFusedMultiplyAccNeg( 5004 MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, 5005 MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs, 5006 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd, 5007 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) { 5008 assert(IdxMulOpd == 1); 5009 5010 Register NewVR = 5011 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC); 5012 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC, 5013 FMAInstKind::Accumulator, &NewVR); 5014 } 5015 5016 /// genFusedMultiplyIdx - Helper to generate fused multiply accumulate 5017 /// instructions. 5018 /// 5019 /// \see genFusedMultiply 5020 static MachineInstr *genFusedMultiplyIdx( 5021 MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, 5022 MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs, 5023 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) { 5024 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC, 5025 FMAInstKind::Indexed); 5026 } 5027 5028 /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate 5029 /// instructions with an additional negation of the accumulator 5030 static MachineInstr *genFusedMultiplyIdxNeg( 5031 MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, 5032 MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs, 5033 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd, 5034 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) { 5035 assert(IdxMulOpd == 1); 5036 5037 Register NewVR = 5038 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC); 5039 5040 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC, 5041 FMAInstKind::Indexed, &NewVR); 5042 } 5043 5044 /// genMaddR - Generate madd instruction and combine mul and add using 5045 /// an extra virtual register 5046 /// Example - an ADD intermediate needs to be stored in a register: 5047 /// MUL I=A,B,0 5048 /// ADD R,I,Imm 5049 /// ==> ORR V, ZR, Imm 5050 /// ==> MADD R,A,B,V 5051 /// \param MF Containing MachineFunction 5052 /// \param MRI Register information 5053 /// \param TII Target information 5054 /// \param Root is the ADD instruction 5055 /// \param [out] InsInstrs is a vector of machine instructions and will 5056 /// contain the generated madd instruction 5057 /// \param IdxMulOpd is index of operand in Root that is the result of 5058 /// the MUL. In the example above IdxMulOpd is 1. 5059 /// \param MaddOpc the opcode fo the madd instruction 5060 /// \param VR is a virtual register that holds the value of an ADD operand 5061 /// (V in the example above). 5062 /// \param RC Register class of operands 5063 static MachineInstr *genMaddR(MachineFunction &MF, MachineRegisterInfo &MRI, 5064 const TargetInstrInfo *TII, MachineInstr &Root, 5065 SmallVectorImpl<MachineInstr *> &InsInstrs, 5066 unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR, 5067 const TargetRegisterClass *RC) { 5068 assert(IdxMulOpd == 1 || IdxMulOpd == 2); 5069 5070 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg()); 5071 Register ResultReg = Root.getOperand(0).getReg(); 5072 Register SrcReg0 = MUL->getOperand(1).getReg(); 5073 bool Src0IsKill = MUL->getOperand(1).isKill(); 5074 Register SrcReg1 = MUL->getOperand(2).getReg(); 5075 bool Src1IsKill = MUL->getOperand(2).isKill(); 5076 5077 if (Register::isVirtualRegister(ResultReg)) 5078 MRI.constrainRegClass(ResultReg, RC); 5079 if (Register::isVirtualRegister(SrcReg0)) 5080 MRI.constrainRegClass(SrcReg0, RC); 5081 if (Register::isVirtualRegister(SrcReg1)) 5082 MRI.constrainRegClass(SrcReg1, RC); 5083 if (Register::isVirtualRegister(VR)) 5084 MRI.constrainRegClass(VR, RC); 5085 5086 MachineInstrBuilder MIB = 5087 BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg) 5088 .addReg(SrcReg0, getKillRegState(Src0IsKill)) 5089 .addReg(SrcReg1, getKillRegState(Src1IsKill)) 5090 .addReg(VR); 5091 // Insert the MADD 5092 InsInstrs.push_back(MIB); 5093 return MUL; 5094 } 5095 5096 /// When getMachineCombinerPatterns() finds potential patterns, 5097 /// this function generates the instructions that could replace the 5098 /// original code sequence 5099 void AArch64InstrInfo::genAlternativeCodeSequence( 5100 MachineInstr &Root, MachineCombinerPattern Pattern, 5101 SmallVectorImpl<MachineInstr *> &InsInstrs, 5102 SmallVectorImpl<MachineInstr *> &DelInstrs, 5103 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const { 5104 MachineBasicBlock &MBB = *Root.getParent(); 5105 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 5106 MachineFunction &MF = *MBB.getParent(); 5107 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 5108 5109 MachineInstr *MUL = nullptr; 5110 const TargetRegisterClass *RC; 5111 unsigned Opc; 5112 switch (Pattern) { 5113 default: 5114 // Reassociate instructions. 5115 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs, 5116 DelInstrs, InstrIdxForVirtReg); 5117 return; 5118 case MachineCombinerPattern::MULADDW_OP1: 5119 case MachineCombinerPattern::MULADDX_OP1: 5120 // MUL I=A,B,0 5121 // ADD R,I,C 5122 // ==> MADD R,A,B,C 5123 // --- Create(MADD); 5124 if (Pattern == MachineCombinerPattern::MULADDW_OP1) { 5125 Opc = AArch64::MADDWrrr; 5126 RC = &AArch64::GPR32RegClass; 5127 } else { 5128 Opc = AArch64::MADDXrrr; 5129 RC = &AArch64::GPR64RegClass; 5130 } 5131 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5132 break; 5133 case MachineCombinerPattern::MULADDW_OP2: 5134 case MachineCombinerPattern::MULADDX_OP2: 5135 // MUL I=A,B,0 5136 // ADD R,C,I 5137 // ==> MADD R,A,B,C 5138 // --- Create(MADD); 5139 if (Pattern == MachineCombinerPattern::MULADDW_OP2) { 5140 Opc = AArch64::MADDWrrr; 5141 RC = &AArch64::GPR32RegClass; 5142 } else { 5143 Opc = AArch64::MADDXrrr; 5144 RC = &AArch64::GPR64RegClass; 5145 } 5146 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5147 break; 5148 case MachineCombinerPattern::MULADDWI_OP1: 5149 case MachineCombinerPattern::MULADDXI_OP1: { 5150 // MUL I=A,B,0 5151 // ADD R,I,Imm 5152 // ==> ORR V, ZR, Imm 5153 // ==> MADD R,A,B,V 5154 // --- Create(MADD); 5155 const TargetRegisterClass *OrrRC; 5156 unsigned BitSize, OrrOpc, ZeroReg; 5157 if (Pattern == MachineCombinerPattern::MULADDWI_OP1) { 5158 OrrOpc = AArch64::ORRWri; 5159 OrrRC = &AArch64::GPR32spRegClass; 5160 BitSize = 32; 5161 ZeroReg = AArch64::WZR; 5162 Opc = AArch64::MADDWrrr; 5163 RC = &AArch64::GPR32RegClass; 5164 } else { 5165 OrrOpc = AArch64::ORRXri; 5166 OrrRC = &AArch64::GPR64spRegClass; 5167 BitSize = 64; 5168 ZeroReg = AArch64::XZR; 5169 Opc = AArch64::MADDXrrr; 5170 RC = &AArch64::GPR64RegClass; 5171 } 5172 Register NewVR = MRI.createVirtualRegister(OrrRC); 5173 uint64_t Imm = Root.getOperand(2).getImm(); 5174 5175 if (Root.getOperand(3).isImm()) { 5176 unsigned Val = Root.getOperand(3).getImm(); 5177 Imm = Imm << Val; 5178 } 5179 uint64_t UImm = SignExtend64(Imm, BitSize); 5180 uint64_t Encoding; 5181 if (AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding)) { 5182 MachineInstrBuilder MIB1 = 5183 BuildMI(MF, Root.getDebugLoc(), TII->get(OrrOpc), NewVR) 5184 .addReg(ZeroReg) 5185 .addImm(Encoding); 5186 InsInstrs.push_back(MIB1); 5187 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5188 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC); 5189 } 5190 break; 5191 } 5192 case MachineCombinerPattern::MULSUBW_OP1: 5193 case MachineCombinerPattern::MULSUBX_OP1: { 5194 // MUL I=A,B,0 5195 // SUB R,I, C 5196 // ==> SUB V, 0, C 5197 // ==> MADD R,A,B,V // = -C + A*B 5198 // --- Create(MADD); 5199 const TargetRegisterClass *SubRC; 5200 unsigned SubOpc, ZeroReg; 5201 if (Pattern == MachineCombinerPattern::MULSUBW_OP1) { 5202 SubOpc = AArch64::SUBWrr; 5203 SubRC = &AArch64::GPR32spRegClass; 5204 ZeroReg = AArch64::WZR; 5205 Opc = AArch64::MADDWrrr; 5206 RC = &AArch64::GPR32RegClass; 5207 } else { 5208 SubOpc = AArch64::SUBXrr; 5209 SubRC = &AArch64::GPR64spRegClass; 5210 ZeroReg = AArch64::XZR; 5211 Opc = AArch64::MADDXrrr; 5212 RC = &AArch64::GPR64RegClass; 5213 } 5214 Register NewVR = MRI.createVirtualRegister(SubRC); 5215 // SUB NewVR, 0, C 5216 MachineInstrBuilder MIB1 = 5217 BuildMI(MF, Root.getDebugLoc(), TII->get(SubOpc), NewVR) 5218 .addReg(ZeroReg) 5219 .add(Root.getOperand(2)); 5220 InsInstrs.push_back(MIB1); 5221 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5222 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC); 5223 break; 5224 } 5225 case MachineCombinerPattern::MULSUBW_OP2: 5226 case MachineCombinerPattern::MULSUBX_OP2: 5227 // MUL I=A,B,0 5228 // SUB R,C,I 5229 // ==> MSUB R,A,B,C (computes C - A*B) 5230 // --- Create(MSUB); 5231 if (Pattern == MachineCombinerPattern::MULSUBW_OP2) { 5232 Opc = AArch64::MSUBWrrr; 5233 RC = &AArch64::GPR32RegClass; 5234 } else { 5235 Opc = AArch64::MSUBXrrr; 5236 RC = &AArch64::GPR64RegClass; 5237 } 5238 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5239 break; 5240 case MachineCombinerPattern::MULSUBWI_OP1: 5241 case MachineCombinerPattern::MULSUBXI_OP1: { 5242 // MUL I=A,B,0 5243 // SUB R,I, Imm 5244 // ==> ORR V, ZR, -Imm 5245 // ==> MADD R,A,B,V // = -Imm + A*B 5246 // --- Create(MADD); 5247 const TargetRegisterClass *OrrRC; 5248 unsigned BitSize, OrrOpc, ZeroReg; 5249 if (Pattern == MachineCombinerPattern::MULSUBWI_OP1) { 5250 OrrOpc = AArch64::ORRWri; 5251 OrrRC = &AArch64::GPR32spRegClass; 5252 BitSize = 32; 5253 ZeroReg = AArch64::WZR; 5254 Opc = AArch64::MADDWrrr; 5255 RC = &AArch64::GPR32RegClass; 5256 } else { 5257 OrrOpc = AArch64::ORRXri; 5258 OrrRC = &AArch64::GPR64spRegClass; 5259 BitSize = 64; 5260 ZeroReg = AArch64::XZR; 5261 Opc = AArch64::MADDXrrr; 5262 RC = &AArch64::GPR64RegClass; 5263 } 5264 Register NewVR = MRI.createVirtualRegister(OrrRC); 5265 uint64_t Imm = Root.getOperand(2).getImm(); 5266 if (Root.getOperand(3).isImm()) { 5267 unsigned Val = Root.getOperand(3).getImm(); 5268 Imm = Imm << Val; 5269 } 5270 uint64_t UImm = SignExtend64(-Imm, BitSize); 5271 uint64_t Encoding; 5272 if (AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding)) { 5273 MachineInstrBuilder MIB1 = 5274 BuildMI(MF, Root.getDebugLoc(), TII->get(OrrOpc), NewVR) 5275 .addReg(ZeroReg) 5276 .addImm(Encoding); 5277 InsInstrs.push_back(MIB1); 5278 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5279 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC); 5280 } 5281 break; 5282 } 5283 5284 case MachineCombinerPattern::MULADDv8i8_OP1: 5285 Opc = AArch64::MLAv8i8; 5286 RC = &AArch64::FPR64RegClass; 5287 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5288 break; 5289 case MachineCombinerPattern::MULADDv8i8_OP2: 5290 Opc = AArch64::MLAv8i8; 5291 RC = &AArch64::FPR64RegClass; 5292 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5293 break; 5294 case MachineCombinerPattern::MULADDv16i8_OP1: 5295 Opc = AArch64::MLAv16i8; 5296 RC = &AArch64::FPR128RegClass; 5297 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5298 break; 5299 case MachineCombinerPattern::MULADDv16i8_OP2: 5300 Opc = AArch64::MLAv16i8; 5301 RC = &AArch64::FPR128RegClass; 5302 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5303 break; 5304 case MachineCombinerPattern::MULADDv4i16_OP1: 5305 Opc = AArch64::MLAv4i16; 5306 RC = &AArch64::FPR64RegClass; 5307 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5308 break; 5309 case MachineCombinerPattern::MULADDv4i16_OP2: 5310 Opc = AArch64::MLAv4i16; 5311 RC = &AArch64::FPR64RegClass; 5312 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5313 break; 5314 case MachineCombinerPattern::MULADDv8i16_OP1: 5315 Opc = AArch64::MLAv8i16; 5316 RC = &AArch64::FPR128RegClass; 5317 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5318 break; 5319 case MachineCombinerPattern::MULADDv8i16_OP2: 5320 Opc = AArch64::MLAv8i16; 5321 RC = &AArch64::FPR128RegClass; 5322 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5323 break; 5324 case MachineCombinerPattern::MULADDv2i32_OP1: 5325 Opc = AArch64::MLAv2i32; 5326 RC = &AArch64::FPR64RegClass; 5327 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5328 break; 5329 case MachineCombinerPattern::MULADDv2i32_OP2: 5330 Opc = AArch64::MLAv2i32; 5331 RC = &AArch64::FPR64RegClass; 5332 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5333 break; 5334 case MachineCombinerPattern::MULADDv4i32_OP1: 5335 Opc = AArch64::MLAv4i32; 5336 RC = &AArch64::FPR128RegClass; 5337 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5338 break; 5339 case MachineCombinerPattern::MULADDv4i32_OP2: 5340 Opc = AArch64::MLAv4i32; 5341 RC = &AArch64::FPR128RegClass; 5342 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5343 break; 5344 5345 case MachineCombinerPattern::MULSUBv8i8_OP1: 5346 Opc = AArch64::MLAv8i8; 5347 RC = &AArch64::FPR64RegClass; 5348 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs, 5349 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8, 5350 RC); 5351 break; 5352 case MachineCombinerPattern::MULSUBv8i8_OP2: 5353 Opc = AArch64::MLSv8i8; 5354 RC = &AArch64::FPR64RegClass; 5355 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5356 break; 5357 case MachineCombinerPattern::MULSUBv16i8_OP1: 5358 Opc = AArch64::MLAv16i8; 5359 RC = &AArch64::FPR128RegClass; 5360 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs, 5361 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8, 5362 RC); 5363 break; 5364 case MachineCombinerPattern::MULSUBv16i8_OP2: 5365 Opc = AArch64::MLSv16i8; 5366 RC = &AArch64::FPR128RegClass; 5367 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5368 break; 5369 case MachineCombinerPattern::MULSUBv4i16_OP1: 5370 Opc = AArch64::MLAv4i16; 5371 RC = &AArch64::FPR64RegClass; 5372 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs, 5373 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16, 5374 RC); 5375 break; 5376 case MachineCombinerPattern::MULSUBv4i16_OP2: 5377 Opc = AArch64::MLSv4i16; 5378 RC = &AArch64::FPR64RegClass; 5379 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5380 break; 5381 case MachineCombinerPattern::MULSUBv8i16_OP1: 5382 Opc = AArch64::MLAv8i16; 5383 RC = &AArch64::FPR128RegClass; 5384 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs, 5385 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16, 5386 RC); 5387 break; 5388 case MachineCombinerPattern::MULSUBv8i16_OP2: 5389 Opc = AArch64::MLSv8i16; 5390 RC = &AArch64::FPR128RegClass; 5391 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5392 break; 5393 case MachineCombinerPattern::MULSUBv2i32_OP1: 5394 Opc = AArch64::MLAv2i32; 5395 RC = &AArch64::FPR64RegClass; 5396 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs, 5397 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32, 5398 RC); 5399 break; 5400 case MachineCombinerPattern::MULSUBv2i32_OP2: 5401 Opc = AArch64::MLSv2i32; 5402 RC = &AArch64::FPR64RegClass; 5403 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5404 break; 5405 case MachineCombinerPattern::MULSUBv4i32_OP1: 5406 Opc = AArch64::MLAv4i32; 5407 RC = &AArch64::FPR128RegClass; 5408 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs, 5409 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32, 5410 RC); 5411 break; 5412 case MachineCombinerPattern::MULSUBv4i32_OP2: 5413 Opc = AArch64::MLSv4i32; 5414 RC = &AArch64::FPR128RegClass; 5415 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5416 break; 5417 5418 case MachineCombinerPattern::MULADDv4i16_indexed_OP1: 5419 Opc = AArch64::MLAv4i16_indexed; 5420 RC = &AArch64::FPR64RegClass; 5421 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5422 break; 5423 case MachineCombinerPattern::MULADDv4i16_indexed_OP2: 5424 Opc = AArch64::MLAv4i16_indexed; 5425 RC = &AArch64::FPR64RegClass; 5426 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5427 break; 5428 case MachineCombinerPattern::MULADDv8i16_indexed_OP1: 5429 Opc = AArch64::MLAv8i16_indexed; 5430 RC = &AArch64::FPR128RegClass; 5431 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5432 break; 5433 case MachineCombinerPattern::MULADDv8i16_indexed_OP2: 5434 Opc = AArch64::MLAv8i16_indexed; 5435 RC = &AArch64::FPR128RegClass; 5436 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5437 break; 5438 case MachineCombinerPattern::MULADDv2i32_indexed_OP1: 5439 Opc = AArch64::MLAv2i32_indexed; 5440 RC = &AArch64::FPR64RegClass; 5441 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5442 break; 5443 case MachineCombinerPattern::MULADDv2i32_indexed_OP2: 5444 Opc = AArch64::MLAv2i32_indexed; 5445 RC = &AArch64::FPR64RegClass; 5446 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5447 break; 5448 case MachineCombinerPattern::MULADDv4i32_indexed_OP1: 5449 Opc = AArch64::MLAv4i32_indexed; 5450 RC = &AArch64::FPR128RegClass; 5451 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5452 break; 5453 case MachineCombinerPattern::MULADDv4i32_indexed_OP2: 5454 Opc = AArch64::MLAv4i32_indexed; 5455 RC = &AArch64::FPR128RegClass; 5456 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5457 break; 5458 5459 case MachineCombinerPattern::MULSUBv4i16_indexed_OP1: 5460 Opc = AArch64::MLAv4i16_indexed; 5461 RC = &AArch64::FPR64RegClass; 5462 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs, 5463 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16, 5464 RC); 5465 break; 5466 case MachineCombinerPattern::MULSUBv4i16_indexed_OP2: 5467 Opc = AArch64::MLSv4i16_indexed; 5468 RC = &AArch64::FPR64RegClass; 5469 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5470 break; 5471 case MachineCombinerPattern::MULSUBv8i16_indexed_OP1: 5472 Opc = AArch64::MLAv8i16_indexed; 5473 RC = &AArch64::FPR128RegClass; 5474 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs, 5475 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16, 5476 RC); 5477 break; 5478 case MachineCombinerPattern::MULSUBv8i16_indexed_OP2: 5479 Opc = AArch64::MLSv8i16_indexed; 5480 RC = &AArch64::FPR128RegClass; 5481 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5482 break; 5483 case MachineCombinerPattern::MULSUBv2i32_indexed_OP1: 5484 Opc = AArch64::MLAv2i32_indexed; 5485 RC = &AArch64::FPR64RegClass; 5486 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs, 5487 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32, 5488 RC); 5489 break; 5490 case MachineCombinerPattern::MULSUBv2i32_indexed_OP2: 5491 Opc = AArch64::MLSv2i32_indexed; 5492 RC = &AArch64::FPR64RegClass; 5493 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5494 break; 5495 case MachineCombinerPattern::MULSUBv4i32_indexed_OP1: 5496 Opc = AArch64::MLAv4i32_indexed; 5497 RC = &AArch64::FPR128RegClass; 5498 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs, 5499 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32, 5500 RC); 5501 break; 5502 case MachineCombinerPattern::MULSUBv4i32_indexed_OP2: 5503 Opc = AArch64::MLSv4i32_indexed; 5504 RC = &AArch64::FPR128RegClass; 5505 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5506 break; 5507 5508 // Floating Point Support 5509 case MachineCombinerPattern::FMULADDH_OP1: 5510 Opc = AArch64::FMADDHrrr; 5511 RC = &AArch64::FPR16RegClass; 5512 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5513 break; 5514 case MachineCombinerPattern::FMULADDS_OP1: 5515 Opc = AArch64::FMADDSrrr; 5516 RC = &AArch64::FPR32RegClass; 5517 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5518 break; 5519 case MachineCombinerPattern::FMULADDD_OP1: 5520 Opc = AArch64::FMADDDrrr; 5521 RC = &AArch64::FPR64RegClass; 5522 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5523 break; 5524 5525 case MachineCombinerPattern::FMULADDH_OP2: 5526 Opc = AArch64::FMADDHrrr; 5527 RC = &AArch64::FPR16RegClass; 5528 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5529 break; 5530 case MachineCombinerPattern::FMULADDS_OP2: 5531 Opc = AArch64::FMADDSrrr; 5532 RC = &AArch64::FPR32RegClass; 5533 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5534 break; 5535 case MachineCombinerPattern::FMULADDD_OP2: 5536 Opc = AArch64::FMADDDrrr; 5537 RC = &AArch64::FPR64RegClass; 5538 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5539 break; 5540 5541 case MachineCombinerPattern::FMLAv1i32_indexed_OP1: 5542 Opc = AArch64::FMLAv1i32_indexed; 5543 RC = &AArch64::FPR32RegClass; 5544 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5545 FMAInstKind::Indexed); 5546 break; 5547 case MachineCombinerPattern::FMLAv1i32_indexed_OP2: 5548 Opc = AArch64::FMLAv1i32_indexed; 5549 RC = &AArch64::FPR32RegClass; 5550 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5551 FMAInstKind::Indexed); 5552 break; 5553 5554 case MachineCombinerPattern::FMLAv1i64_indexed_OP1: 5555 Opc = AArch64::FMLAv1i64_indexed; 5556 RC = &AArch64::FPR64RegClass; 5557 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5558 FMAInstKind::Indexed); 5559 break; 5560 case MachineCombinerPattern::FMLAv1i64_indexed_OP2: 5561 Opc = AArch64::FMLAv1i64_indexed; 5562 RC = &AArch64::FPR64RegClass; 5563 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5564 FMAInstKind::Indexed); 5565 break; 5566 5567 case MachineCombinerPattern::FMLAv4i16_indexed_OP1: 5568 RC = &AArch64::FPR64RegClass; 5569 Opc = AArch64::FMLAv4i16_indexed; 5570 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5571 FMAInstKind::Indexed); 5572 break; 5573 case MachineCombinerPattern::FMLAv4f16_OP1: 5574 RC = &AArch64::FPR64RegClass; 5575 Opc = AArch64::FMLAv4f16; 5576 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5577 FMAInstKind::Accumulator); 5578 break; 5579 case MachineCombinerPattern::FMLAv4i16_indexed_OP2: 5580 RC = &AArch64::FPR64RegClass; 5581 Opc = AArch64::FMLAv4i16_indexed; 5582 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5583 FMAInstKind::Indexed); 5584 break; 5585 case MachineCombinerPattern::FMLAv4f16_OP2: 5586 RC = &AArch64::FPR64RegClass; 5587 Opc = AArch64::FMLAv4f16; 5588 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5589 FMAInstKind::Accumulator); 5590 break; 5591 5592 case MachineCombinerPattern::FMLAv2i32_indexed_OP1: 5593 case MachineCombinerPattern::FMLAv2f32_OP1: 5594 RC = &AArch64::FPR64RegClass; 5595 if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP1) { 5596 Opc = AArch64::FMLAv2i32_indexed; 5597 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5598 FMAInstKind::Indexed); 5599 } else { 5600 Opc = AArch64::FMLAv2f32; 5601 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5602 FMAInstKind::Accumulator); 5603 } 5604 break; 5605 case MachineCombinerPattern::FMLAv2i32_indexed_OP2: 5606 case MachineCombinerPattern::FMLAv2f32_OP2: 5607 RC = &AArch64::FPR64RegClass; 5608 if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP2) { 5609 Opc = AArch64::FMLAv2i32_indexed; 5610 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5611 FMAInstKind::Indexed); 5612 } else { 5613 Opc = AArch64::FMLAv2f32; 5614 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5615 FMAInstKind::Accumulator); 5616 } 5617 break; 5618 5619 case MachineCombinerPattern::FMLAv8i16_indexed_OP1: 5620 RC = &AArch64::FPR128RegClass; 5621 Opc = AArch64::FMLAv8i16_indexed; 5622 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5623 FMAInstKind::Indexed); 5624 break; 5625 case MachineCombinerPattern::FMLAv8f16_OP1: 5626 RC = &AArch64::FPR128RegClass; 5627 Opc = AArch64::FMLAv8f16; 5628 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5629 FMAInstKind::Accumulator); 5630 break; 5631 case MachineCombinerPattern::FMLAv8i16_indexed_OP2: 5632 RC = &AArch64::FPR128RegClass; 5633 Opc = AArch64::FMLAv8i16_indexed; 5634 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5635 FMAInstKind::Indexed); 5636 break; 5637 case MachineCombinerPattern::FMLAv8f16_OP2: 5638 RC = &AArch64::FPR128RegClass; 5639 Opc = AArch64::FMLAv8f16; 5640 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5641 FMAInstKind::Accumulator); 5642 break; 5643 5644 case MachineCombinerPattern::FMLAv2i64_indexed_OP1: 5645 case MachineCombinerPattern::FMLAv2f64_OP1: 5646 RC = &AArch64::FPR128RegClass; 5647 if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP1) { 5648 Opc = AArch64::FMLAv2i64_indexed; 5649 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5650 FMAInstKind::Indexed); 5651 } else { 5652 Opc = AArch64::FMLAv2f64; 5653 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5654 FMAInstKind::Accumulator); 5655 } 5656 break; 5657 case MachineCombinerPattern::FMLAv2i64_indexed_OP2: 5658 case MachineCombinerPattern::FMLAv2f64_OP2: 5659 RC = &AArch64::FPR128RegClass; 5660 if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP2) { 5661 Opc = AArch64::FMLAv2i64_indexed; 5662 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5663 FMAInstKind::Indexed); 5664 } else { 5665 Opc = AArch64::FMLAv2f64; 5666 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5667 FMAInstKind::Accumulator); 5668 } 5669 break; 5670 5671 case MachineCombinerPattern::FMLAv4i32_indexed_OP1: 5672 case MachineCombinerPattern::FMLAv4f32_OP1: 5673 RC = &AArch64::FPR128RegClass; 5674 if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP1) { 5675 Opc = AArch64::FMLAv4i32_indexed; 5676 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5677 FMAInstKind::Indexed); 5678 } else { 5679 Opc = AArch64::FMLAv4f32; 5680 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5681 FMAInstKind::Accumulator); 5682 } 5683 break; 5684 5685 case MachineCombinerPattern::FMLAv4i32_indexed_OP2: 5686 case MachineCombinerPattern::FMLAv4f32_OP2: 5687 RC = &AArch64::FPR128RegClass; 5688 if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP2) { 5689 Opc = AArch64::FMLAv4i32_indexed; 5690 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5691 FMAInstKind::Indexed); 5692 } else { 5693 Opc = AArch64::FMLAv4f32; 5694 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5695 FMAInstKind::Accumulator); 5696 } 5697 break; 5698 5699 case MachineCombinerPattern::FMULSUBH_OP1: 5700 Opc = AArch64::FNMSUBHrrr; 5701 RC = &AArch64::FPR16RegClass; 5702 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5703 break; 5704 case MachineCombinerPattern::FMULSUBS_OP1: 5705 Opc = AArch64::FNMSUBSrrr; 5706 RC = &AArch64::FPR32RegClass; 5707 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5708 break; 5709 case MachineCombinerPattern::FMULSUBD_OP1: 5710 Opc = AArch64::FNMSUBDrrr; 5711 RC = &AArch64::FPR64RegClass; 5712 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5713 break; 5714 5715 case MachineCombinerPattern::FNMULSUBH_OP1: 5716 Opc = AArch64::FNMADDHrrr; 5717 RC = &AArch64::FPR16RegClass; 5718 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5719 break; 5720 case MachineCombinerPattern::FNMULSUBS_OP1: 5721 Opc = AArch64::FNMADDSrrr; 5722 RC = &AArch64::FPR32RegClass; 5723 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5724 break; 5725 case MachineCombinerPattern::FNMULSUBD_OP1: 5726 Opc = AArch64::FNMADDDrrr; 5727 RC = &AArch64::FPR64RegClass; 5728 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC); 5729 break; 5730 5731 case MachineCombinerPattern::FMULSUBH_OP2: 5732 Opc = AArch64::FMSUBHrrr; 5733 RC = &AArch64::FPR16RegClass; 5734 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5735 break; 5736 case MachineCombinerPattern::FMULSUBS_OP2: 5737 Opc = AArch64::FMSUBSrrr; 5738 RC = &AArch64::FPR32RegClass; 5739 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5740 break; 5741 case MachineCombinerPattern::FMULSUBD_OP2: 5742 Opc = AArch64::FMSUBDrrr; 5743 RC = &AArch64::FPR64RegClass; 5744 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC); 5745 break; 5746 5747 case MachineCombinerPattern::FMLSv1i32_indexed_OP2: 5748 Opc = AArch64::FMLSv1i32_indexed; 5749 RC = &AArch64::FPR32RegClass; 5750 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5751 FMAInstKind::Indexed); 5752 break; 5753 5754 case MachineCombinerPattern::FMLSv1i64_indexed_OP2: 5755 Opc = AArch64::FMLSv1i64_indexed; 5756 RC = &AArch64::FPR64RegClass; 5757 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5758 FMAInstKind::Indexed); 5759 break; 5760 5761 case MachineCombinerPattern::FMLSv4f16_OP1: 5762 case MachineCombinerPattern::FMLSv4i16_indexed_OP1: { 5763 RC = &AArch64::FPR64RegClass; 5764 Register NewVR = MRI.createVirtualRegister(RC); 5765 MachineInstrBuilder MIB1 = 5766 BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv4f16), NewVR) 5767 .add(Root.getOperand(2)); 5768 InsInstrs.push_back(MIB1); 5769 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5770 if (Pattern == MachineCombinerPattern::FMLSv4f16_OP1) { 5771 Opc = AArch64::FMLAv4f16; 5772 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5773 FMAInstKind::Accumulator, &NewVR); 5774 } else { 5775 Opc = AArch64::FMLAv4i16_indexed; 5776 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5777 FMAInstKind::Indexed, &NewVR); 5778 } 5779 break; 5780 } 5781 case MachineCombinerPattern::FMLSv4f16_OP2: 5782 RC = &AArch64::FPR64RegClass; 5783 Opc = AArch64::FMLSv4f16; 5784 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5785 FMAInstKind::Accumulator); 5786 break; 5787 case MachineCombinerPattern::FMLSv4i16_indexed_OP2: 5788 RC = &AArch64::FPR64RegClass; 5789 Opc = AArch64::FMLSv4i16_indexed; 5790 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5791 FMAInstKind::Indexed); 5792 break; 5793 5794 case MachineCombinerPattern::FMLSv2f32_OP2: 5795 case MachineCombinerPattern::FMLSv2i32_indexed_OP2: 5796 RC = &AArch64::FPR64RegClass; 5797 if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP2) { 5798 Opc = AArch64::FMLSv2i32_indexed; 5799 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5800 FMAInstKind::Indexed); 5801 } else { 5802 Opc = AArch64::FMLSv2f32; 5803 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5804 FMAInstKind::Accumulator); 5805 } 5806 break; 5807 5808 case MachineCombinerPattern::FMLSv8f16_OP1: 5809 case MachineCombinerPattern::FMLSv8i16_indexed_OP1: { 5810 RC = &AArch64::FPR128RegClass; 5811 Register NewVR = MRI.createVirtualRegister(RC); 5812 MachineInstrBuilder MIB1 = 5813 BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv8f16), NewVR) 5814 .add(Root.getOperand(2)); 5815 InsInstrs.push_back(MIB1); 5816 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5817 if (Pattern == MachineCombinerPattern::FMLSv8f16_OP1) { 5818 Opc = AArch64::FMLAv8f16; 5819 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5820 FMAInstKind::Accumulator, &NewVR); 5821 } else { 5822 Opc = AArch64::FMLAv8i16_indexed; 5823 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5824 FMAInstKind::Indexed, &NewVR); 5825 } 5826 break; 5827 } 5828 case MachineCombinerPattern::FMLSv8f16_OP2: 5829 RC = &AArch64::FPR128RegClass; 5830 Opc = AArch64::FMLSv8f16; 5831 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5832 FMAInstKind::Accumulator); 5833 break; 5834 case MachineCombinerPattern::FMLSv8i16_indexed_OP2: 5835 RC = &AArch64::FPR128RegClass; 5836 Opc = AArch64::FMLSv8i16_indexed; 5837 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5838 FMAInstKind::Indexed); 5839 break; 5840 5841 case MachineCombinerPattern::FMLSv2f64_OP2: 5842 case MachineCombinerPattern::FMLSv2i64_indexed_OP2: 5843 RC = &AArch64::FPR128RegClass; 5844 if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP2) { 5845 Opc = AArch64::FMLSv2i64_indexed; 5846 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5847 FMAInstKind::Indexed); 5848 } else { 5849 Opc = AArch64::FMLSv2f64; 5850 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5851 FMAInstKind::Accumulator); 5852 } 5853 break; 5854 5855 case MachineCombinerPattern::FMLSv4f32_OP2: 5856 case MachineCombinerPattern::FMLSv4i32_indexed_OP2: 5857 RC = &AArch64::FPR128RegClass; 5858 if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP2) { 5859 Opc = AArch64::FMLSv4i32_indexed; 5860 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5861 FMAInstKind::Indexed); 5862 } else { 5863 Opc = AArch64::FMLSv4f32; 5864 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC, 5865 FMAInstKind::Accumulator); 5866 } 5867 break; 5868 case MachineCombinerPattern::FMLSv2f32_OP1: 5869 case MachineCombinerPattern::FMLSv2i32_indexed_OP1: { 5870 RC = &AArch64::FPR64RegClass; 5871 Register NewVR = MRI.createVirtualRegister(RC); 5872 MachineInstrBuilder MIB1 = 5873 BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv2f32), NewVR) 5874 .add(Root.getOperand(2)); 5875 InsInstrs.push_back(MIB1); 5876 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5877 if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP1) { 5878 Opc = AArch64::FMLAv2i32_indexed; 5879 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5880 FMAInstKind::Indexed, &NewVR); 5881 } else { 5882 Opc = AArch64::FMLAv2f32; 5883 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5884 FMAInstKind::Accumulator, &NewVR); 5885 } 5886 break; 5887 } 5888 case MachineCombinerPattern::FMLSv4f32_OP1: 5889 case MachineCombinerPattern::FMLSv4i32_indexed_OP1: { 5890 RC = &AArch64::FPR128RegClass; 5891 Register NewVR = MRI.createVirtualRegister(RC); 5892 MachineInstrBuilder MIB1 = 5893 BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv4f32), NewVR) 5894 .add(Root.getOperand(2)); 5895 InsInstrs.push_back(MIB1); 5896 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5897 if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP1) { 5898 Opc = AArch64::FMLAv4i32_indexed; 5899 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5900 FMAInstKind::Indexed, &NewVR); 5901 } else { 5902 Opc = AArch64::FMLAv4f32; 5903 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5904 FMAInstKind::Accumulator, &NewVR); 5905 } 5906 break; 5907 } 5908 case MachineCombinerPattern::FMLSv2f64_OP1: 5909 case MachineCombinerPattern::FMLSv2i64_indexed_OP1: { 5910 RC = &AArch64::FPR128RegClass; 5911 Register NewVR = MRI.createVirtualRegister(RC); 5912 MachineInstrBuilder MIB1 = 5913 BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv2f64), NewVR) 5914 .add(Root.getOperand(2)); 5915 InsInstrs.push_back(MIB1); 5916 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 5917 if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP1) { 5918 Opc = AArch64::FMLAv2i64_indexed; 5919 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5920 FMAInstKind::Indexed, &NewVR); 5921 } else { 5922 Opc = AArch64::FMLAv2f64; 5923 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC, 5924 FMAInstKind::Accumulator, &NewVR); 5925 } 5926 break; 5927 } 5928 } // end switch (Pattern) 5929 // Record MUL and ADD/SUB for deletion 5930 // FIXME: This assertion fails in CodeGen/AArch64/tailmerging_in_mbp.ll and 5931 // CodeGen/AArch64/urem-seteq-nonzero.ll. 5932 // assert(MUL && "MUL was never set"); 5933 DelInstrs.push_back(MUL); 5934 DelInstrs.push_back(&Root); 5935 } 5936 5937 /// Replace csincr-branch sequence by simple conditional branch 5938 /// 5939 /// Examples: 5940 /// 1. \code 5941 /// csinc w9, wzr, wzr, <condition code> 5942 /// tbnz w9, #0, 0x44 5943 /// \endcode 5944 /// to 5945 /// \code 5946 /// b.<inverted condition code> 5947 /// \endcode 5948 /// 5949 /// 2. \code 5950 /// csinc w9, wzr, wzr, <condition code> 5951 /// tbz w9, #0, 0x44 5952 /// \endcode 5953 /// to 5954 /// \code 5955 /// b.<condition code> 5956 /// \endcode 5957 /// 5958 /// Replace compare and branch sequence by TBZ/TBNZ instruction when the 5959 /// compare's constant operand is power of 2. 5960 /// 5961 /// Examples: 5962 /// \code 5963 /// and w8, w8, #0x400 5964 /// cbnz w8, L1 5965 /// \endcode 5966 /// to 5967 /// \code 5968 /// tbnz w8, #10, L1 5969 /// \endcode 5970 /// 5971 /// \param MI Conditional Branch 5972 /// \return True when the simple conditional branch is generated 5973 /// 5974 bool AArch64InstrInfo::optimizeCondBranch(MachineInstr &MI) const { 5975 bool IsNegativeBranch = false; 5976 bool IsTestAndBranch = false; 5977 unsigned TargetBBInMI = 0; 5978 switch (MI.getOpcode()) { 5979 default: 5980 llvm_unreachable("Unknown branch instruction?"); 5981 case AArch64::Bcc: 5982 return false; 5983 case AArch64::CBZW: 5984 case AArch64::CBZX: 5985 TargetBBInMI = 1; 5986 break; 5987 case AArch64::CBNZW: 5988 case AArch64::CBNZX: 5989 TargetBBInMI = 1; 5990 IsNegativeBranch = true; 5991 break; 5992 case AArch64::TBZW: 5993 case AArch64::TBZX: 5994 TargetBBInMI = 2; 5995 IsTestAndBranch = true; 5996 break; 5997 case AArch64::TBNZW: 5998 case AArch64::TBNZX: 5999 TargetBBInMI = 2; 6000 IsNegativeBranch = true; 6001 IsTestAndBranch = true; 6002 break; 6003 } 6004 // So we increment a zero register and test for bits other 6005 // than bit 0? Conservatively bail out in case the verifier 6006 // missed this case. 6007 if (IsTestAndBranch && MI.getOperand(1).getImm()) 6008 return false; 6009 6010 // Find Definition. 6011 assert(MI.getParent() && "Incomplete machine instruciton\n"); 6012 MachineBasicBlock *MBB = MI.getParent(); 6013 MachineFunction *MF = MBB->getParent(); 6014 MachineRegisterInfo *MRI = &MF->getRegInfo(); 6015 Register VReg = MI.getOperand(0).getReg(); 6016 if (!Register::isVirtualRegister(VReg)) 6017 return false; 6018 6019 MachineInstr *DefMI = MRI->getVRegDef(VReg); 6020 6021 // Look through COPY instructions to find definition. 6022 while (DefMI->isCopy()) { 6023 Register CopyVReg = DefMI->getOperand(1).getReg(); 6024 if (!MRI->hasOneNonDBGUse(CopyVReg)) 6025 return false; 6026 if (!MRI->hasOneDef(CopyVReg)) 6027 return false; 6028 DefMI = MRI->getVRegDef(CopyVReg); 6029 } 6030 6031 switch (DefMI->getOpcode()) { 6032 default: 6033 return false; 6034 // Fold AND into a TBZ/TBNZ if constant operand is power of 2. 6035 case AArch64::ANDWri: 6036 case AArch64::ANDXri: { 6037 if (IsTestAndBranch) 6038 return false; 6039 if (DefMI->getParent() != MBB) 6040 return false; 6041 if (!MRI->hasOneNonDBGUse(VReg)) 6042 return false; 6043 6044 bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri); 6045 uint64_t Mask = AArch64_AM::decodeLogicalImmediate( 6046 DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64); 6047 if (!isPowerOf2_64(Mask)) 6048 return false; 6049 6050 MachineOperand &MO = DefMI->getOperand(1); 6051 Register NewReg = MO.getReg(); 6052 if (!Register::isVirtualRegister(NewReg)) 6053 return false; 6054 6055 assert(!MRI->def_empty(NewReg) && "Register must be defined."); 6056 6057 MachineBasicBlock &RefToMBB = *MBB; 6058 MachineBasicBlock *TBB = MI.getOperand(1).getMBB(); 6059 DebugLoc DL = MI.getDebugLoc(); 6060 unsigned Imm = Log2_64(Mask); 6061 unsigned Opc = (Imm < 32) 6062 ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW) 6063 : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX); 6064 MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc)) 6065 .addReg(NewReg) 6066 .addImm(Imm) 6067 .addMBB(TBB); 6068 // Register lives on to the CBZ now. 6069 MO.setIsKill(false); 6070 6071 // For immediate smaller than 32, we need to use the 32-bit 6072 // variant (W) in all cases. Indeed the 64-bit variant does not 6073 // allow to encode them. 6074 // Therefore, if the input register is 64-bit, we need to take the 6075 // 32-bit sub-part. 6076 if (!Is32Bit && Imm < 32) 6077 NewMI->getOperand(0).setSubReg(AArch64::sub_32); 6078 MI.eraseFromParent(); 6079 return true; 6080 } 6081 // Look for CSINC 6082 case AArch64::CSINCWr: 6083 case AArch64::CSINCXr: { 6084 if (!(DefMI->getOperand(1).getReg() == AArch64::WZR && 6085 DefMI->getOperand(2).getReg() == AArch64::WZR) && 6086 !(DefMI->getOperand(1).getReg() == AArch64::XZR && 6087 DefMI->getOperand(2).getReg() == AArch64::XZR)) 6088 return false; 6089 6090 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) != -1) 6091 return false; 6092 6093 AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm(); 6094 // Convert only when the condition code is not modified between 6095 // the CSINC and the branch. The CC may be used by other 6096 // instructions in between. 6097 if (areCFlagsAccessedBetweenInstrs(DefMI, MI, &getRegisterInfo(), AK_Write)) 6098 return false; 6099 MachineBasicBlock &RefToMBB = *MBB; 6100 MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB(); 6101 DebugLoc DL = MI.getDebugLoc(); 6102 if (IsNegativeBranch) 6103 CC = AArch64CC::getInvertedCondCode(CC); 6104 BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB); 6105 MI.eraseFromParent(); 6106 return true; 6107 } 6108 } 6109 } 6110 6111 std::pair<unsigned, unsigned> 6112 AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const { 6113 const unsigned Mask = AArch64II::MO_FRAGMENT; 6114 return std::make_pair(TF & Mask, TF & ~Mask); 6115 } 6116 6117 ArrayRef<std::pair<unsigned, const char *>> 6118 AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const { 6119 using namespace AArch64II; 6120 6121 static const std::pair<unsigned, const char *> TargetFlags[] = { 6122 {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"}, 6123 {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"}, 6124 {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"}, 6125 {MO_HI12, "aarch64-hi12"}}; 6126 return makeArrayRef(TargetFlags); 6127 } 6128 6129 ArrayRef<std::pair<unsigned, const char *>> 6130 AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const { 6131 using namespace AArch64II; 6132 6133 static const std::pair<unsigned, const char *> TargetFlags[] = { 6134 {MO_COFFSTUB, "aarch64-coffstub"}, 6135 {MO_GOT, "aarch64-got"}, 6136 {MO_NC, "aarch64-nc"}, 6137 {MO_S, "aarch64-s"}, 6138 {MO_TLS, "aarch64-tls"}, 6139 {MO_DLLIMPORT, "aarch64-dllimport"}, 6140 {MO_PREL, "aarch64-prel"}, 6141 {MO_TAGGED, "aarch64-tagged"}}; 6142 return makeArrayRef(TargetFlags); 6143 } 6144 6145 ArrayRef<std::pair<MachineMemOperand::Flags, const char *>> 6146 AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const { 6147 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] = 6148 {{MOSuppressPair, "aarch64-suppress-pair"}, 6149 {MOStridedAccess, "aarch64-strided-access"}}; 6150 return makeArrayRef(TargetFlags); 6151 } 6152 6153 /// Constants defining how certain sequences should be outlined. 6154 /// This encompasses how an outlined function should be called, and what kind of 6155 /// frame should be emitted for that outlined function. 6156 /// 6157 /// \p MachineOutlinerDefault implies that the function should be called with 6158 /// a save and restore of LR to the stack. 6159 /// 6160 /// That is, 6161 /// 6162 /// I1 Save LR OUTLINED_FUNCTION: 6163 /// I2 --> BL OUTLINED_FUNCTION I1 6164 /// I3 Restore LR I2 6165 /// I3 6166 /// RET 6167 /// 6168 /// * Call construction overhead: 3 (save + BL + restore) 6169 /// * Frame construction overhead: 1 (ret) 6170 /// * Requires stack fixups? Yes 6171 /// 6172 /// \p MachineOutlinerTailCall implies that the function is being created from 6173 /// a sequence of instructions ending in a return. 6174 /// 6175 /// That is, 6176 /// 6177 /// I1 OUTLINED_FUNCTION: 6178 /// I2 --> B OUTLINED_FUNCTION I1 6179 /// RET I2 6180 /// RET 6181 /// 6182 /// * Call construction overhead: 1 (B) 6183 /// * Frame construction overhead: 0 (Return included in sequence) 6184 /// * Requires stack fixups? No 6185 /// 6186 /// \p MachineOutlinerNoLRSave implies that the function should be called using 6187 /// a BL instruction, but doesn't require LR to be saved and restored. This 6188 /// happens when LR is known to be dead. 6189 /// 6190 /// That is, 6191 /// 6192 /// I1 OUTLINED_FUNCTION: 6193 /// I2 --> BL OUTLINED_FUNCTION I1 6194 /// I3 I2 6195 /// I3 6196 /// RET 6197 /// 6198 /// * Call construction overhead: 1 (BL) 6199 /// * Frame construction overhead: 1 (RET) 6200 /// * Requires stack fixups? No 6201 /// 6202 /// \p MachineOutlinerThunk implies that the function is being created from 6203 /// a sequence of instructions ending in a call. The outlined function is 6204 /// called with a BL instruction, and the outlined function tail-calls the 6205 /// original call destination. 6206 /// 6207 /// That is, 6208 /// 6209 /// I1 OUTLINED_FUNCTION: 6210 /// I2 --> BL OUTLINED_FUNCTION I1 6211 /// BL f I2 6212 /// B f 6213 /// * Call construction overhead: 1 (BL) 6214 /// * Frame construction overhead: 0 6215 /// * Requires stack fixups? No 6216 /// 6217 /// \p MachineOutlinerRegSave implies that the function should be called with a 6218 /// save and restore of LR to an available register. This allows us to avoid 6219 /// stack fixups. Note that this outlining variant is compatible with the 6220 /// NoLRSave case. 6221 /// 6222 /// That is, 6223 /// 6224 /// I1 Save LR OUTLINED_FUNCTION: 6225 /// I2 --> BL OUTLINED_FUNCTION I1 6226 /// I3 Restore LR I2 6227 /// I3 6228 /// RET 6229 /// 6230 /// * Call construction overhead: 3 (save + BL + restore) 6231 /// * Frame construction overhead: 1 (ret) 6232 /// * Requires stack fixups? No 6233 enum MachineOutlinerClass { 6234 MachineOutlinerDefault, /// Emit a save, restore, call, and return. 6235 MachineOutlinerTailCall, /// Only emit a branch. 6236 MachineOutlinerNoLRSave, /// Emit a call and return. 6237 MachineOutlinerThunk, /// Emit a call and tail-call. 6238 MachineOutlinerRegSave /// Same as default, but save to a register. 6239 }; 6240 6241 enum MachineOutlinerMBBFlags { 6242 LRUnavailableSomewhere = 0x2, 6243 HasCalls = 0x4, 6244 UnsafeRegsDead = 0x8 6245 }; 6246 6247 unsigned 6248 AArch64InstrInfo::findRegisterToSaveLRTo(const outliner::Candidate &C) const { 6249 assert(C.LRUWasSet && "LRU wasn't set?"); 6250 MachineFunction *MF = C.getMF(); 6251 const AArch64RegisterInfo *ARI = static_cast<const AArch64RegisterInfo *>( 6252 MF->getSubtarget().getRegisterInfo()); 6253 6254 // Check if there is an available register across the sequence that we can 6255 // use. 6256 for (unsigned Reg : AArch64::GPR64RegClass) { 6257 if (!ARI->isReservedReg(*MF, Reg) && 6258 Reg != AArch64::LR && // LR is not reserved, but don't use it. 6259 Reg != AArch64::X16 && // X16 is not guaranteed to be preserved. 6260 Reg != AArch64::X17 && // Ditto for X17. 6261 C.LRU.available(Reg) && C.UsedInSequence.available(Reg)) 6262 return Reg; 6263 } 6264 6265 // No suitable register. Return 0. 6266 return 0u; 6267 } 6268 6269 static bool 6270 outliningCandidatesSigningScopeConsensus(const outliner::Candidate &a, 6271 const outliner::Candidate &b) { 6272 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>(); 6273 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>(); 6274 6275 return MFIa->shouldSignReturnAddress(false) == MFIb->shouldSignReturnAddress(false) && 6276 MFIa->shouldSignReturnAddress(true) == MFIb->shouldSignReturnAddress(true); 6277 } 6278 6279 static bool 6280 outliningCandidatesSigningKeyConsensus(const outliner::Candidate &a, 6281 const outliner::Candidate &b) { 6282 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>(); 6283 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>(); 6284 6285 return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey(); 6286 } 6287 6288 static bool outliningCandidatesV8_3OpsConsensus(const outliner::Candidate &a, 6289 const outliner::Candidate &b) { 6290 const AArch64Subtarget &SubtargetA = 6291 a.getMF()->getSubtarget<AArch64Subtarget>(); 6292 const AArch64Subtarget &SubtargetB = 6293 b.getMF()->getSubtarget<AArch64Subtarget>(); 6294 return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps(); 6295 } 6296 6297 outliner::OutlinedFunction AArch64InstrInfo::getOutliningCandidateInfo( 6298 std::vector<outliner::Candidate> &RepeatedSequenceLocs) const { 6299 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0]; 6300 unsigned SequenceSize = 6301 std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0, 6302 [this](unsigned Sum, const MachineInstr &MI) { 6303 return Sum + getInstSizeInBytes(MI); 6304 }); 6305 unsigned NumBytesToCreateFrame = 0; 6306 6307 // We only allow outlining for functions having exactly matching return 6308 // address signing attributes, i.e., all share the same value for the 6309 // attribute "sign-return-address" and all share the same type of key they 6310 // are signed with. 6311 // Additionally we require all functions to simultaniously either support 6312 // v8.3a features or not. Otherwise an outlined function could get signed 6313 // using dedicated v8.3 instructions and a call from a function that doesn't 6314 // support v8.3 instructions would therefore be invalid. 6315 if (std::adjacent_find( 6316 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(), 6317 [](const outliner::Candidate &a, const outliner::Candidate &b) { 6318 // Return true if a and b are non-equal w.r.t. return address 6319 // signing or support of v8.3a features 6320 if (outliningCandidatesSigningScopeConsensus(a, b) && 6321 outliningCandidatesSigningKeyConsensus(a, b) && 6322 outliningCandidatesV8_3OpsConsensus(a, b)) { 6323 return false; 6324 } 6325 return true; 6326 }) != RepeatedSequenceLocs.end()) { 6327 return outliner::OutlinedFunction(); 6328 } 6329 6330 // Since at this point all candidates agree on their return address signing 6331 // picking just one is fine. If the candidate functions potentially sign their 6332 // return addresses, the outlined function should do the same. Note that in 6333 // the case of "sign-return-address"="non-leaf" this is an assumption: It is 6334 // not certainly true that the outlined function will have to sign its return 6335 // address but this decision is made later, when the decision to outline 6336 // has already been made. 6337 // The same holds for the number of additional instructions we need: On 6338 // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is 6339 // necessary. However, at this point we don't know if the outlined function 6340 // will have a RET instruction so we assume the worst. 6341 const TargetRegisterInfo &TRI = getRegisterInfo(); 6342 if (FirstCand.getMF() 6343 ->getInfo<AArch64FunctionInfo>() 6344 ->shouldSignReturnAddress(true)) { 6345 // One PAC and one AUT instructions 6346 NumBytesToCreateFrame += 8; 6347 6348 // We have to check if sp modifying instructions would get outlined. 6349 // If so we only allow outlining if sp is unchanged overall, so matching 6350 // sub and add instructions are okay to outline, all other sp modifications 6351 // are not 6352 auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) { 6353 int SPValue = 0; 6354 MachineBasicBlock::iterator MBBI = C.front(); 6355 for (;;) { 6356 if (MBBI->modifiesRegister(AArch64::SP, &TRI)) { 6357 switch (MBBI->getOpcode()) { 6358 case AArch64::ADDXri: 6359 case AArch64::ADDWri: 6360 assert(MBBI->getNumOperands() == 4 && "Wrong number of operands"); 6361 assert(MBBI->getOperand(2).isImm() && 6362 "Expected operand to be immediate"); 6363 assert(MBBI->getOperand(1).isReg() && 6364 "Expected operand to be a register"); 6365 // Check if the add just increments sp. If so, we search for 6366 // matching sub instructions that decrement sp. If not, the 6367 // modification is illegal 6368 if (MBBI->getOperand(1).getReg() == AArch64::SP) 6369 SPValue += MBBI->getOperand(2).getImm(); 6370 else 6371 return true; 6372 break; 6373 case AArch64::SUBXri: 6374 case AArch64::SUBWri: 6375 assert(MBBI->getNumOperands() == 4 && "Wrong number of operands"); 6376 assert(MBBI->getOperand(2).isImm() && 6377 "Expected operand to be immediate"); 6378 assert(MBBI->getOperand(1).isReg() && 6379 "Expected operand to be a register"); 6380 // Check if the sub just decrements sp. If so, we search for 6381 // matching add instructions that increment sp. If not, the 6382 // modification is illegal 6383 if (MBBI->getOperand(1).getReg() == AArch64::SP) 6384 SPValue -= MBBI->getOperand(2).getImm(); 6385 else 6386 return true; 6387 break; 6388 default: 6389 return true; 6390 } 6391 } 6392 if (MBBI == C.back()) 6393 break; 6394 ++MBBI; 6395 } 6396 if (SPValue) 6397 return true; 6398 return false; 6399 }; 6400 // Remove candidates with illegal stack modifying instructions 6401 llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification); 6402 6403 // If the sequence doesn't have enough candidates left, then we're done. 6404 if (RepeatedSequenceLocs.size() < 2) 6405 return outliner::OutlinedFunction(); 6406 } 6407 6408 // Properties about candidate MBBs that hold for all of them. 6409 unsigned FlagsSetInAll = 0xF; 6410 6411 // Compute liveness information for each candidate, and set FlagsSetInAll. 6412 std::for_each(RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(), 6413 [&FlagsSetInAll](outliner::Candidate &C) { 6414 FlagsSetInAll &= C.Flags; 6415 }); 6416 6417 // According to the AArch64 Procedure Call Standard, the following are 6418 // undefined on entry/exit from a function call: 6419 // 6420 // * Registers x16, x17, (and thus w16, w17) 6421 // * Condition codes (and thus the NZCV register) 6422 // 6423 // Because if this, we can't outline any sequence of instructions where 6424 // one 6425 // of these registers is live into/across it. Thus, we need to delete 6426 // those 6427 // candidates. 6428 auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) { 6429 // If the unsafe registers in this block are all dead, then we don't need 6430 // to compute liveness here. 6431 if (C.Flags & UnsafeRegsDead) 6432 return false; 6433 C.initLRU(TRI); 6434 LiveRegUnits LRU = C.LRU; 6435 return (!LRU.available(AArch64::W16) || !LRU.available(AArch64::W17) || 6436 !LRU.available(AArch64::NZCV)); 6437 }; 6438 6439 // Are there any candidates where those registers are live? 6440 if (!(FlagsSetInAll & UnsafeRegsDead)) { 6441 // Erase every candidate that violates the restrictions above. (It could be 6442 // true that we have viable candidates, so it's not worth bailing out in 6443 // the case that, say, 1 out of 20 candidates violate the restructions.) 6444 llvm::erase_if(RepeatedSequenceLocs, CantGuaranteeValueAcrossCall); 6445 6446 // If the sequence doesn't have enough candidates left, then we're done. 6447 if (RepeatedSequenceLocs.size() < 2) 6448 return outliner::OutlinedFunction(); 6449 } 6450 6451 // At this point, we have only "safe" candidates to outline. Figure out 6452 // frame + call instruction information. 6453 6454 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode(); 6455 6456 // Helper lambda which sets call information for every candidate. 6457 auto SetCandidateCallInfo = 6458 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) { 6459 for (outliner::Candidate &C : RepeatedSequenceLocs) 6460 C.setCallInfo(CallID, NumBytesForCall); 6461 }; 6462 6463 unsigned FrameID = MachineOutlinerDefault; 6464 NumBytesToCreateFrame += 4; 6465 6466 bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) { 6467 return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement(); 6468 }); 6469 6470 // We check to see if CFI Instructions are present, and if they are 6471 // we find the number of CFI Instructions in the candidates. 6472 unsigned CFICount = 0; 6473 MachineBasicBlock::iterator MBBI = RepeatedSequenceLocs[0].front(); 6474 for (unsigned Loc = RepeatedSequenceLocs[0].getStartIdx(); 6475 Loc < RepeatedSequenceLocs[0].getEndIdx() + 1; Loc++) { 6476 const std::vector<MCCFIInstruction> &CFIInstructions = 6477 RepeatedSequenceLocs[0].getMF()->getFrameInstructions(); 6478 if (MBBI->isCFIInstruction()) { 6479 unsigned CFIIndex = MBBI->getOperand(0).getCFIIndex(); 6480 MCCFIInstruction CFI = CFIInstructions[CFIIndex]; 6481 CFICount++; 6482 } 6483 MBBI++; 6484 } 6485 6486 // We compare the number of found CFI Instructions to the number of CFI 6487 // instructions in the parent function for each candidate. We must check this 6488 // since if we outline one of the CFI instructions in a function, we have to 6489 // outline them all for correctness. If we do not, the address offsets will be 6490 // incorrect between the two sections of the program. 6491 for (outliner::Candidate &C : RepeatedSequenceLocs) { 6492 std::vector<MCCFIInstruction> CFIInstructions = 6493 C.getMF()->getFrameInstructions(); 6494 6495 if (CFICount > 0 && CFICount != CFIInstructions.size()) 6496 return outliner::OutlinedFunction(); 6497 } 6498 6499 // Returns true if an instructions is safe to fix up, false otherwise. 6500 auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) { 6501 if (MI.isCall()) 6502 return true; 6503 6504 if (!MI.modifiesRegister(AArch64::SP, &TRI) && 6505 !MI.readsRegister(AArch64::SP, &TRI)) 6506 return true; 6507 6508 // Any modification of SP will break our code to save/restore LR. 6509 // FIXME: We could handle some instructions which add a constant 6510 // offset to SP, with a bit more work. 6511 if (MI.modifiesRegister(AArch64::SP, &TRI)) 6512 return false; 6513 6514 // At this point, we have a stack instruction that we might need to 6515 // fix up. We'll handle it if it's a load or store. 6516 if (MI.mayLoadOrStore()) { 6517 const MachineOperand *Base; // Filled with the base operand of MI. 6518 int64_t Offset; // Filled with the offset of MI. 6519 bool OffsetIsScalable; 6520 6521 // Does it allow us to offset the base operand and is the base the 6522 // register SP? 6523 if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable, &TRI) || 6524 !Base->isReg() || Base->getReg() != AArch64::SP) 6525 return false; 6526 6527 // Fixe-up code below assumes bytes. 6528 if (OffsetIsScalable) 6529 return false; 6530 6531 // Find the minimum/maximum offset for this instruction and check 6532 // if fixing it up would be in range. 6533 int64_t MinOffset, 6534 MaxOffset; // Unscaled offsets for the instruction. 6535 TypeSize Scale(0U, false); // The scale to multiply the offsets by. 6536 unsigned DummyWidth; 6537 getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset); 6538 6539 Offset += 16; // Update the offset to what it would be if we outlined. 6540 if (Offset < MinOffset * (int64_t)Scale.getFixedSize() || 6541 Offset > MaxOffset * (int64_t)Scale.getFixedSize()) 6542 return false; 6543 6544 // It's in range, so we can outline it. 6545 return true; 6546 } 6547 6548 // FIXME: Add handling for instructions like "add x0, sp, #8". 6549 6550 // We can't fix it up, so don't outline it. 6551 return false; 6552 }; 6553 6554 // True if it's possible to fix up each stack instruction in this sequence. 6555 // Important for frames/call variants that modify the stack. 6556 bool AllStackInstrsSafe = std::all_of( 6557 FirstCand.front(), std::next(FirstCand.back()), IsSafeToFixup); 6558 6559 // If the last instruction in any candidate is a terminator, then we should 6560 // tail call all of the candidates. 6561 if (RepeatedSequenceLocs[0].back()->isTerminator()) { 6562 FrameID = MachineOutlinerTailCall; 6563 NumBytesToCreateFrame = 0; 6564 SetCandidateCallInfo(MachineOutlinerTailCall, 4); 6565 } 6566 6567 else if (LastInstrOpcode == AArch64::BL || 6568 ((LastInstrOpcode == AArch64::BLR || 6569 LastInstrOpcode == AArch64::BLRNoIP) && 6570 !HasBTI)) { 6571 // FIXME: Do we need to check if the code after this uses the value of LR? 6572 FrameID = MachineOutlinerThunk; 6573 NumBytesToCreateFrame = 0; 6574 SetCandidateCallInfo(MachineOutlinerThunk, 4); 6575 } 6576 6577 else { 6578 // We need to decide how to emit calls + frames. We can always emit the same 6579 // frame if we don't need to save to the stack. If we have to save to the 6580 // stack, then we need a different frame. 6581 unsigned NumBytesNoStackCalls = 0; 6582 std::vector<outliner::Candidate> CandidatesWithoutStackFixups; 6583 6584 // Check if we have to save LR. 6585 for (outliner::Candidate &C : RepeatedSequenceLocs) { 6586 C.initLRU(TRI); 6587 6588 // If we have a noreturn caller, then we're going to be conservative and 6589 // say that we have to save LR. If we don't have a ret at the end of the 6590 // block, then we can't reason about liveness accurately. 6591 // 6592 // FIXME: We can probably do better than always disabling this in 6593 // noreturn functions by fixing up the liveness info. 6594 bool IsNoReturn = 6595 C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn); 6596 6597 // Is LR available? If so, we don't need a save. 6598 if (C.LRU.available(AArch64::LR) && !IsNoReturn) { 6599 NumBytesNoStackCalls += 4; 6600 C.setCallInfo(MachineOutlinerNoLRSave, 4); 6601 CandidatesWithoutStackFixups.push_back(C); 6602 } 6603 6604 // Is an unused register available? If so, we won't modify the stack, so 6605 // we can outline with the same frame type as those that don't save LR. 6606 else if (findRegisterToSaveLRTo(C)) { 6607 NumBytesNoStackCalls += 12; 6608 C.setCallInfo(MachineOutlinerRegSave, 12); 6609 CandidatesWithoutStackFixups.push_back(C); 6610 } 6611 6612 // Is SP used in the sequence at all? If not, we don't have to modify 6613 // the stack, so we are guaranteed to get the same frame. 6614 else if (C.UsedInSequence.available(AArch64::SP)) { 6615 NumBytesNoStackCalls += 12; 6616 C.setCallInfo(MachineOutlinerDefault, 12); 6617 CandidatesWithoutStackFixups.push_back(C); 6618 } 6619 6620 // If we outline this, we need to modify the stack. Pretend we don't 6621 // outline this by saving all of its bytes. 6622 else { 6623 NumBytesNoStackCalls += SequenceSize; 6624 } 6625 } 6626 6627 // If there are no places where we have to save LR, then note that we 6628 // don't have to update the stack. Otherwise, give every candidate the 6629 // default call type, as long as it's safe to do so. 6630 if (!AllStackInstrsSafe || 6631 NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) { 6632 RepeatedSequenceLocs = CandidatesWithoutStackFixups; 6633 FrameID = MachineOutlinerNoLRSave; 6634 } else { 6635 SetCandidateCallInfo(MachineOutlinerDefault, 12); 6636 6637 // Bugzilla ID: 46767 6638 // TODO: Check if fixing up the stack more than once is safe so we can 6639 // outline these. 6640 // 6641 // An outline resulting in a caller that requires stack fixups at the 6642 // callsite to a callee that also requires stack fixups can happen when 6643 // there are no available registers at the candidate callsite for a 6644 // candidate that itself also has calls. 6645 // 6646 // In other words if function_containing_sequence in the following pseudo 6647 // assembly requires that we save LR at the point of the call, but there 6648 // are no available registers: in this case we save using SP and as a 6649 // result the SP offsets requires stack fixups by multiples of 16. 6650 // 6651 // function_containing_sequence: 6652 // ... 6653 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N 6654 // call OUTLINED_FUNCTION_N 6655 // restore LR from SP 6656 // ... 6657 // 6658 // OUTLINED_FUNCTION_N: 6659 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N 6660 // ... 6661 // bl foo 6662 // restore LR from SP 6663 // ret 6664 // 6665 // Because the code to handle more than one stack fixup does not 6666 // currently have the proper checks for legality, these cases will assert 6667 // in the AArch64 MachineOutliner. This is because the code to do this 6668 // needs more hardening, testing, better checks that generated code is 6669 // legal, etc and because it is only verified to handle a single pass of 6670 // stack fixup. 6671 // 6672 // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch 6673 // these cases until they are known to be handled. Bugzilla 46767 is 6674 // referenced in comments at the assert site. 6675 // 6676 // To avoid asserting (or generating non-legal code on noassert builds) 6677 // we remove all candidates which would need more than one stack fixup by 6678 // pruning the cases where the candidate has calls while also having no 6679 // available LR and having no available general purpose registers to copy 6680 // LR to (ie one extra stack save/restore). 6681 // 6682 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) { 6683 erase_if(RepeatedSequenceLocs, [this](outliner::Candidate &C) { 6684 return (std::any_of( 6685 C.front(), std::next(C.back()), 6686 [](const MachineInstr &MI) { return MI.isCall(); })) && 6687 (!C.LRU.available(AArch64::LR) || !findRegisterToSaveLRTo(C)); 6688 }); 6689 } 6690 } 6691 6692 // If we dropped all of the candidates, bail out here. 6693 if (RepeatedSequenceLocs.size() < 2) { 6694 RepeatedSequenceLocs.clear(); 6695 return outliner::OutlinedFunction(); 6696 } 6697 } 6698 6699 // Does every candidate's MBB contain a call? If so, then we might have a call 6700 // in the range. 6701 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) { 6702 // Check if the range contains a call. These require a save + restore of the 6703 // link register. 6704 bool ModStackToSaveLR = false; 6705 if (std::any_of(FirstCand.front(), FirstCand.back(), 6706 [](const MachineInstr &MI) { return MI.isCall(); })) 6707 ModStackToSaveLR = true; 6708 6709 // Handle the last instruction separately. If this is a tail call, then the 6710 // last instruction is a call. We don't want to save + restore in this case. 6711 // However, it could be possible that the last instruction is a call without 6712 // it being valid to tail call this sequence. We should consider this as 6713 // well. 6714 else if (FrameID != MachineOutlinerThunk && 6715 FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall()) 6716 ModStackToSaveLR = true; 6717 6718 if (ModStackToSaveLR) { 6719 // We can't fix up the stack. Bail out. 6720 if (!AllStackInstrsSafe) { 6721 RepeatedSequenceLocs.clear(); 6722 return outliner::OutlinedFunction(); 6723 } 6724 6725 // Save + restore LR. 6726 NumBytesToCreateFrame += 8; 6727 } 6728 } 6729 6730 // If we have CFI instructions, we can only outline if the outlined section 6731 // can be a tail call 6732 if (FrameID != MachineOutlinerTailCall && CFICount > 0) 6733 return outliner::OutlinedFunction(); 6734 6735 return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize, 6736 NumBytesToCreateFrame, FrameID); 6737 } 6738 6739 bool AArch64InstrInfo::isFunctionSafeToOutlineFrom( 6740 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const { 6741 const Function &F = MF.getFunction(); 6742 6743 // Can F be deduplicated by the linker? If it can, don't outline from it. 6744 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage()) 6745 return false; 6746 6747 // Don't outline from functions with section markings; the program could 6748 // expect that all the code is in the named section. 6749 // FIXME: Allow outlining from multiple functions with the same section 6750 // marking. 6751 if (F.hasSection()) 6752 return false; 6753 6754 // Outlining from functions with redzones is unsafe since the outliner may 6755 // modify the stack. Check if hasRedZone is true or unknown; if yes, don't 6756 // outline from it. 6757 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 6758 if (!AFI || AFI->hasRedZone().getValueOr(true)) 6759 return false; 6760 6761 // FIXME: Teach the outliner to generate/handle Windows unwind info. 6762 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) 6763 return false; 6764 6765 // It's safe to outline from MF. 6766 return true; 6767 } 6768 6769 bool AArch64InstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB, 6770 unsigned &Flags) const { 6771 // Check if LR is available through all of the MBB. If it's not, then set 6772 // a flag. 6773 assert(MBB.getParent()->getRegInfo().tracksLiveness() && 6774 "Suitable Machine Function for outlining must track liveness"); 6775 LiveRegUnits LRU(getRegisterInfo()); 6776 6777 std::for_each(MBB.rbegin(), MBB.rend(), 6778 [&LRU](MachineInstr &MI) { LRU.accumulate(MI); }); 6779 6780 // Check if each of the unsafe registers are available... 6781 bool W16AvailableInBlock = LRU.available(AArch64::W16); 6782 bool W17AvailableInBlock = LRU.available(AArch64::W17); 6783 bool NZCVAvailableInBlock = LRU.available(AArch64::NZCV); 6784 6785 // If all of these are dead (and not live out), we know we don't have to check 6786 // them later. 6787 if (W16AvailableInBlock && W17AvailableInBlock && NZCVAvailableInBlock) 6788 Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead; 6789 6790 // Now, add the live outs to the set. 6791 LRU.addLiveOuts(MBB); 6792 6793 // If any of these registers is available in the MBB, but also a live out of 6794 // the block, then we know outlining is unsafe. 6795 if (W16AvailableInBlock && !LRU.available(AArch64::W16)) 6796 return false; 6797 if (W17AvailableInBlock && !LRU.available(AArch64::W17)) 6798 return false; 6799 if (NZCVAvailableInBlock && !LRU.available(AArch64::NZCV)) 6800 return false; 6801 6802 // Check if there's a call inside this MachineBasicBlock. If there is, then 6803 // set a flag. 6804 if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); })) 6805 Flags |= MachineOutlinerMBBFlags::HasCalls; 6806 6807 MachineFunction *MF = MBB.getParent(); 6808 6809 // In the event that we outline, we may have to save LR. If there is an 6810 // available register in the MBB, then we'll always save LR there. Check if 6811 // this is true. 6812 bool CanSaveLR = false; 6813 const AArch64RegisterInfo *ARI = static_cast<const AArch64RegisterInfo *>( 6814 MF->getSubtarget().getRegisterInfo()); 6815 6816 // Check if there is an available register across the sequence that we can 6817 // use. 6818 for (unsigned Reg : AArch64::GPR64RegClass) { 6819 if (!ARI->isReservedReg(*MF, Reg) && Reg != AArch64::LR && 6820 Reg != AArch64::X16 && Reg != AArch64::X17 && LRU.available(Reg)) { 6821 CanSaveLR = true; 6822 break; 6823 } 6824 } 6825 6826 // Check if we have a register we can save LR to, and if LR was used 6827 // somewhere. If both of those things are true, then we need to evaluate the 6828 // safety of outlining stack instructions later. 6829 if (!CanSaveLR && !LRU.available(AArch64::LR)) 6830 Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere; 6831 6832 return true; 6833 } 6834 6835 outliner::InstrType 6836 AArch64InstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT, 6837 unsigned Flags) const { 6838 MachineInstr &MI = *MIT; 6839 MachineBasicBlock *MBB = MI.getParent(); 6840 MachineFunction *MF = MBB->getParent(); 6841 AArch64FunctionInfo *FuncInfo = MF->getInfo<AArch64FunctionInfo>(); 6842 6843 // Don't outline anything used for return address signing. The outlined 6844 // function will get signed later if needed 6845 switch (MI.getOpcode()) { 6846 case AArch64::PACIASP: 6847 case AArch64::PACIBSP: 6848 case AArch64::AUTIASP: 6849 case AArch64::AUTIBSP: 6850 case AArch64::RETAA: 6851 case AArch64::RETAB: 6852 case AArch64::EMITBKEY: 6853 return outliner::InstrType::Illegal; 6854 } 6855 6856 // Don't outline LOHs. 6857 if (FuncInfo->getLOHRelated().count(&MI)) 6858 return outliner::InstrType::Illegal; 6859 6860 // We can only outline these if we will tail call the outlined function, or 6861 // fix up the CFI offsets. Currently, CFI instructions are outlined only if 6862 // in a tail call. 6863 // 6864 // FIXME: If the proper fixups for the offset are implemented, this should be 6865 // possible. 6866 if (MI.isCFIInstruction()) 6867 return outliner::InstrType::Legal; 6868 6869 // Don't allow debug values to impact outlining type. 6870 if (MI.isDebugInstr() || MI.isIndirectDebugValue()) 6871 return outliner::InstrType::Invisible; 6872 6873 // At this point, KILL instructions don't really tell us much so we can go 6874 // ahead and skip over them. 6875 if (MI.isKill()) 6876 return outliner::InstrType::Invisible; 6877 6878 // Is this a terminator for a basic block? 6879 if (MI.isTerminator()) { 6880 6881 // Is this the end of a function? 6882 if (MI.getParent()->succ_empty()) 6883 return outliner::InstrType::Legal; 6884 6885 // It's not, so don't outline it. 6886 return outliner::InstrType::Illegal; 6887 } 6888 6889 // Make sure none of the operands are un-outlinable. 6890 for (const MachineOperand &MOP : MI.operands()) { 6891 if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() || 6892 MOP.isTargetIndex()) 6893 return outliner::InstrType::Illegal; 6894 6895 // If it uses LR or W30 explicitly, then don't touch it. 6896 if (MOP.isReg() && !MOP.isImplicit() && 6897 (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30)) 6898 return outliner::InstrType::Illegal; 6899 } 6900 6901 // Special cases for instructions that can always be outlined, but will fail 6902 // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always 6903 // be outlined because they don't require a *specific* value to be in LR. 6904 if (MI.getOpcode() == AArch64::ADRP) 6905 return outliner::InstrType::Legal; 6906 6907 // If MI is a call we might be able to outline it. We don't want to outline 6908 // any calls that rely on the position of items on the stack. When we outline 6909 // something containing a call, we have to emit a save and restore of LR in 6910 // the outlined function. Currently, this always happens by saving LR to the 6911 // stack. Thus, if we outline, say, half the parameters for a function call 6912 // plus the call, then we'll break the callee's expectations for the layout 6913 // of the stack. 6914 // 6915 // FIXME: Allow calls to functions which construct a stack frame, as long 6916 // as they don't access arguments on the stack. 6917 // FIXME: Figure out some way to analyze functions defined in other modules. 6918 // We should be able to compute the memory usage based on the IR calling 6919 // convention, even if we can't see the definition. 6920 if (MI.isCall()) { 6921 // Get the function associated with the call. Look at each operand and find 6922 // the one that represents the callee and get its name. 6923 const Function *Callee = nullptr; 6924 for (const MachineOperand &MOP : MI.operands()) { 6925 if (MOP.isGlobal()) { 6926 Callee = dyn_cast<Function>(MOP.getGlobal()); 6927 break; 6928 } 6929 } 6930 6931 // Never outline calls to mcount. There isn't any rule that would require 6932 // this, but the Linux kernel's "ftrace" feature depends on it. 6933 if (Callee && Callee->getName() == "\01_mcount") 6934 return outliner::InstrType::Illegal; 6935 6936 // If we don't know anything about the callee, assume it depends on the 6937 // stack layout of the caller. In that case, it's only legal to outline 6938 // as a tail-call. Explicitly list the call instructions we know about so we 6939 // don't get unexpected results with call pseudo-instructions. 6940 auto UnknownCallOutlineType = outliner::InstrType::Illegal; 6941 if (MI.getOpcode() == AArch64::BLR || 6942 MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL) 6943 UnknownCallOutlineType = outliner::InstrType::LegalTerminator; 6944 6945 if (!Callee) 6946 return UnknownCallOutlineType; 6947 6948 // We have a function we have information about. Check it if it's something 6949 // can safely outline. 6950 MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee); 6951 6952 // We don't know what's going on with the callee at all. Don't touch it. 6953 if (!CalleeMF) 6954 return UnknownCallOutlineType; 6955 6956 // Check if we know anything about the callee saves on the function. If we 6957 // don't, then don't touch it, since that implies that we haven't 6958 // computed anything about its stack frame yet. 6959 MachineFrameInfo &MFI = CalleeMF->getFrameInfo(); 6960 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 || 6961 MFI.getNumObjects() > 0) 6962 return UnknownCallOutlineType; 6963 6964 // At this point, we can say that CalleeMF ought to not pass anything on the 6965 // stack. Therefore, we can outline it. 6966 return outliner::InstrType::Legal; 6967 } 6968 6969 // Don't outline positions. 6970 if (MI.isPosition()) 6971 return outliner::InstrType::Illegal; 6972 6973 // Don't touch the link register or W30. 6974 if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) || 6975 MI.modifiesRegister(AArch64::W30, &getRegisterInfo())) 6976 return outliner::InstrType::Illegal; 6977 6978 // Don't outline BTI instructions, because that will prevent the outlining 6979 // site from being indirectly callable. 6980 if (MI.getOpcode() == AArch64::HINT) { 6981 int64_t Imm = MI.getOperand(0).getImm(); 6982 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38) 6983 return outliner::InstrType::Illegal; 6984 } 6985 6986 return outliner::InstrType::Legal; 6987 } 6988 6989 void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const { 6990 for (MachineInstr &MI : MBB) { 6991 const MachineOperand *Base; 6992 unsigned Width; 6993 int64_t Offset; 6994 bool OffsetIsScalable; 6995 6996 // Is this a load or store with an immediate offset with SP as the base? 6997 if (!MI.mayLoadOrStore() || 6998 !getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable, Width, 6999 &RI) || 7000 (Base->isReg() && Base->getReg() != AArch64::SP)) 7001 continue; 7002 7003 // It is, so we have to fix it up. 7004 TypeSize Scale(0U, false); 7005 int64_t Dummy1, Dummy2; 7006 7007 MachineOperand &StackOffsetOperand = getMemOpBaseRegImmOfsOffsetOperand(MI); 7008 assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!"); 7009 getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2); 7010 assert(Scale != 0 && "Unexpected opcode!"); 7011 assert(!OffsetIsScalable && "Expected offset to be a byte offset"); 7012 7013 // We've pushed the return address to the stack, so add 16 to the offset. 7014 // This is safe, since we already checked if it would overflow when we 7015 // checked if this instruction was legal to outline. 7016 int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedSize(); 7017 StackOffsetOperand.setImm(NewImm); 7018 } 7019 } 7020 7021 static void signOutlinedFunction(MachineFunction &MF, MachineBasicBlock &MBB, 7022 bool ShouldSignReturnAddr, 7023 bool ShouldSignReturnAddrWithAKey) { 7024 if (ShouldSignReturnAddr) { 7025 MachineBasicBlock::iterator MBBPAC = MBB.begin(); 7026 MachineBasicBlock::iterator MBBAUT = MBB.getFirstTerminator(); 7027 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 7028 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 7029 DebugLoc DL; 7030 7031 if (MBBAUT != MBB.end()) 7032 DL = MBBAUT->getDebugLoc(); 7033 7034 // At the very beginning of the basic block we insert the following 7035 // depending on the key type 7036 // 7037 // a_key: b_key: 7038 // PACIASP EMITBKEY 7039 // CFI_INSTRUCTION PACIBSP 7040 // CFI_INSTRUCTION 7041 if (ShouldSignReturnAddrWithAKey) { 7042 BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::PACIASP)) 7043 .setMIFlag(MachineInstr::FrameSetup); 7044 } else { 7045 BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::EMITBKEY)) 7046 .setMIFlag(MachineInstr::FrameSetup); 7047 BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::PACIBSP)) 7048 .setMIFlag(MachineInstr::FrameSetup); 7049 } 7050 unsigned CFIIndex = 7051 MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr)); 7052 BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::CFI_INSTRUCTION)) 7053 .addCFIIndex(CFIIndex) 7054 .setMIFlags(MachineInstr::FrameSetup); 7055 7056 // If v8.3a features are available we can replace a RET instruction by 7057 // RETAA or RETAB and omit the AUT instructions 7058 if (Subtarget.hasPAuth() && MBBAUT != MBB.end() && 7059 MBBAUT->getOpcode() == AArch64::RET) { 7060 BuildMI(MBB, MBBAUT, DL, 7061 TII->get(ShouldSignReturnAddrWithAKey ? AArch64::RETAA 7062 : AArch64::RETAB)) 7063 .copyImplicitOps(*MBBAUT); 7064 MBB.erase(MBBAUT); 7065 } else { 7066 BuildMI(MBB, MBBAUT, DL, 7067 TII->get(ShouldSignReturnAddrWithAKey ? AArch64::AUTIASP 7068 : AArch64::AUTIBSP)) 7069 .setMIFlag(MachineInstr::FrameDestroy); 7070 } 7071 } 7072 } 7073 7074 void AArch64InstrInfo::buildOutlinedFrame( 7075 MachineBasicBlock &MBB, MachineFunction &MF, 7076 const outliner::OutlinedFunction &OF) const { 7077 7078 AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>(); 7079 7080 if (OF.FrameConstructionID == MachineOutlinerTailCall) 7081 FI->setOutliningStyle("Tail Call"); 7082 else if (OF.FrameConstructionID == MachineOutlinerThunk) { 7083 // For thunk outlining, rewrite the last instruction from a call to a 7084 // tail-call. 7085 MachineInstr *Call = &*--MBB.instr_end(); 7086 unsigned TailOpcode; 7087 if (Call->getOpcode() == AArch64::BL) { 7088 TailOpcode = AArch64::TCRETURNdi; 7089 } else { 7090 assert(Call->getOpcode() == AArch64::BLR || 7091 Call->getOpcode() == AArch64::BLRNoIP); 7092 TailOpcode = AArch64::TCRETURNriALL; 7093 } 7094 MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode)) 7095 .add(Call->getOperand(0)) 7096 .addImm(0); 7097 MBB.insert(MBB.end(), TC); 7098 Call->eraseFromParent(); 7099 7100 FI->setOutliningStyle("Thunk"); 7101 } 7102 7103 bool IsLeafFunction = true; 7104 7105 // Is there a call in the outlined range? 7106 auto IsNonTailCall = [](const MachineInstr &MI) { 7107 return MI.isCall() && !MI.isReturn(); 7108 }; 7109 7110 if (llvm::any_of(MBB.instrs(), IsNonTailCall)) { 7111 // Fix up the instructions in the range, since we're going to modify the 7112 // stack. 7113 7114 // Bugzilla ID: 46767 7115 // TODO: Check if fixing up twice is safe so we can outline these. 7116 assert(OF.FrameConstructionID != MachineOutlinerDefault && 7117 "Can only fix up stack references once"); 7118 fixupPostOutline(MBB); 7119 7120 IsLeafFunction = false; 7121 7122 // LR has to be a live in so that we can save it. 7123 if (!MBB.isLiveIn(AArch64::LR)) 7124 MBB.addLiveIn(AArch64::LR); 7125 7126 MachineBasicBlock::iterator It = MBB.begin(); 7127 MachineBasicBlock::iterator Et = MBB.end(); 7128 7129 if (OF.FrameConstructionID == MachineOutlinerTailCall || 7130 OF.FrameConstructionID == MachineOutlinerThunk) 7131 Et = std::prev(MBB.end()); 7132 7133 // Insert a save before the outlined region 7134 MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre)) 7135 .addReg(AArch64::SP, RegState::Define) 7136 .addReg(AArch64::LR) 7137 .addReg(AArch64::SP) 7138 .addImm(-16); 7139 It = MBB.insert(It, STRXpre); 7140 7141 const TargetSubtargetInfo &STI = MF.getSubtarget(); 7142 const MCRegisterInfo *MRI = STI.getRegisterInfo(); 7143 unsigned DwarfReg = MRI->getDwarfRegNum(AArch64::LR, true); 7144 7145 // Add a CFI saying the stack was moved 16 B down. 7146 int64_t StackPosEntry = 7147 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 16)); 7148 BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION)) 7149 .addCFIIndex(StackPosEntry) 7150 .setMIFlags(MachineInstr::FrameSetup); 7151 7152 // Add a CFI saying that the LR that we want to find is now 16 B higher than 7153 // before. 7154 int64_t LRPosEntry = 7155 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg, -16)); 7156 BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION)) 7157 .addCFIIndex(LRPosEntry) 7158 .setMIFlags(MachineInstr::FrameSetup); 7159 7160 // Insert a restore before the terminator for the function. 7161 MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost)) 7162 .addReg(AArch64::SP, RegState::Define) 7163 .addReg(AArch64::LR, RegState::Define) 7164 .addReg(AArch64::SP) 7165 .addImm(16); 7166 Et = MBB.insert(Et, LDRXpost); 7167 } 7168 7169 // If a bunch of candidates reach this point they must agree on their return 7170 // address signing. It is therefore enough to just consider the signing 7171 // behaviour of one of them 7172 const auto &MFI = *OF.Candidates.front().getMF()->getInfo<AArch64FunctionInfo>(); 7173 bool ShouldSignReturnAddr = MFI.shouldSignReturnAddress(!IsLeafFunction); 7174 7175 // a_key is the default 7176 bool ShouldSignReturnAddrWithAKey = !MFI.shouldSignWithBKey(); 7177 7178 // If this is a tail call outlined function, then there's already a return. 7179 if (OF.FrameConstructionID == MachineOutlinerTailCall || 7180 OF.FrameConstructionID == MachineOutlinerThunk) { 7181 signOutlinedFunction(MF, MBB, ShouldSignReturnAddr, 7182 ShouldSignReturnAddrWithAKey); 7183 return; 7184 } 7185 7186 // It's not a tail call, so we have to insert the return ourselves. 7187 7188 // LR has to be a live in so that we can return to it. 7189 if (!MBB.isLiveIn(AArch64::LR)) 7190 MBB.addLiveIn(AArch64::LR); 7191 7192 MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET)) 7193 .addReg(AArch64::LR); 7194 MBB.insert(MBB.end(), ret); 7195 7196 signOutlinedFunction(MF, MBB, ShouldSignReturnAddr, 7197 ShouldSignReturnAddrWithAKey); 7198 7199 FI->setOutliningStyle("Function"); 7200 7201 // Did we have to modify the stack by saving the link register? 7202 if (OF.FrameConstructionID != MachineOutlinerDefault) 7203 return; 7204 7205 // We modified the stack. 7206 // Walk over the basic block and fix up all the stack accesses. 7207 fixupPostOutline(MBB); 7208 } 7209 7210 MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall( 7211 Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It, 7212 MachineFunction &MF, const outliner::Candidate &C) const { 7213 7214 // Are we tail calling? 7215 if (C.CallConstructionID == MachineOutlinerTailCall) { 7216 // If yes, then we can just branch to the label. 7217 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi)) 7218 .addGlobalAddress(M.getNamedValue(MF.getName())) 7219 .addImm(0)); 7220 return It; 7221 } 7222 7223 // Are we saving the link register? 7224 if (C.CallConstructionID == MachineOutlinerNoLRSave || 7225 C.CallConstructionID == MachineOutlinerThunk) { 7226 // No, so just insert the call. 7227 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL)) 7228 .addGlobalAddress(M.getNamedValue(MF.getName()))); 7229 return It; 7230 } 7231 7232 // We want to return the spot where we inserted the call. 7233 MachineBasicBlock::iterator CallPt; 7234 7235 // Instructions for saving and restoring LR around the call instruction we're 7236 // going to insert. 7237 MachineInstr *Save; 7238 MachineInstr *Restore; 7239 // Can we save to a register? 7240 if (C.CallConstructionID == MachineOutlinerRegSave) { 7241 // FIXME: This logic should be sunk into a target-specific interface so that 7242 // we don't have to recompute the register. 7243 unsigned Reg = findRegisterToSaveLRTo(C); 7244 assert(Reg != 0 && "No callee-saved register available?"); 7245 7246 // Save and restore LR from that register. 7247 Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg) 7248 .addReg(AArch64::XZR) 7249 .addReg(AArch64::LR) 7250 .addImm(0); 7251 Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR) 7252 .addReg(AArch64::XZR) 7253 .addReg(Reg) 7254 .addImm(0); 7255 } else { 7256 // We have the default case. Save and restore from SP. 7257 Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre)) 7258 .addReg(AArch64::SP, RegState::Define) 7259 .addReg(AArch64::LR) 7260 .addReg(AArch64::SP) 7261 .addImm(-16); 7262 Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost)) 7263 .addReg(AArch64::SP, RegState::Define) 7264 .addReg(AArch64::LR, RegState::Define) 7265 .addReg(AArch64::SP) 7266 .addImm(16); 7267 } 7268 7269 It = MBB.insert(It, Save); 7270 It++; 7271 7272 // Insert the call. 7273 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL)) 7274 .addGlobalAddress(M.getNamedValue(MF.getName()))); 7275 CallPt = It; 7276 It++; 7277 7278 It = MBB.insert(It, Restore); 7279 return CallPt; 7280 } 7281 7282 bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault( 7283 MachineFunction &MF) const { 7284 return MF.getFunction().hasMinSize(); 7285 } 7286 7287 Optional<DestSourcePair> 7288 AArch64InstrInfo::isCopyInstrImpl(const MachineInstr &MI) const { 7289 7290 // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg 7291 // and zero immediate operands used as an alias for mov instruction. 7292 if (MI.getOpcode() == AArch64::ORRWrs && 7293 MI.getOperand(1).getReg() == AArch64::WZR && 7294 MI.getOperand(3).getImm() == 0x0) { 7295 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)}; 7296 } 7297 7298 if (MI.getOpcode() == AArch64::ORRXrs && 7299 MI.getOperand(1).getReg() == AArch64::XZR && 7300 MI.getOperand(3).getImm() == 0x0) { 7301 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)}; 7302 } 7303 7304 return None; 7305 } 7306 7307 Optional<RegImmPair> AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, 7308 Register Reg) const { 7309 int Sign = 1; 7310 int64_t Offset = 0; 7311 7312 // TODO: Handle cases where Reg is a super- or sub-register of the 7313 // destination register. 7314 const MachineOperand &Op0 = MI.getOperand(0); 7315 if (!Op0.isReg() || Reg != Op0.getReg()) 7316 return None; 7317 7318 switch (MI.getOpcode()) { 7319 default: 7320 return None; 7321 case AArch64::SUBWri: 7322 case AArch64::SUBXri: 7323 case AArch64::SUBSWri: 7324 case AArch64::SUBSXri: 7325 Sign *= -1; 7326 LLVM_FALLTHROUGH; 7327 case AArch64::ADDSWri: 7328 case AArch64::ADDSXri: 7329 case AArch64::ADDWri: 7330 case AArch64::ADDXri: { 7331 // TODO: Third operand can be global address (usually some string). 7332 if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() || 7333 !MI.getOperand(2).isImm()) 7334 return None; 7335 int Shift = MI.getOperand(3).getImm(); 7336 assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12"); 7337 Offset = Sign * (MI.getOperand(2).getImm() << Shift); 7338 } 7339 } 7340 return RegImmPair{MI.getOperand(1).getReg(), Offset}; 7341 } 7342 7343 /// If the given ORR instruction is a copy, and \p DescribedReg overlaps with 7344 /// the destination register then, if possible, describe the value in terms of 7345 /// the source register. 7346 static Optional<ParamLoadedValue> 7347 describeORRLoadedValue(const MachineInstr &MI, Register DescribedReg, 7348 const TargetInstrInfo *TII, 7349 const TargetRegisterInfo *TRI) { 7350 auto DestSrc = TII->isCopyInstr(MI); 7351 if (!DestSrc) 7352 return None; 7353 7354 Register DestReg = DestSrc->Destination->getReg(); 7355 Register SrcReg = DestSrc->Source->getReg(); 7356 7357 auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {}); 7358 7359 // If the described register is the destination, just return the source. 7360 if (DestReg == DescribedReg) 7361 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr); 7362 7363 // ORRWrs zero-extends to 64-bits, so we need to consider such cases. 7364 if (MI.getOpcode() == AArch64::ORRWrs && 7365 TRI->isSuperRegister(DestReg, DescribedReg)) 7366 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr); 7367 7368 // We may need to describe the lower part of a ORRXrs move. 7369 if (MI.getOpcode() == AArch64::ORRXrs && 7370 TRI->isSubRegister(DestReg, DescribedReg)) { 7371 Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32); 7372 return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr); 7373 } 7374 7375 assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) && 7376 "Unhandled ORR[XW]rs copy case"); 7377 7378 return None; 7379 } 7380 7381 Optional<ParamLoadedValue> 7382 AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI, 7383 Register Reg) const { 7384 const MachineFunction *MF = MI.getMF(); 7385 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 7386 switch (MI.getOpcode()) { 7387 case AArch64::MOVZWi: 7388 case AArch64::MOVZXi: { 7389 // MOVZWi may be used for producing zero-extended 32-bit immediates in 7390 // 64-bit parameters, so we need to consider super-registers. 7391 if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg)) 7392 return None; 7393 7394 if (!MI.getOperand(1).isImm()) 7395 return None; 7396 int64_t Immediate = MI.getOperand(1).getImm(); 7397 int Shift = MI.getOperand(2).getImm(); 7398 return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift), 7399 nullptr); 7400 } 7401 case AArch64::ORRWrs: 7402 case AArch64::ORRXrs: 7403 return describeORRLoadedValue(MI, Reg, this, TRI); 7404 } 7405 7406 return TargetInstrInfo::describeLoadedValue(MI, Reg); 7407 } 7408 7409 bool AArch64InstrInfo::isExtendLikelyToBeFolded( 7410 MachineInstr &ExtMI, MachineRegisterInfo &MRI) const { 7411 assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT || 7412 ExtMI.getOpcode() == TargetOpcode::G_ZEXT || 7413 ExtMI.getOpcode() == TargetOpcode::G_ANYEXT); 7414 7415 // Anyexts are nops. 7416 if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT) 7417 return true; 7418 7419 Register DefReg = ExtMI.getOperand(0).getReg(); 7420 if (!MRI.hasOneNonDBGUse(DefReg)) 7421 return false; 7422 7423 // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an 7424 // addressing mode. 7425 auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg); 7426 return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD; 7427 } 7428 7429 uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const { 7430 return get(Opc).TSFlags & AArch64::ElementSizeMask; 7431 } 7432 7433 bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const { 7434 return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike; 7435 } 7436 7437 bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const { 7438 return get(Opc).TSFlags & AArch64::InstrFlagIsWhile; 7439 } 7440 7441 unsigned int 7442 AArch64InstrInfo::getTailDuplicateSize(CodeGenOpt::Level OptLevel) const { 7443 return OptLevel >= CodeGenOpt::Aggressive ? 6 : 2; 7444 } 7445 7446 unsigned llvm::getBLRCallOpcode(const MachineFunction &MF) { 7447 if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr()) 7448 return AArch64::BLRNoIP; 7449 else 7450 return AArch64::BLR; 7451 } 7452 7453 #define GET_INSTRINFO_HELPERS 7454 #define GET_INSTRMAP_INFO 7455 #include "AArch64GenInstrInfo.inc" 7456