1 //===-- lib/CodeGen/GlobalISel/GICombinerHelper.cpp -----------------------===// 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 #include "llvm/CodeGen/GlobalISel/CombinerHelper.h" 9 #include "llvm/ADT/SetVector.h" 10 #include "llvm/ADT/SmallBitVector.h" 11 #include "llvm/CodeGen/GlobalISel/Combiner.h" 12 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" 13 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 14 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h" 15 #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h" 16 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" 17 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 18 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" 19 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" 20 #include "llvm/CodeGen/GlobalISel/Utils.h" 21 #include "llvm/CodeGen/LowLevelType.h" 22 #include "llvm/CodeGen/MachineBasicBlock.h" 23 #include "llvm/CodeGen/MachineDominators.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineInstr.h" 26 #include "llvm/CodeGen/MachineMemOperand.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/TargetInstrInfo.h" 29 #include "llvm/CodeGen/TargetLowering.h" 30 #include "llvm/CodeGen/TargetOpcodes.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/Support/Casting.h" 33 #include "llvm/Support/DivisionByConstantInfo.h" 34 #include "llvm/Support/MathExtras.h" 35 #include <tuple> 36 37 #define DEBUG_TYPE "gi-combiner" 38 39 using namespace llvm; 40 using namespace MIPatternMatch; 41 42 // Option to allow testing of the combiner while no targets know about indexed 43 // addressing. 44 static cl::opt<bool> 45 ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false), 46 cl::desc("Force all indexed operations to be " 47 "legal for the GlobalISel combiner")); 48 49 CombinerHelper::CombinerHelper(GISelChangeObserver &Observer, 50 MachineIRBuilder &B, GISelKnownBits *KB, 51 MachineDominatorTree *MDT, 52 const LegalizerInfo *LI) 53 : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), KB(KB), 54 MDT(MDT), LI(LI), RBI(Builder.getMF().getSubtarget().getRegBankInfo()), 55 TRI(Builder.getMF().getSubtarget().getRegisterInfo()) { 56 (void)this->KB; 57 } 58 59 const TargetLowering &CombinerHelper::getTargetLowering() const { 60 return *Builder.getMF().getSubtarget().getTargetLowering(); 61 } 62 63 /// \returns The little endian in-memory byte position of byte \p I in a 64 /// \p ByteWidth bytes wide type. 65 /// 66 /// E.g. Given a 4-byte type x, x[0] -> byte 0 67 static unsigned littleEndianByteAt(const unsigned ByteWidth, const unsigned I) { 68 assert(I < ByteWidth && "I must be in [0, ByteWidth)"); 69 return I; 70 } 71 72 /// Determines the LogBase2 value for a non-null input value using the 73 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 74 static Register buildLogBase2(Register V, MachineIRBuilder &MIB) { 75 auto &MRI = *MIB.getMRI(); 76 LLT Ty = MRI.getType(V); 77 auto Ctlz = MIB.buildCTLZ(Ty, V); 78 auto Base = MIB.buildConstant(Ty, Ty.getScalarSizeInBits() - 1); 79 return MIB.buildSub(Ty, Base, Ctlz).getReg(0); 80 } 81 82 /// \returns The big endian in-memory byte position of byte \p I in a 83 /// \p ByteWidth bytes wide type. 84 /// 85 /// E.g. Given a 4-byte type x, x[0] -> byte 3 86 static unsigned bigEndianByteAt(const unsigned ByteWidth, const unsigned I) { 87 assert(I < ByteWidth && "I must be in [0, ByteWidth)"); 88 return ByteWidth - I - 1; 89 } 90 91 /// Given a map from byte offsets in memory to indices in a load/store, 92 /// determine if that map corresponds to a little or big endian byte pattern. 93 /// 94 /// \param MemOffset2Idx maps memory offsets to address offsets. 95 /// \param LowestIdx is the lowest index in \p MemOffset2Idx. 96 /// 97 /// \returns true if the map corresponds to a big endian byte pattern, false 98 /// if it corresponds to a little endian byte pattern, and None otherwise. 99 /// 100 /// E.g. given a 32-bit type x, and x[AddrOffset], the in-memory byte patterns 101 /// are as follows: 102 /// 103 /// AddrOffset Little endian Big endian 104 /// 0 0 3 105 /// 1 1 2 106 /// 2 2 1 107 /// 3 3 0 108 static Optional<bool> 109 isBigEndian(const SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx, 110 int64_t LowestIdx) { 111 // Need at least two byte positions to decide on endianness. 112 unsigned Width = MemOffset2Idx.size(); 113 if (Width < 2) 114 return None; 115 bool BigEndian = true, LittleEndian = true; 116 for (unsigned MemOffset = 0; MemOffset < Width; ++ MemOffset) { 117 auto MemOffsetAndIdx = MemOffset2Idx.find(MemOffset); 118 if (MemOffsetAndIdx == MemOffset2Idx.end()) 119 return None; 120 const int64_t Idx = MemOffsetAndIdx->second - LowestIdx; 121 assert(Idx >= 0 && "Expected non-negative byte offset?"); 122 LittleEndian &= Idx == littleEndianByteAt(Width, MemOffset); 123 BigEndian &= Idx == bigEndianByteAt(Width, MemOffset); 124 if (!BigEndian && !LittleEndian) 125 return None; 126 } 127 128 assert((BigEndian != LittleEndian) && 129 "Pattern cannot be both big and little endian!"); 130 return BigEndian; 131 } 132 133 bool CombinerHelper::isLegalOrBeforeLegalizer( 134 const LegalityQuery &Query) const { 135 return !LI || LI->getAction(Query).Action == LegalizeActions::Legal; 136 } 137 138 void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg, 139 Register ToReg) const { 140 Observer.changingAllUsesOfReg(MRI, FromReg); 141 142 if (MRI.constrainRegAttrs(ToReg, FromReg)) 143 MRI.replaceRegWith(FromReg, ToReg); 144 else 145 Builder.buildCopy(ToReg, FromReg); 146 147 Observer.finishedChangingAllUsesOfReg(); 148 } 149 150 void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI, 151 MachineOperand &FromRegOp, 152 Register ToReg) const { 153 assert(FromRegOp.getParent() && "Expected an operand in an MI"); 154 Observer.changingInstr(*FromRegOp.getParent()); 155 156 FromRegOp.setReg(ToReg); 157 158 Observer.changedInstr(*FromRegOp.getParent()); 159 } 160 161 const RegisterBank *CombinerHelper::getRegBank(Register Reg) const { 162 return RBI->getRegBank(Reg, MRI, *TRI); 163 } 164 165 void CombinerHelper::setRegBank(Register Reg, const RegisterBank *RegBank) { 166 if (RegBank) 167 MRI.setRegBank(Reg, *RegBank); 168 } 169 170 bool CombinerHelper::tryCombineCopy(MachineInstr &MI) { 171 if (matchCombineCopy(MI)) { 172 applyCombineCopy(MI); 173 return true; 174 } 175 return false; 176 } 177 bool CombinerHelper::matchCombineCopy(MachineInstr &MI) { 178 if (MI.getOpcode() != TargetOpcode::COPY) 179 return false; 180 Register DstReg = MI.getOperand(0).getReg(); 181 Register SrcReg = MI.getOperand(1).getReg(); 182 return canReplaceReg(DstReg, SrcReg, MRI); 183 } 184 void CombinerHelper::applyCombineCopy(MachineInstr &MI) { 185 Register DstReg = MI.getOperand(0).getReg(); 186 Register SrcReg = MI.getOperand(1).getReg(); 187 MI.eraseFromParent(); 188 replaceRegWith(MRI, DstReg, SrcReg); 189 } 190 191 bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) { 192 bool IsUndef = false; 193 SmallVector<Register, 4> Ops; 194 if (matchCombineConcatVectors(MI, IsUndef, Ops)) { 195 applyCombineConcatVectors(MI, IsUndef, Ops); 196 return true; 197 } 198 return false; 199 } 200 201 bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef, 202 SmallVectorImpl<Register> &Ops) { 203 assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS && 204 "Invalid instruction"); 205 IsUndef = true; 206 MachineInstr *Undef = nullptr; 207 208 // Walk over all the operands of concat vectors and check if they are 209 // build_vector themselves or undef. 210 // Then collect their operands in Ops. 211 for (const MachineOperand &MO : MI.uses()) { 212 Register Reg = MO.getReg(); 213 MachineInstr *Def = MRI.getVRegDef(Reg); 214 assert(Def && "Operand not defined"); 215 switch (Def->getOpcode()) { 216 case TargetOpcode::G_BUILD_VECTOR: 217 IsUndef = false; 218 // Remember the operands of the build_vector to fold 219 // them into the yet-to-build flattened concat vectors. 220 for (const MachineOperand &BuildVecMO : Def->uses()) 221 Ops.push_back(BuildVecMO.getReg()); 222 break; 223 case TargetOpcode::G_IMPLICIT_DEF: { 224 LLT OpType = MRI.getType(Reg); 225 // Keep one undef value for all the undef operands. 226 if (!Undef) { 227 Builder.setInsertPt(*MI.getParent(), MI); 228 Undef = Builder.buildUndef(OpType.getScalarType()); 229 } 230 assert(MRI.getType(Undef->getOperand(0).getReg()) == 231 OpType.getScalarType() && 232 "All undefs should have the same type"); 233 // Break the undef vector in as many scalar elements as needed 234 // for the flattening. 235 for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements(); 236 EltIdx != EltEnd; ++EltIdx) 237 Ops.push_back(Undef->getOperand(0).getReg()); 238 break; 239 } 240 default: 241 return false; 242 } 243 } 244 return true; 245 } 246 void CombinerHelper::applyCombineConcatVectors( 247 MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) { 248 // We determined that the concat_vectors can be flatten. 249 // Generate the flattened build_vector. 250 Register DstReg = MI.getOperand(0).getReg(); 251 Builder.setInsertPt(*MI.getParent(), MI); 252 Register NewDstReg = MRI.cloneVirtualRegister(DstReg); 253 254 // Note: IsUndef is sort of redundant. We could have determine it by 255 // checking that at all Ops are undef. Alternatively, we could have 256 // generate a build_vector of undefs and rely on another combine to 257 // clean that up. For now, given we already gather this information 258 // in tryCombineConcatVectors, just save compile time and issue the 259 // right thing. 260 if (IsUndef) 261 Builder.buildUndef(NewDstReg); 262 else 263 Builder.buildBuildVector(NewDstReg, Ops); 264 MI.eraseFromParent(); 265 replaceRegWith(MRI, DstReg, NewDstReg); 266 } 267 268 bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) { 269 SmallVector<Register, 4> Ops; 270 if (matchCombineShuffleVector(MI, Ops)) { 271 applyCombineShuffleVector(MI, Ops); 272 return true; 273 } 274 return false; 275 } 276 277 bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI, 278 SmallVectorImpl<Register> &Ops) { 279 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR && 280 "Invalid instruction kind"); 281 LLT DstType = MRI.getType(MI.getOperand(0).getReg()); 282 Register Src1 = MI.getOperand(1).getReg(); 283 LLT SrcType = MRI.getType(Src1); 284 // As bizarre as it may look, shuffle vector can actually produce 285 // scalar! This is because at the IR level a <1 x ty> shuffle 286 // vector is perfectly valid. 287 unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1; 288 unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1; 289 290 // If the resulting vector is smaller than the size of the source 291 // vectors being concatenated, we won't be able to replace the 292 // shuffle vector into a concat_vectors. 293 // 294 // Note: We may still be able to produce a concat_vectors fed by 295 // extract_vector_elt and so on. It is less clear that would 296 // be better though, so don't bother for now. 297 // 298 // If the destination is a scalar, the size of the sources doesn't 299 // matter. we will lower the shuffle to a plain copy. This will 300 // work only if the source and destination have the same size. But 301 // that's covered by the next condition. 302 // 303 // TODO: If the size between the source and destination don't match 304 // we could still emit an extract vector element in that case. 305 if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1) 306 return false; 307 308 // Check that the shuffle mask can be broken evenly between the 309 // different sources. 310 if (DstNumElts % SrcNumElts != 0) 311 return false; 312 313 // Mask length is a multiple of the source vector length. 314 // Check if the shuffle is some kind of concatenation of the input 315 // vectors. 316 unsigned NumConcat = DstNumElts / SrcNumElts; 317 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 318 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask(); 319 for (unsigned i = 0; i != DstNumElts; ++i) { 320 int Idx = Mask[i]; 321 // Undef value. 322 if (Idx < 0) 323 continue; 324 // Ensure the indices in each SrcType sized piece are sequential and that 325 // the same source is used for the whole piece. 326 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 327 (ConcatSrcs[i / SrcNumElts] >= 0 && 328 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) 329 return false; 330 // Remember which source this index came from. 331 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 332 } 333 334 // The shuffle is concatenating multiple vectors together. 335 // Collect the different operands for that. 336 Register UndefReg; 337 Register Src2 = MI.getOperand(2).getReg(); 338 for (auto Src : ConcatSrcs) { 339 if (Src < 0) { 340 if (!UndefReg) { 341 Builder.setInsertPt(*MI.getParent(), MI); 342 UndefReg = Builder.buildUndef(SrcType).getReg(0); 343 } 344 Ops.push_back(UndefReg); 345 } else if (Src == 0) 346 Ops.push_back(Src1); 347 else 348 Ops.push_back(Src2); 349 } 350 return true; 351 } 352 353 void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI, 354 const ArrayRef<Register> Ops) { 355 Register DstReg = MI.getOperand(0).getReg(); 356 Builder.setInsertPt(*MI.getParent(), MI); 357 Register NewDstReg = MRI.cloneVirtualRegister(DstReg); 358 359 if (Ops.size() == 1) 360 Builder.buildCopy(NewDstReg, Ops[0]); 361 else 362 Builder.buildMerge(NewDstReg, Ops); 363 364 MI.eraseFromParent(); 365 replaceRegWith(MRI, DstReg, NewDstReg); 366 } 367 368 namespace { 369 370 /// Select a preference between two uses. CurrentUse is the current preference 371 /// while *ForCandidate is attributes of the candidate under consideration. 372 PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse, 373 const LLT TyForCandidate, 374 unsigned OpcodeForCandidate, 375 MachineInstr *MIForCandidate) { 376 if (!CurrentUse.Ty.isValid()) { 377 if (CurrentUse.ExtendOpcode == OpcodeForCandidate || 378 CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT) 379 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 380 return CurrentUse; 381 } 382 383 // We permit the extend to hoist through basic blocks but this is only 384 // sensible if the target has extending loads. If you end up lowering back 385 // into a load and extend during the legalizer then the end result is 386 // hoisting the extend up to the load. 387 388 // Prefer defined extensions to undefined extensions as these are more 389 // likely to reduce the number of instructions. 390 if (OpcodeForCandidate == TargetOpcode::G_ANYEXT && 391 CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT) 392 return CurrentUse; 393 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT && 394 OpcodeForCandidate != TargetOpcode::G_ANYEXT) 395 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 396 397 // Prefer sign extensions to zero extensions as sign-extensions tend to be 398 // more expensive. 399 if (CurrentUse.Ty == TyForCandidate) { 400 if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT && 401 OpcodeForCandidate == TargetOpcode::G_ZEXT) 402 return CurrentUse; 403 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT && 404 OpcodeForCandidate == TargetOpcode::G_SEXT) 405 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 406 } 407 408 // This is potentially target specific. We've chosen the largest type 409 // because G_TRUNC is usually free. One potential catch with this is that 410 // some targets have a reduced number of larger registers than smaller 411 // registers and this choice potentially increases the live-range for the 412 // larger value. 413 if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) { 414 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 415 } 416 return CurrentUse; 417 } 418 419 /// Find a suitable place to insert some instructions and insert them. This 420 /// function accounts for special cases like inserting before a PHI node. 421 /// The current strategy for inserting before PHI's is to duplicate the 422 /// instructions for each predecessor. However, while that's ok for G_TRUNC 423 /// on most targets since it generally requires no code, other targets/cases may 424 /// want to try harder to find a dominating block. 425 static void InsertInsnsWithoutSideEffectsBeforeUse( 426 MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO, 427 std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator, 428 MachineOperand &UseMO)> 429 Inserter) { 430 MachineInstr &UseMI = *UseMO.getParent(); 431 432 MachineBasicBlock *InsertBB = UseMI.getParent(); 433 434 // If the use is a PHI then we want the predecessor block instead. 435 if (UseMI.isPHI()) { 436 MachineOperand *PredBB = std::next(&UseMO); 437 InsertBB = PredBB->getMBB(); 438 } 439 440 // If the block is the same block as the def then we want to insert just after 441 // the def instead of at the start of the block. 442 if (InsertBB == DefMI.getParent()) { 443 MachineBasicBlock::iterator InsertPt = &DefMI; 444 Inserter(InsertBB, std::next(InsertPt), UseMO); 445 return; 446 } 447 448 // Otherwise we want the start of the BB 449 Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO); 450 } 451 } // end anonymous namespace 452 453 bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) { 454 PreferredTuple Preferred; 455 if (matchCombineExtendingLoads(MI, Preferred)) { 456 applyCombineExtendingLoads(MI, Preferred); 457 return true; 458 } 459 return false; 460 } 461 462 bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI, 463 PreferredTuple &Preferred) { 464 // We match the loads and follow the uses to the extend instead of matching 465 // the extends and following the def to the load. This is because the load 466 // must remain in the same position for correctness (unless we also add code 467 // to find a safe place to sink it) whereas the extend is freely movable. 468 // It also prevents us from duplicating the load for the volatile case or just 469 // for performance. 470 GAnyLoad *LoadMI = dyn_cast<GAnyLoad>(&MI); 471 if (!LoadMI) 472 return false; 473 474 Register LoadReg = LoadMI->getDstReg(); 475 476 LLT LoadValueTy = MRI.getType(LoadReg); 477 if (!LoadValueTy.isScalar()) 478 return false; 479 480 // Most architectures are going to legalize <s8 loads into at least a 1 byte 481 // load, and the MMOs can only describe memory accesses in multiples of bytes. 482 // If we try to perform extload combining on those, we can end up with 483 // %a(s8) = extload %ptr (load 1 byte from %ptr) 484 // ... which is an illegal extload instruction. 485 if (LoadValueTy.getSizeInBits() < 8) 486 return false; 487 488 // For non power-of-2 types, they will very likely be legalized into multiple 489 // loads. Don't bother trying to match them into extending loads. 490 if (!isPowerOf2_32(LoadValueTy.getSizeInBits())) 491 return false; 492 493 // Find the preferred type aside from the any-extends (unless it's the only 494 // one) and non-extending ops. We'll emit an extending load to that type and 495 // and emit a variant of (extend (trunc X)) for the others according to the 496 // relative type sizes. At the same time, pick an extend to use based on the 497 // extend involved in the chosen type. 498 unsigned PreferredOpcode = 499 isa<GLoad>(&MI) 500 ? TargetOpcode::G_ANYEXT 501 : isa<GSExtLoad>(&MI) ? TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT; 502 Preferred = {LLT(), PreferredOpcode, nullptr}; 503 for (auto &UseMI : MRI.use_nodbg_instructions(LoadReg)) { 504 if (UseMI.getOpcode() == TargetOpcode::G_SEXT || 505 UseMI.getOpcode() == TargetOpcode::G_ZEXT || 506 (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) { 507 const auto &MMO = LoadMI->getMMO(); 508 // For atomics, only form anyextending loads. 509 if (MMO.isAtomic() && UseMI.getOpcode() != TargetOpcode::G_ANYEXT) 510 continue; 511 // Check for legality. 512 if (LI) { 513 LegalityQuery::MemDesc MMDesc(MMO); 514 LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg()); 515 LLT SrcTy = MRI.getType(LoadMI->getPointerReg()); 516 if (LI->getAction({LoadMI->getOpcode(), {UseTy, SrcTy}, {MMDesc}}) 517 .Action != LegalizeActions::Legal) 518 continue; 519 } 520 Preferred = ChoosePreferredUse(Preferred, 521 MRI.getType(UseMI.getOperand(0).getReg()), 522 UseMI.getOpcode(), &UseMI); 523 } 524 } 525 526 // There were no extends 527 if (!Preferred.MI) 528 return false; 529 // It should be impossible to chose an extend without selecting a different 530 // type since by definition the result of an extend is larger. 531 assert(Preferred.Ty != LoadValueTy && "Extending to same type?"); 532 533 LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI); 534 return true; 535 } 536 537 void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI, 538 PreferredTuple &Preferred) { 539 // Rewrite the load to the chosen extending load. 540 Register ChosenDstReg = Preferred.MI->getOperand(0).getReg(); 541 542 // Inserter to insert a truncate back to the original type at a given point 543 // with some basic CSE to limit truncate duplication to one per BB. 544 DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns; 545 auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB, 546 MachineBasicBlock::iterator InsertBefore, 547 MachineOperand &UseMO) { 548 MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB); 549 if (PreviouslyEmitted) { 550 Observer.changingInstr(*UseMO.getParent()); 551 UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg()); 552 Observer.changedInstr(*UseMO.getParent()); 553 return; 554 } 555 556 Builder.setInsertPt(*InsertIntoBB, InsertBefore); 557 Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg()); 558 MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg); 559 EmittedInsns[InsertIntoBB] = NewMI; 560 replaceRegOpWith(MRI, UseMO, NewDstReg); 561 }; 562 563 Observer.changingInstr(MI); 564 MI.setDesc( 565 Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT 566 ? TargetOpcode::G_SEXTLOAD 567 : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT 568 ? TargetOpcode::G_ZEXTLOAD 569 : TargetOpcode::G_LOAD)); 570 571 // Rewrite all the uses to fix up the types. 572 auto &LoadValue = MI.getOperand(0); 573 SmallVector<MachineOperand *, 4> Uses; 574 for (auto &UseMO : MRI.use_operands(LoadValue.getReg())) 575 Uses.push_back(&UseMO); 576 577 for (auto *UseMO : Uses) { 578 MachineInstr *UseMI = UseMO->getParent(); 579 580 // If the extend is compatible with the preferred extend then we should fix 581 // up the type and extend so that it uses the preferred use. 582 if (UseMI->getOpcode() == Preferred.ExtendOpcode || 583 UseMI->getOpcode() == TargetOpcode::G_ANYEXT) { 584 Register UseDstReg = UseMI->getOperand(0).getReg(); 585 MachineOperand &UseSrcMO = UseMI->getOperand(1); 586 const LLT UseDstTy = MRI.getType(UseDstReg); 587 if (UseDstReg != ChosenDstReg) { 588 if (Preferred.Ty == UseDstTy) { 589 // If the use has the same type as the preferred use, then merge 590 // the vregs and erase the extend. For example: 591 // %1:_(s8) = G_LOAD ... 592 // %2:_(s32) = G_SEXT %1(s8) 593 // %3:_(s32) = G_ANYEXT %1(s8) 594 // ... = ... %3(s32) 595 // rewrites to: 596 // %2:_(s32) = G_SEXTLOAD ... 597 // ... = ... %2(s32) 598 replaceRegWith(MRI, UseDstReg, ChosenDstReg); 599 Observer.erasingInstr(*UseMO->getParent()); 600 UseMO->getParent()->eraseFromParent(); 601 } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) { 602 // If the preferred size is smaller, then keep the extend but extend 603 // from the result of the extending load. For example: 604 // %1:_(s8) = G_LOAD ... 605 // %2:_(s32) = G_SEXT %1(s8) 606 // %3:_(s64) = G_ANYEXT %1(s8) 607 // ... = ... %3(s64) 608 /// rewrites to: 609 // %2:_(s32) = G_SEXTLOAD ... 610 // %3:_(s64) = G_ANYEXT %2:_(s32) 611 // ... = ... %3(s64) 612 replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg); 613 } else { 614 // If the preferred size is large, then insert a truncate. For 615 // example: 616 // %1:_(s8) = G_LOAD ... 617 // %2:_(s64) = G_SEXT %1(s8) 618 // %3:_(s32) = G_ZEXT %1(s8) 619 // ... = ... %3(s32) 620 /// rewrites to: 621 // %2:_(s64) = G_SEXTLOAD ... 622 // %4:_(s8) = G_TRUNC %2:_(s32) 623 // %3:_(s64) = G_ZEXT %2:_(s8) 624 // ... = ... %3(s64) 625 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, 626 InsertTruncAt); 627 } 628 continue; 629 } 630 // The use is (one of) the uses of the preferred use we chose earlier. 631 // We're going to update the load to def this value later so just erase 632 // the old extend. 633 Observer.erasingInstr(*UseMO->getParent()); 634 UseMO->getParent()->eraseFromParent(); 635 continue; 636 } 637 638 // The use isn't an extend. Truncate back to the type we originally loaded. 639 // This is free on many targets. 640 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt); 641 } 642 643 MI.getOperand(0).setReg(ChosenDstReg); 644 Observer.changedInstr(MI); 645 } 646 647 bool CombinerHelper::matchCombineLoadWithAndMask(MachineInstr &MI, 648 BuildFnTy &MatchInfo) { 649 assert(MI.getOpcode() == TargetOpcode::G_AND); 650 651 // If we have the following code: 652 // %mask = G_CONSTANT 255 653 // %ld = G_LOAD %ptr, (load s16) 654 // %and = G_AND %ld, %mask 655 // 656 // Try to fold it into 657 // %ld = G_ZEXTLOAD %ptr, (load s8) 658 659 Register Dst = MI.getOperand(0).getReg(); 660 if (MRI.getType(Dst).isVector()) 661 return false; 662 663 auto MaybeMask = 664 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 665 if (!MaybeMask) 666 return false; 667 668 APInt MaskVal = MaybeMask->Value; 669 670 if (!MaskVal.isMask()) 671 return false; 672 673 Register SrcReg = MI.getOperand(1).getReg(); 674 GAnyLoad *LoadMI = getOpcodeDef<GAnyLoad>(SrcReg, MRI); 675 if (!LoadMI || !MRI.hasOneNonDBGUse(LoadMI->getDstReg()) || 676 !LoadMI->isSimple()) 677 return false; 678 679 Register LoadReg = LoadMI->getDstReg(); 680 LLT LoadTy = MRI.getType(LoadReg); 681 Register PtrReg = LoadMI->getPointerReg(); 682 uint64_t LoadSizeBits = LoadMI->getMemSizeInBits(); 683 unsigned MaskSizeBits = MaskVal.countTrailingOnes(); 684 685 // The mask may not be larger than the in-memory type, as it might cover sign 686 // extended bits 687 if (MaskSizeBits > LoadSizeBits) 688 return false; 689 690 // If the mask covers the whole destination register, there's nothing to 691 // extend 692 if (MaskSizeBits >= LoadTy.getSizeInBits()) 693 return false; 694 695 // Most targets cannot deal with loads of size < 8 and need to re-legalize to 696 // at least byte loads. Avoid creating such loads here 697 if (MaskSizeBits < 8 || !isPowerOf2_32(MaskSizeBits)) 698 return false; 699 700 const MachineMemOperand &MMO = LoadMI->getMMO(); 701 LegalityQuery::MemDesc MemDesc(MMO); 702 MemDesc.MemoryTy = LLT::scalar(MaskSizeBits); 703 if (!isLegalOrBeforeLegalizer( 704 {TargetOpcode::G_ZEXTLOAD, {LoadTy, MRI.getType(PtrReg)}, {MemDesc}})) 705 return false; 706 707 MatchInfo = [=](MachineIRBuilder &B) { 708 B.setInstrAndDebugLoc(*LoadMI); 709 auto &MF = B.getMF(); 710 auto PtrInfo = MMO.getPointerInfo(); 711 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, MaskSizeBits / 8); 712 B.buildLoadInstr(TargetOpcode::G_ZEXTLOAD, Dst, PtrReg, *NewMMO); 713 }; 714 return true; 715 } 716 717 bool CombinerHelper::isPredecessor(const MachineInstr &DefMI, 718 const MachineInstr &UseMI) { 719 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() && 720 "shouldn't consider debug uses"); 721 assert(DefMI.getParent() == UseMI.getParent()); 722 if (&DefMI == &UseMI) 723 return true; 724 const MachineBasicBlock &MBB = *DefMI.getParent(); 725 auto DefOrUse = find_if(MBB, [&DefMI, &UseMI](const MachineInstr &MI) { 726 return &MI == &DefMI || &MI == &UseMI; 727 }); 728 if (DefOrUse == MBB.end()) 729 llvm_unreachable("Block must contain both DefMI and UseMI!"); 730 return &*DefOrUse == &DefMI; 731 } 732 733 bool CombinerHelper::dominates(const MachineInstr &DefMI, 734 const MachineInstr &UseMI) { 735 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() && 736 "shouldn't consider debug uses"); 737 if (MDT) 738 return MDT->dominates(&DefMI, &UseMI); 739 else if (DefMI.getParent() != UseMI.getParent()) 740 return false; 741 742 return isPredecessor(DefMI, UseMI); 743 } 744 745 bool CombinerHelper::matchSextTruncSextLoad(MachineInstr &MI) { 746 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 747 Register SrcReg = MI.getOperand(1).getReg(); 748 Register LoadUser = SrcReg; 749 750 if (MRI.getType(SrcReg).isVector()) 751 return false; 752 753 Register TruncSrc; 754 if (mi_match(SrcReg, MRI, m_GTrunc(m_Reg(TruncSrc)))) 755 LoadUser = TruncSrc; 756 757 uint64_t SizeInBits = MI.getOperand(2).getImm(); 758 // If the source is a G_SEXTLOAD from the same bit width, then we don't 759 // need any extend at all, just a truncate. 760 if (auto *LoadMI = getOpcodeDef<GSExtLoad>(LoadUser, MRI)) { 761 // If truncating more than the original extended value, abort. 762 auto LoadSizeBits = LoadMI->getMemSizeInBits(); 763 if (TruncSrc && MRI.getType(TruncSrc).getSizeInBits() < LoadSizeBits) 764 return false; 765 if (LoadSizeBits == SizeInBits) 766 return true; 767 } 768 return false; 769 } 770 771 void CombinerHelper::applySextTruncSextLoad(MachineInstr &MI) { 772 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 773 Builder.setInstrAndDebugLoc(MI); 774 Builder.buildCopy(MI.getOperand(0).getReg(), MI.getOperand(1).getReg()); 775 MI.eraseFromParent(); 776 } 777 778 bool CombinerHelper::matchSextInRegOfLoad( 779 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 780 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 781 782 // Only supports scalars for now. 783 if (MRI.getType(MI.getOperand(0).getReg()).isVector()) 784 return false; 785 786 Register SrcReg = MI.getOperand(1).getReg(); 787 auto *LoadDef = getOpcodeDef<GLoad>(SrcReg, MRI); 788 if (!LoadDef || !MRI.hasOneNonDBGUse(LoadDef->getOperand(0).getReg()) || 789 !LoadDef->isSimple()) 790 return false; 791 792 // If the sign extend extends from a narrower width than the load's width, 793 // then we can narrow the load width when we combine to a G_SEXTLOAD. 794 // Avoid widening the load at all. 795 unsigned NewSizeBits = std::min((uint64_t)MI.getOperand(2).getImm(), 796 LoadDef->getMemSizeInBits()); 797 798 // Don't generate G_SEXTLOADs with a < 1 byte width. 799 if (NewSizeBits < 8) 800 return false; 801 // Don't bother creating a non-power-2 sextload, it will likely be broken up 802 // anyway for most targets. 803 if (!isPowerOf2_32(NewSizeBits)) 804 return false; 805 806 const MachineMemOperand &MMO = LoadDef->getMMO(); 807 LegalityQuery::MemDesc MMDesc(MMO); 808 MMDesc.MemoryTy = LLT::scalar(NewSizeBits); 809 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SEXTLOAD, 810 {MRI.getType(LoadDef->getDstReg()), 811 MRI.getType(LoadDef->getPointerReg())}, 812 {MMDesc}})) 813 return false; 814 815 MatchInfo = std::make_tuple(LoadDef->getDstReg(), NewSizeBits); 816 return true; 817 } 818 819 void CombinerHelper::applySextInRegOfLoad( 820 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 821 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 822 Register LoadReg; 823 unsigned ScalarSizeBits; 824 std::tie(LoadReg, ScalarSizeBits) = MatchInfo; 825 GLoad *LoadDef = cast<GLoad>(MRI.getVRegDef(LoadReg)); 826 827 // If we have the following: 828 // %ld = G_LOAD %ptr, (load 2) 829 // %ext = G_SEXT_INREG %ld, 8 830 // ==> 831 // %ld = G_SEXTLOAD %ptr (load 1) 832 833 auto &MMO = LoadDef->getMMO(); 834 Builder.setInstrAndDebugLoc(*LoadDef); 835 auto &MF = Builder.getMF(); 836 auto PtrInfo = MMO.getPointerInfo(); 837 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, ScalarSizeBits / 8); 838 Builder.buildLoadInstr(TargetOpcode::G_SEXTLOAD, MI.getOperand(0).getReg(), 839 LoadDef->getPointerReg(), *NewMMO); 840 MI.eraseFromParent(); 841 } 842 843 bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr, 844 Register &Base, Register &Offset) { 845 auto &MF = *MI.getParent()->getParent(); 846 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 847 848 #ifndef NDEBUG 849 unsigned Opcode = MI.getOpcode(); 850 assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD || 851 Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE); 852 #endif 853 854 Base = MI.getOperand(1).getReg(); 855 MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base); 856 if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) 857 return false; 858 859 LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI); 860 // FIXME: The following use traversal needs a bail out for patholigical cases. 861 for (auto &Use : MRI.use_nodbg_instructions(Base)) { 862 if (Use.getOpcode() != TargetOpcode::G_PTR_ADD) 863 continue; 864 865 Offset = Use.getOperand(2).getReg(); 866 if (!ForceLegalIndexing && 867 !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) { 868 LLVM_DEBUG(dbgs() << " Ignoring candidate with illegal addrmode: " 869 << Use); 870 continue; 871 } 872 873 // Make sure the offset calculation is before the potentially indexed op. 874 // FIXME: we really care about dependency here. The offset calculation might 875 // be movable. 876 MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset); 877 if (!OffsetDef || !dominates(*OffsetDef, MI)) { 878 LLVM_DEBUG(dbgs() << " Ignoring candidate with offset after mem-op: " 879 << Use); 880 continue; 881 } 882 883 // FIXME: check whether all uses of Base are load/store with foldable 884 // addressing modes. If so, using the normal addr-modes is better than 885 // forming an indexed one. 886 887 bool MemOpDominatesAddrUses = true; 888 for (auto &PtrAddUse : 889 MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) { 890 if (!dominates(MI, PtrAddUse)) { 891 MemOpDominatesAddrUses = false; 892 break; 893 } 894 } 895 896 if (!MemOpDominatesAddrUses) { 897 LLVM_DEBUG( 898 dbgs() << " Ignoring candidate as memop does not dominate uses: " 899 << Use); 900 continue; 901 } 902 903 LLVM_DEBUG(dbgs() << " Found match: " << Use); 904 Addr = Use.getOperand(0).getReg(); 905 return true; 906 } 907 908 return false; 909 } 910 911 bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr, 912 Register &Base, Register &Offset) { 913 auto &MF = *MI.getParent()->getParent(); 914 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 915 916 #ifndef NDEBUG 917 unsigned Opcode = MI.getOpcode(); 918 assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD || 919 Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE); 920 #endif 921 922 Addr = MI.getOperand(1).getReg(); 923 MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI); 924 if (!AddrDef || MRI.hasOneNonDBGUse(Addr)) 925 return false; 926 927 Base = AddrDef->getOperand(1).getReg(); 928 Offset = AddrDef->getOperand(2).getReg(); 929 930 LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI); 931 932 if (!ForceLegalIndexing && 933 !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) { 934 LLVM_DEBUG(dbgs() << " Skipping, not legal for target"); 935 return false; 936 } 937 938 MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI); 939 if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) { 940 LLVM_DEBUG(dbgs() << " Skipping, frame index would need copy anyway."); 941 return false; 942 } 943 944 if (MI.getOpcode() == TargetOpcode::G_STORE) { 945 // Would require a copy. 946 if (Base == MI.getOperand(0).getReg()) { 947 LLVM_DEBUG(dbgs() << " Skipping, storing base so need copy anyway."); 948 return false; 949 } 950 951 // We're expecting one use of Addr in MI, but it could also be the 952 // value stored, which isn't actually dominated by the instruction. 953 if (MI.getOperand(0).getReg() == Addr) { 954 LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses"); 955 return false; 956 } 957 } 958 959 // FIXME: check whether all uses of the base pointer are constant PtrAdds. 960 // That might allow us to end base's liveness here by adjusting the constant. 961 962 for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) { 963 if (!dominates(MI, UseMI)) { 964 LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses."); 965 return false; 966 } 967 } 968 969 return true; 970 } 971 972 bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) { 973 IndexedLoadStoreMatchInfo MatchInfo; 974 if (matchCombineIndexedLoadStore(MI, MatchInfo)) { 975 applyCombineIndexedLoadStore(MI, MatchInfo); 976 return true; 977 } 978 return false; 979 } 980 981 bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) { 982 unsigned Opcode = MI.getOpcode(); 983 if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD && 984 Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE) 985 return false; 986 987 // For now, no targets actually support these opcodes so don't waste time 988 // running these unless we're forced to for testing. 989 if (!ForceLegalIndexing) 990 return false; 991 992 MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base, 993 MatchInfo.Offset); 994 if (!MatchInfo.IsPre && 995 !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base, 996 MatchInfo.Offset)) 997 return false; 998 999 return true; 1000 } 1001 1002 void CombinerHelper::applyCombineIndexedLoadStore( 1003 MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) { 1004 MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr); 1005 MachineIRBuilder MIRBuilder(MI); 1006 unsigned Opcode = MI.getOpcode(); 1007 bool IsStore = Opcode == TargetOpcode::G_STORE; 1008 unsigned NewOpcode; 1009 switch (Opcode) { 1010 case TargetOpcode::G_LOAD: 1011 NewOpcode = TargetOpcode::G_INDEXED_LOAD; 1012 break; 1013 case TargetOpcode::G_SEXTLOAD: 1014 NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD; 1015 break; 1016 case TargetOpcode::G_ZEXTLOAD: 1017 NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD; 1018 break; 1019 case TargetOpcode::G_STORE: 1020 NewOpcode = TargetOpcode::G_INDEXED_STORE; 1021 break; 1022 default: 1023 llvm_unreachable("Unknown load/store opcode"); 1024 } 1025 1026 auto MIB = MIRBuilder.buildInstr(NewOpcode); 1027 if (IsStore) { 1028 MIB.addDef(MatchInfo.Addr); 1029 MIB.addUse(MI.getOperand(0).getReg()); 1030 } else { 1031 MIB.addDef(MI.getOperand(0).getReg()); 1032 MIB.addDef(MatchInfo.Addr); 1033 } 1034 1035 MIB.addUse(MatchInfo.Base); 1036 MIB.addUse(MatchInfo.Offset); 1037 MIB.addImm(MatchInfo.IsPre); 1038 MI.eraseFromParent(); 1039 AddrDef.eraseFromParent(); 1040 1041 LLVM_DEBUG(dbgs() << " Combinined to indexed operation"); 1042 } 1043 1044 bool CombinerHelper::matchCombineDivRem(MachineInstr &MI, 1045 MachineInstr *&OtherMI) { 1046 unsigned Opcode = MI.getOpcode(); 1047 bool IsDiv, IsSigned; 1048 1049 switch (Opcode) { 1050 default: 1051 llvm_unreachable("Unexpected opcode!"); 1052 case TargetOpcode::G_SDIV: 1053 case TargetOpcode::G_UDIV: { 1054 IsDiv = true; 1055 IsSigned = Opcode == TargetOpcode::G_SDIV; 1056 break; 1057 } 1058 case TargetOpcode::G_SREM: 1059 case TargetOpcode::G_UREM: { 1060 IsDiv = false; 1061 IsSigned = Opcode == TargetOpcode::G_SREM; 1062 break; 1063 } 1064 } 1065 1066 Register Src1 = MI.getOperand(1).getReg(); 1067 unsigned DivOpcode, RemOpcode, DivremOpcode; 1068 if (IsSigned) { 1069 DivOpcode = TargetOpcode::G_SDIV; 1070 RemOpcode = TargetOpcode::G_SREM; 1071 DivremOpcode = TargetOpcode::G_SDIVREM; 1072 } else { 1073 DivOpcode = TargetOpcode::G_UDIV; 1074 RemOpcode = TargetOpcode::G_UREM; 1075 DivremOpcode = TargetOpcode::G_UDIVREM; 1076 } 1077 1078 if (!isLegalOrBeforeLegalizer({DivremOpcode, {MRI.getType(Src1)}})) 1079 return false; 1080 1081 // Combine: 1082 // %div:_ = G_[SU]DIV %src1:_, %src2:_ 1083 // %rem:_ = G_[SU]REM %src1:_, %src2:_ 1084 // into: 1085 // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_ 1086 1087 // Combine: 1088 // %rem:_ = G_[SU]REM %src1:_, %src2:_ 1089 // %div:_ = G_[SU]DIV %src1:_, %src2:_ 1090 // into: 1091 // %div:_, %rem:_ = G_[SU]DIVREM %src1:_, %src2:_ 1092 1093 for (auto &UseMI : MRI.use_nodbg_instructions(Src1)) { 1094 if (MI.getParent() == UseMI.getParent() && 1095 ((IsDiv && UseMI.getOpcode() == RemOpcode) || 1096 (!IsDiv && UseMI.getOpcode() == DivOpcode)) && 1097 matchEqualDefs(MI.getOperand(2), UseMI.getOperand(2))) { 1098 OtherMI = &UseMI; 1099 return true; 1100 } 1101 } 1102 1103 return false; 1104 } 1105 1106 void CombinerHelper::applyCombineDivRem(MachineInstr &MI, 1107 MachineInstr *&OtherMI) { 1108 unsigned Opcode = MI.getOpcode(); 1109 assert(OtherMI && "OtherMI shouldn't be empty."); 1110 1111 Register DestDivReg, DestRemReg; 1112 if (Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_UDIV) { 1113 DestDivReg = MI.getOperand(0).getReg(); 1114 DestRemReg = OtherMI->getOperand(0).getReg(); 1115 } else { 1116 DestDivReg = OtherMI->getOperand(0).getReg(); 1117 DestRemReg = MI.getOperand(0).getReg(); 1118 } 1119 1120 bool IsSigned = 1121 Opcode == TargetOpcode::G_SDIV || Opcode == TargetOpcode::G_SREM; 1122 1123 // Check which instruction is first in the block so we don't break def-use 1124 // deps by "moving" the instruction incorrectly. 1125 if (dominates(MI, *OtherMI)) 1126 Builder.setInstrAndDebugLoc(MI); 1127 else 1128 Builder.setInstrAndDebugLoc(*OtherMI); 1129 1130 Builder.buildInstr(IsSigned ? TargetOpcode::G_SDIVREM 1131 : TargetOpcode::G_UDIVREM, 1132 {DestDivReg, DestRemReg}, 1133 {MI.getOperand(1).getReg(), MI.getOperand(2).getReg()}); 1134 MI.eraseFromParent(); 1135 OtherMI->eraseFromParent(); 1136 } 1137 1138 bool CombinerHelper::matchOptBrCondByInvertingCond(MachineInstr &MI, 1139 MachineInstr *&BrCond) { 1140 assert(MI.getOpcode() == TargetOpcode::G_BR); 1141 1142 // Try to match the following: 1143 // bb1: 1144 // G_BRCOND %c1, %bb2 1145 // G_BR %bb3 1146 // bb2: 1147 // ... 1148 // bb3: 1149 1150 // The above pattern does not have a fall through to the successor bb2, always 1151 // resulting in a branch no matter which path is taken. Here we try to find 1152 // and replace that pattern with conditional branch to bb3 and otherwise 1153 // fallthrough to bb2. This is generally better for branch predictors. 1154 1155 MachineBasicBlock *MBB = MI.getParent(); 1156 MachineBasicBlock::iterator BrIt(MI); 1157 if (BrIt == MBB->begin()) 1158 return false; 1159 assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator"); 1160 1161 BrCond = &*std::prev(BrIt); 1162 if (BrCond->getOpcode() != TargetOpcode::G_BRCOND) 1163 return false; 1164 1165 // Check that the next block is the conditional branch target. Also make sure 1166 // that it isn't the same as the G_BR's target (otherwise, this will loop.) 1167 MachineBasicBlock *BrCondTarget = BrCond->getOperand(1).getMBB(); 1168 return BrCondTarget != MI.getOperand(0).getMBB() && 1169 MBB->isLayoutSuccessor(BrCondTarget); 1170 } 1171 1172 void CombinerHelper::applyOptBrCondByInvertingCond(MachineInstr &MI, 1173 MachineInstr *&BrCond) { 1174 MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB(); 1175 Builder.setInstrAndDebugLoc(*BrCond); 1176 LLT Ty = MRI.getType(BrCond->getOperand(0).getReg()); 1177 // FIXME: Does int/fp matter for this? If so, we might need to restrict 1178 // this to i1 only since we might not know for sure what kind of 1179 // compare generated the condition value. 1180 auto True = Builder.buildConstant( 1181 Ty, getICmpTrueVal(getTargetLowering(), false, false)); 1182 auto Xor = Builder.buildXor(Ty, BrCond->getOperand(0), True); 1183 1184 auto *FallthroughBB = BrCond->getOperand(1).getMBB(); 1185 Observer.changingInstr(MI); 1186 MI.getOperand(0).setMBB(FallthroughBB); 1187 Observer.changedInstr(MI); 1188 1189 // Change the conditional branch to use the inverted condition and 1190 // new target block. 1191 Observer.changingInstr(*BrCond); 1192 BrCond->getOperand(0).setReg(Xor.getReg(0)); 1193 BrCond->getOperand(1).setMBB(BrTarget); 1194 Observer.changedInstr(*BrCond); 1195 } 1196 1197 static Type *getTypeForLLT(LLT Ty, LLVMContext &C) { 1198 if (Ty.isVector()) 1199 return FixedVectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()), 1200 Ty.getNumElements()); 1201 return IntegerType::get(C, Ty.getSizeInBits()); 1202 } 1203 1204 bool CombinerHelper::tryEmitMemcpyInline(MachineInstr &MI) { 1205 MachineIRBuilder HelperBuilder(MI); 1206 GISelObserverWrapper DummyObserver; 1207 LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder); 1208 return Helper.lowerMemcpyInline(MI) == 1209 LegalizerHelper::LegalizeResult::Legalized; 1210 } 1211 1212 bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) { 1213 MachineIRBuilder HelperBuilder(MI); 1214 GISelObserverWrapper DummyObserver; 1215 LegalizerHelper Helper(HelperBuilder.getMF(), DummyObserver, HelperBuilder); 1216 return Helper.lowerMemCpyFamily(MI, MaxLen) == 1217 LegalizerHelper::LegalizeResult::Legalized; 1218 } 1219 1220 static Optional<APFloat> constantFoldFpUnary(unsigned Opcode, LLT DstTy, 1221 const Register Op, 1222 const MachineRegisterInfo &MRI) { 1223 const ConstantFP *MaybeCst = getConstantFPVRegVal(Op, MRI); 1224 if (!MaybeCst) 1225 return None; 1226 1227 APFloat V = MaybeCst->getValueAPF(); 1228 switch (Opcode) { 1229 default: 1230 llvm_unreachable("Unexpected opcode!"); 1231 case TargetOpcode::G_FNEG: { 1232 V.changeSign(); 1233 return V; 1234 } 1235 case TargetOpcode::G_FABS: { 1236 V.clearSign(); 1237 return V; 1238 } 1239 case TargetOpcode::G_FPTRUNC: 1240 break; 1241 case TargetOpcode::G_FSQRT: { 1242 bool Unused; 1243 V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused); 1244 V = APFloat(sqrt(V.convertToDouble())); 1245 break; 1246 } 1247 case TargetOpcode::G_FLOG2: { 1248 bool Unused; 1249 V.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &Unused); 1250 V = APFloat(log2(V.convertToDouble())); 1251 break; 1252 } 1253 } 1254 // Convert `APFloat` to appropriate IEEE type depending on `DstTy`. Otherwise, 1255 // `buildFConstant` will assert on size mismatch. Only `G_FPTRUNC`, `G_FSQRT`, 1256 // and `G_FLOG2` reach here. 1257 bool Unused; 1258 V.convert(getFltSemanticForLLT(DstTy), APFloat::rmNearestTiesToEven, &Unused); 1259 return V; 1260 } 1261 1262 bool CombinerHelper::matchCombineConstantFoldFpUnary(MachineInstr &MI, 1263 Optional<APFloat> &Cst) { 1264 Register DstReg = MI.getOperand(0).getReg(); 1265 Register SrcReg = MI.getOperand(1).getReg(); 1266 LLT DstTy = MRI.getType(DstReg); 1267 Cst = constantFoldFpUnary(MI.getOpcode(), DstTy, SrcReg, MRI); 1268 return Cst.hasValue(); 1269 } 1270 1271 void CombinerHelper::applyCombineConstantFoldFpUnary(MachineInstr &MI, 1272 Optional<APFloat> &Cst) { 1273 assert(Cst.hasValue() && "Optional is unexpectedly empty!"); 1274 Builder.setInstrAndDebugLoc(MI); 1275 MachineFunction &MF = Builder.getMF(); 1276 auto *FPVal = ConstantFP::get(MF.getFunction().getContext(), *Cst); 1277 Register DstReg = MI.getOperand(0).getReg(); 1278 Builder.buildFConstant(DstReg, *FPVal); 1279 MI.eraseFromParent(); 1280 } 1281 1282 bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI, 1283 PtrAddChain &MatchInfo) { 1284 // We're trying to match the following pattern: 1285 // %t1 = G_PTR_ADD %base, G_CONSTANT imm1 1286 // %root = G_PTR_ADD %t1, G_CONSTANT imm2 1287 // --> 1288 // %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2) 1289 1290 if (MI.getOpcode() != TargetOpcode::G_PTR_ADD) 1291 return false; 1292 1293 Register Add2 = MI.getOperand(1).getReg(); 1294 Register Imm1 = MI.getOperand(2).getReg(); 1295 auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI); 1296 if (!MaybeImmVal) 1297 return false; 1298 1299 MachineInstr *Add2Def = MRI.getVRegDef(Add2); 1300 if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD) 1301 return false; 1302 1303 Register Base = Add2Def->getOperand(1).getReg(); 1304 Register Imm2 = Add2Def->getOperand(2).getReg(); 1305 auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI); 1306 if (!MaybeImm2Val) 1307 return false; 1308 1309 // Check if the new combined immediate forms an illegal addressing mode. 1310 // Do not combine if it was legal before but would get illegal. 1311 // To do so, we need to find a load/store user of the pointer to get 1312 // the access type. 1313 Type *AccessTy = nullptr; 1314 auto &MF = *MI.getMF(); 1315 for (auto &UseMI : MRI.use_nodbg_instructions(MI.getOperand(0).getReg())) { 1316 if (auto *LdSt = dyn_cast<GLoadStore>(&UseMI)) { 1317 AccessTy = getTypeForLLT(MRI.getType(LdSt->getReg(0)), 1318 MF.getFunction().getContext()); 1319 break; 1320 } 1321 } 1322 TargetLoweringBase::AddrMode AMNew; 1323 APInt CombinedImm = MaybeImmVal->Value + MaybeImm2Val->Value; 1324 AMNew.BaseOffs = CombinedImm.getSExtValue(); 1325 if (AccessTy) { 1326 AMNew.HasBaseReg = true; 1327 TargetLoweringBase::AddrMode AMOld; 1328 AMOld.BaseOffs = MaybeImm2Val->Value.getSExtValue(); 1329 AMOld.HasBaseReg = true; 1330 unsigned AS = MRI.getType(Add2).getAddressSpace(); 1331 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 1332 if (TLI.isLegalAddressingMode(MF.getDataLayout(), AMOld, AccessTy, AS) && 1333 !TLI.isLegalAddressingMode(MF.getDataLayout(), AMNew, AccessTy, AS)) 1334 return false; 1335 } 1336 1337 // Pass the combined immediate to the apply function. 1338 MatchInfo.Imm = AMNew.BaseOffs; 1339 MatchInfo.Base = Base; 1340 MatchInfo.Bank = getRegBank(Imm2); 1341 return true; 1342 } 1343 1344 void CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI, 1345 PtrAddChain &MatchInfo) { 1346 assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD"); 1347 MachineIRBuilder MIB(MI); 1348 LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg()); 1349 auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm); 1350 setRegBank(NewOffset.getReg(0), MatchInfo.Bank); 1351 Observer.changingInstr(MI); 1352 MI.getOperand(1).setReg(MatchInfo.Base); 1353 MI.getOperand(2).setReg(NewOffset.getReg(0)); 1354 Observer.changedInstr(MI); 1355 } 1356 1357 bool CombinerHelper::matchShiftImmedChain(MachineInstr &MI, 1358 RegisterImmPair &MatchInfo) { 1359 // We're trying to match the following pattern with any of 1360 // G_SHL/G_ASHR/G_LSHR/G_SSHLSAT/G_USHLSAT shift instructions: 1361 // %t1 = SHIFT %base, G_CONSTANT imm1 1362 // %root = SHIFT %t1, G_CONSTANT imm2 1363 // --> 1364 // %root = SHIFT %base, G_CONSTANT (imm1 + imm2) 1365 1366 unsigned Opcode = MI.getOpcode(); 1367 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR || 1368 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT || 1369 Opcode == TargetOpcode::G_USHLSAT) && 1370 "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT"); 1371 1372 Register Shl2 = MI.getOperand(1).getReg(); 1373 Register Imm1 = MI.getOperand(2).getReg(); 1374 auto MaybeImmVal = getIConstantVRegValWithLookThrough(Imm1, MRI); 1375 if (!MaybeImmVal) 1376 return false; 1377 1378 MachineInstr *Shl2Def = MRI.getUniqueVRegDef(Shl2); 1379 if (Shl2Def->getOpcode() != Opcode) 1380 return false; 1381 1382 Register Base = Shl2Def->getOperand(1).getReg(); 1383 Register Imm2 = Shl2Def->getOperand(2).getReg(); 1384 auto MaybeImm2Val = getIConstantVRegValWithLookThrough(Imm2, MRI); 1385 if (!MaybeImm2Val) 1386 return false; 1387 1388 // Pass the combined immediate to the apply function. 1389 MatchInfo.Imm = 1390 (MaybeImmVal->Value.getSExtValue() + MaybeImm2Val->Value).getSExtValue(); 1391 MatchInfo.Reg = Base; 1392 1393 // There is no simple replacement for a saturating unsigned left shift that 1394 // exceeds the scalar size. 1395 if (Opcode == TargetOpcode::G_USHLSAT && 1396 MatchInfo.Imm >= MRI.getType(Shl2).getScalarSizeInBits()) 1397 return false; 1398 1399 return true; 1400 } 1401 1402 void CombinerHelper::applyShiftImmedChain(MachineInstr &MI, 1403 RegisterImmPair &MatchInfo) { 1404 unsigned Opcode = MI.getOpcode(); 1405 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR || 1406 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_SSHLSAT || 1407 Opcode == TargetOpcode::G_USHLSAT) && 1408 "Expected G_SHL, G_ASHR, G_LSHR, G_SSHLSAT or G_USHLSAT"); 1409 1410 Builder.setInstrAndDebugLoc(MI); 1411 LLT Ty = MRI.getType(MI.getOperand(1).getReg()); 1412 unsigned const ScalarSizeInBits = Ty.getScalarSizeInBits(); 1413 auto Imm = MatchInfo.Imm; 1414 1415 if (Imm >= ScalarSizeInBits) { 1416 // Any logical shift that exceeds scalar size will produce zero. 1417 if (Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_LSHR) { 1418 Builder.buildConstant(MI.getOperand(0), 0); 1419 MI.eraseFromParent(); 1420 return; 1421 } 1422 // Arithmetic shift and saturating signed left shift have no effect beyond 1423 // scalar size. 1424 Imm = ScalarSizeInBits - 1; 1425 } 1426 1427 LLT ImmTy = MRI.getType(MI.getOperand(2).getReg()); 1428 Register NewImm = Builder.buildConstant(ImmTy, Imm).getReg(0); 1429 Observer.changingInstr(MI); 1430 MI.getOperand(1).setReg(MatchInfo.Reg); 1431 MI.getOperand(2).setReg(NewImm); 1432 Observer.changedInstr(MI); 1433 } 1434 1435 bool CombinerHelper::matchShiftOfShiftedLogic(MachineInstr &MI, 1436 ShiftOfShiftedLogic &MatchInfo) { 1437 // We're trying to match the following pattern with any of 1438 // G_SHL/G_ASHR/G_LSHR/G_USHLSAT/G_SSHLSAT shift instructions in combination 1439 // with any of G_AND/G_OR/G_XOR logic instructions. 1440 // %t1 = SHIFT %X, G_CONSTANT C0 1441 // %t2 = LOGIC %t1, %Y 1442 // %root = SHIFT %t2, G_CONSTANT C1 1443 // --> 1444 // %t3 = SHIFT %X, G_CONSTANT (C0+C1) 1445 // %t4 = SHIFT %Y, G_CONSTANT C1 1446 // %root = LOGIC %t3, %t4 1447 unsigned ShiftOpcode = MI.getOpcode(); 1448 assert((ShiftOpcode == TargetOpcode::G_SHL || 1449 ShiftOpcode == TargetOpcode::G_ASHR || 1450 ShiftOpcode == TargetOpcode::G_LSHR || 1451 ShiftOpcode == TargetOpcode::G_USHLSAT || 1452 ShiftOpcode == TargetOpcode::G_SSHLSAT) && 1453 "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT"); 1454 1455 // Match a one-use bitwise logic op. 1456 Register LogicDest = MI.getOperand(1).getReg(); 1457 if (!MRI.hasOneNonDBGUse(LogicDest)) 1458 return false; 1459 1460 MachineInstr *LogicMI = MRI.getUniqueVRegDef(LogicDest); 1461 unsigned LogicOpcode = LogicMI->getOpcode(); 1462 if (LogicOpcode != TargetOpcode::G_AND && LogicOpcode != TargetOpcode::G_OR && 1463 LogicOpcode != TargetOpcode::G_XOR) 1464 return false; 1465 1466 // Find a matching one-use shift by constant. 1467 const Register C1 = MI.getOperand(2).getReg(); 1468 auto MaybeImmVal = getIConstantVRegValWithLookThrough(C1, MRI); 1469 if (!MaybeImmVal) 1470 return false; 1471 1472 const uint64_t C1Val = MaybeImmVal->Value.getZExtValue(); 1473 1474 auto matchFirstShift = [&](const MachineInstr *MI, uint64_t &ShiftVal) { 1475 // Shift should match previous one and should be a one-use. 1476 if (MI->getOpcode() != ShiftOpcode || 1477 !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg())) 1478 return false; 1479 1480 // Must be a constant. 1481 auto MaybeImmVal = 1482 getIConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI); 1483 if (!MaybeImmVal) 1484 return false; 1485 1486 ShiftVal = MaybeImmVal->Value.getSExtValue(); 1487 return true; 1488 }; 1489 1490 // Logic ops are commutative, so check each operand for a match. 1491 Register LogicMIReg1 = LogicMI->getOperand(1).getReg(); 1492 MachineInstr *LogicMIOp1 = MRI.getUniqueVRegDef(LogicMIReg1); 1493 Register LogicMIReg2 = LogicMI->getOperand(2).getReg(); 1494 MachineInstr *LogicMIOp2 = MRI.getUniqueVRegDef(LogicMIReg2); 1495 uint64_t C0Val; 1496 1497 if (matchFirstShift(LogicMIOp1, C0Val)) { 1498 MatchInfo.LogicNonShiftReg = LogicMIReg2; 1499 MatchInfo.Shift2 = LogicMIOp1; 1500 } else if (matchFirstShift(LogicMIOp2, C0Val)) { 1501 MatchInfo.LogicNonShiftReg = LogicMIReg1; 1502 MatchInfo.Shift2 = LogicMIOp2; 1503 } else 1504 return false; 1505 1506 MatchInfo.ValSum = C0Val + C1Val; 1507 1508 // The fold is not valid if the sum of the shift values exceeds bitwidth. 1509 if (MatchInfo.ValSum >= MRI.getType(LogicDest).getScalarSizeInBits()) 1510 return false; 1511 1512 MatchInfo.Logic = LogicMI; 1513 return true; 1514 } 1515 1516 void CombinerHelper::applyShiftOfShiftedLogic(MachineInstr &MI, 1517 ShiftOfShiftedLogic &MatchInfo) { 1518 unsigned Opcode = MI.getOpcode(); 1519 assert((Opcode == TargetOpcode::G_SHL || Opcode == TargetOpcode::G_ASHR || 1520 Opcode == TargetOpcode::G_LSHR || Opcode == TargetOpcode::G_USHLSAT || 1521 Opcode == TargetOpcode::G_SSHLSAT) && 1522 "Expected G_SHL, G_ASHR, G_LSHR, G_USHLSAT and G_SSHLSAT"); 1523 1524 LLT ShlType = MRI.getType(MI.getOperand(2).getReg()); 1525 LLT DestType = MRI.getType(MI.getOperand(0).getReg()); 1526 Builder.setInstrAndDebugLoc(MI); 1527 1528 Register Const = Builder.buildConstant(ShlType, MatchInfo.ValSum).getReg(0); 1529 1530 Register Shift1Base = MatchInfo.Shift2->getOperand(1).getReg(); 1531 Register Shift1 = 1532 Builder.buildInstr(Opcode, {DestType}, {Shift1Base, Const}).getReg(0); 1533 1534 Register Shift2Const = MI.getOperand(2).getReg(); 1535 Register Shift2 = Builder 1536 .buildInstr(Opcode, {DestType}, 1537 {MatchInfo.LogicNonShiftReg, Shift2Const}) 1538 .getReg(0); 1539 1540 Register Dest = MI.getOperand(0).getReg(); 1541 Builder.buildInstr(MatchInfo.Logic->getOpcode(), {Dest}, {Shift1, Shift2}); 1542 1543 // These were one use so it's safe to remove them. 1544 MatchInfo.Shift2->eraseFromParentAndMarkDBGValuesForRemoval(); 1545 MatchInfo.Logic->eraseFromParentAndMarkDBGValuesForRemoval(); 1546 1547 MI.eraseFromParent(); 1548 } 1549 1550 bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI, 1551 unsigned &ShiftVal) { 1552 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 1553 auto MaybeImmVal = 1554 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 1555 if (!MaybeImmVal) 1556 return false; 1557 1558 ShiftVal = MaybeImmVal->Value.exactLogBase2(); 1559 return (static_cast<int32_t>(ShiftVal) != -1); 1560 } 1561 1562 void CombinerHelper::applyCombineMulToShl(MachineInstr &MI, 1563 unsigned &ShiftVal) { 1564 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 1565 MachineIRBuilder MIB(MI); 1566 LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg()); 1567 auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal); 1568 Observer.changingInstr(MI); 1569 MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL)); 1570 MI.getOperand(2).setReg(ShiftCst.getReg(0)); 1571 Observer.changedInstr(MI); 1572 } 1573 1574 // shl ([sza]ext x), y => zext (shl x, y), if shift does not overflow source 1575 bool CombinerHelper::matchCombineShlOfExtend(MachineInstr &MI, 1576 RegisterImmPair &MatchData) { 1577 assert(MI.getOpcode() == TargetOpcode::G_SHL && KB); 1578 1579 Register LHS = MI.getOperand(1).getReg(); 1580 1581 Register ExtSrc; 1582 if (!mi_match(LHS, MRI, m_GAnyExt(m_Reg(ExtSrc))) && 1583 !mi_match(LHS, MRI, m_GZExt(m_Reg(ExtSrc))) && 1584 !mi_match(LHS, MRI, m_GSExt(m_Reg(ExtSrc)))) 1585 return false; 1586 1587 // TODO: Should handle vector splat. 1588 Register RHS = MI.getOperand(2).getReg(); 1589 auto MaybeShiftAmtVal = getIConstantVRegValWithLookThrough(RHS, MRI); 1590 if (!MaybeShiftAmtVal) 1591 return false; 1592 1593 if (LI) { 1594 LLT SrcTy = MRI.getType(ExtSrc); 1595 1596 // We only really care about the legality with the shifted value. We can 1597 // pick any type the constant shift amount, so ask the target what to 1598 // use. Otherwise we would have to guess and hope it is reported as legal. 1599 LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(SrcTy); 1600 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_SHL, {SrcTy, ShiftAmtTy}})) 1601 return false; 1602 } 1603 1604 int64_t ShiftAmt = MaybeShiftAmtVal->Value.getSExtValue(); 1605 MatchData.Reg = ExtSrc; 1606 MatchData.Imm = ShiftAmt; 1607 1608 unsigned MinLeadingZeros = KB->getKnownZeroes(ExtSrc).countLeadingOnes(); 1609 return MinLeadingZeros >= ShiftAmt; 1610 } 1611 1612 void CombinerHelper::applyCombineShlOfExtend(MachineInstr &MI, 1613 const RegisterImmPair &MatchData) { 1614 Register ExtSrcReg = MatchData.Reg; 1615 int64_t ShiftAmtVal = MatchData.Imm; 1616 1617 LLT ExtSrcTy = MRI.getType(ExtSrcReg); 1618 Builder.setInstrAndDebugLoc(MI); 1619 auto ShiftAmt = Builder.buildConstant(ExtSrcTy, ShiftAmtVal); 1620 auto NarrowShift = 1621 Builder.buildShl(ExtSrcTy, ExtSrcReg, ShiftAmt, MI.getFlags()); 1622 Builder.buildZExt(MI.getOperand(0), NarrowShift); 1623 MI.eraseFromParent(); 1624 } 1625 1626 bool CombinerHelper::matchCombineMergeUnmerge(MachineInstr &MI, 1627 Register &MatchInfo) { 1628 GMerge &Merge = cast<GMerge>(MI); 1629 SmallVector<Register, 16> MergedValues; 1630 for (unsigned I = 0; I < Merge.getNumSources(); ++I) 1631 MergedValues.emplace_back(Merge.getSourceReg(I)); 1632 1633 auto *Unmerge = getOpcodeDef<GUnmerge>(MergedValues[0], MRI); 1634 if (!Unmerge || Unmerge->getNumDefs() != Merge.getNumSources()) 1635 return false; 1636 1637 for (unsigned I = 0; I < MergedValues.size(); ++I) 1638 if (MergedValues[I] != Unmerge->getReg(I)) 1639 return false; 1640 1641 MatchInfo = Unmerge->getSourceReg(); 1642 return true; 1643 } 1644 1645 static Register peekThroughBitcast(Register Reg, 1646 const MachineRegisterInfo &MRI) { 1647 while (mi_match(Reg, MRI, m_GBitcast(m_Reg(Reg)))) 1648 ; 1649 1650 return Reg; 1651 } 1652 1653 bool CombinerHelper::matchCombineUnmergeMergeToPlainValues( 1654 MachineInstr &MI, SmallVectorImpl<Register> &Operands) { 1655 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 1656 "Expected an unmerge"); 1657 auto &Unmerge = cast<GUnmerge>(MI); 1658 Register SrcReg = peekThroughBitcast(Unmerge.getSourceReg(), MRI); 1659 1660 auto *SrcInstr = getOpcodeDef<GMergeLikeOp>(SrcReg, MRI); 1661 if (!SrcInstr) 1662 return false; 1663 1664 // Check the source type of the merge. 1665 LLT SrcMergeTy = MRI.getType(SrcInstr->getSourceReg(0)); 1666 LLT Dst0Ty = MRI.getType(Unmerge.getReg(0)); 1667 bool SameSize = Dst0Ty.getSizeInBits() == SrcMergeTy.getSizeInBits(); 1668 if (SrcMergeTy != Dst0Ty && !SameSize) 1669 return false; 1670 // They are the same now (modulo a bitcast). 1671 // We can collect all the src registers. 1672 for (unsigned Idx = 0; Idx < SrcInstr->getNumSources(); ++Idx) 1673 Operands.push_back(SrcInstr->getSourceReg(Idx)); 1674 return true; 1675 } 1676 1677 void CombinerHelper::applyCombineUnmergeMergeToPlainValues( 1678 MachineInstr &MI, SmallVectorImpl<Register> &Operands) { 1679 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 1680 "Expected an unmerge"); 1681 assert((MI.getNumOperands() - 1 == Operands.size()) && 1682 "Not enough operands to replace all defs"); 1683 unsigned NumElems = MI.getNumOperands() - 1; 1684 1685 LLT SrcTy = MRI.getType(Operands[0]); 1686 LLT DstTy = MRI.getType(MI.getOperand(0).getReg()); 1687 bool CanReuseInputDirectly = DstTy == SrcTy; 1688 Builder.setInstrAndDebugLoc(MI); 1689 for (unsigned Idx = 0; Idx < NumElems; ++Idx) { 1690 Register DstReg = MI.getOperand(Idx).getReg(); 1691 Register SrcReg = Operands[Idx]; 1692 if (CanReuseInputDirectly) 1693 replaceRegWith(MRI, DstReg, SrcReg); 1694 else 1695 Builder.buildCast(DstReg, SrcReg); 1696 } 1697 MI.eraseFromParent(); 1698 } 1699 1700 bool CombinerHelper::matchCombineUnmergeConstant(MachineInstr &MI, 1701 SmallVectorImpl<APInt> &Csts) { 1702 unsigned SrcIdx = MI.getNumOperands() - 1; 1703 Register SrcReg = MI.getOperand(SrcIdx).getReg(); 1704 MachineInstr *SrcInstr = MRI.getVRegDef(SrcReg); 1705 if (SrcInstr->getOpcode() != TargetOpcode::G_CONSTANT && 1706 SrcInstr->getOpcode() != TargetOpcode::G_FCONSTANT) 1707 return false; 1708 // Break down the big constant in smaller ones. 1709 const MachineOperand &CstVal = SrcInstr->getOperand(1); 1710 APInt Val = SrcInstr->getOpcode() == TargetOpcode::G_CONSTANT 1711 ? CstVal.getCImm()->getValue() 1712 : CstVal.getFPImm()->getValueAPF().bitcastToAPInt(); 1713 1714 LLT Dst0Ty = MRI.getType(MI.getOperand(0).getReg()); 1715 unsigned ShiftAmt = Dst0Ty.getSizeInBits(); 1716 // Unmerge a constant. 1717 for (unsigned Idx = 0; Idx != SrcIdx; ++Idx) { 1718 Csts.emplace_back(Val.trunc(ShiftAmt)); 1719 Val = Val.lshr(ShiftAmt); 1720 } 1721 1722 return true; 1723 } 1724 1725 void CombinerHelper::applyCombineUnmergeConstant(MachineInstr &MI, 1726 SmallVectorImpl<APInt> &Csts) { 1727 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 1728 "Expected an unmerge"); 1729 assert((MI.getNumOperands() - 1 == Csts.size()) && 1730 "Not enough operands to replace all defs"); 1731 unsigned NumElems = MI.getNumOperands() - 1; 1732 Builder.setInstrAndDebugLoc(MI); 1733 for (unsigned Idx = 0; Idx < NumElems; ++Idx) { 1734 Register DstReg = MI.getOperand(Idx).getReg(); 1735 Builder.buildConstant(DstReg, Csts[Idx]); 1736 } 1737 1738 MI.eraseFromParent(); 1739 } 1740 1741 bool CombinerHelper::matchCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) { 1742 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 1743 "Expected an unmerge"); 1744 // Check that all the lanes are dead except the first one. 1745 for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) { 1746 if (!MRI.use_nodbg_empty(MI.getOperand(Idx).getReg())) 1747 return false; 1748 } 1749 return true; 1750 } 1751 1752 void CombinerHelper::applyCombineUnmergeWithDeadLanesToTrunc(MachineInstr &MI) { 1753 Builder.setInstrAndDebugLoc(MI); 1754 Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg(); 1755 // Truncating a vector is going to truncate every single lane, 1756 // whereas we want the full lowbits. 1757 // Do the operation on a scalar instead. 1758 LLT SrcTy = MRI.getType(SrcReg); 1759 if (SrcTy.isVector()) 1760 SrcReg = 1761 Builder.buildCast(LLT::scalar(SrcTy.getSizeInBits()), SrcReg).getReg(0); 1762 1763 Register Dst0Reg = MI.getOperand(0).getReg(); 1764 LLT Dst0Ty = MRI.getType(Dst0Reg); 1765 if (Dst0Ty.isVector()) { 1766 auto MIB = Builder.buildTrunc(LLT::scalar(Dst0Ty.getSizeInBits()), SrcReg); 1767 Builder.buildCast(Dst0Reg, MIB); 1768 } else 1769 Builder.buildTrunc(Dst0Reg, SrcReg); 1770 MI.eraseFromParent(); 1771 } 1772 1773 bool CombinerHelper::matchCombineUnmergeZExtToZExt(MachineInstr &MI) { 1774 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 1775 "Expected an unmerge"); 1776 Register Dst0Reg = MI.getOperand(0).getReg(); 1777 LLT Dst0Ty = MRI.getType(Dst0Reg); 1778 // G_ZEXT on vector applies to each lane, so it will 1779 // affect all destinations. Therefore we won't be able 1780 // to simplify the unmerge to just the first definition. 1781 if (Dst0Ty.isVector()) 1782 return false; 1783 Register SrcReg = MI.getOperand(MI.getNumDefs()).getReg(); 1784 LLT SrcTy = MRI.getType(SrcReg); 1785 if (SrcTy.isVector()) 1786 return false; 1787 1788 Register ZExtSrcReg; 1789 if (!mi_match(SrcReg, MRI, m_GZExt(m_Reg(ZExtSrcReg)))) 1790 return false; 1791 1792 // Finally we can replace the first definition with 1793 // a zext of the source if the definition is big enough to hold 1794 // all of ZExtSrc bits. 1795 LLT ZExtSrcTy = MRI.getType(ZExtSrcReg); 1796 return ZExtSrcTy.getSizeInBits() <= Dst0Ty.getSizeInBits(); 1797 } 1798 1799 void CombinerHelper::applyCombineUnmergeZExtToZExt(MachineInstr &MI) { 1800 assert(MI.getOpcode() == TargetOpcode::G_UNMERGE_VALUES && 1801 "Expected an unmerge"); 1802 1803 Register Dst0Reg = MI.getOperand(0).getReg(); 1804 1805 MachineInstr *ZExtInstr = 1806 MRI.getVRegDef(MI.getOperand(MI.getNumDefs()).getReg()); 1807 assert(ZExtInstr && ZExtInstr->getOpcode() == TargetOpcode::G_ZEXT && 1808 "Expecting a G_ZEXT"); 1809 1810 Register ZExtSrcReg = ZExtInstr->getOperand(1).getReg(); 1811 LLT Dst0Ty = MRI.getType(Dst0Reg); 1812 LLT ZExtSrcTy = MRI.getType(ZExtSrcReg); 1813 1814 Builder.setInstrAndDebugLoc(MI); 1815 1816 if (Dst0Ty.getSizeInBits() > ZExtSrcTy.getSizeInBits()) { 1817 Builder.buildZExt(Dst0Reg, ZExtSrcReg); 1818 } else { 1819 assert(Dst0Ty.getSizeInBits() == ZExtSrcTy.getSizeInBits() && 1820 "ZExt src doesn't fit in destination"); 1821 replaceRegWith(MRI, Dst0Reg, ZExtSrcReg); 1822 } 1823 1824 Register ZeroReg; 1825 for (unsigned Idx = 1, EndIdx = MI.getNumDefs(); Idx != EndIdx; ++Idx) { 1826 if (!ZeroReg) 1827 ZeroReg = Builder.buildConstant(Dst0Ty, 0).getReg(0); 1828 replaceRegWith(MRI, MI.getOperand(Idx).getReg(), ZeroReg); 1829 } 1830 MI.eraseFromParent(); 1831 } 1832 1833 bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI, 1834 unsigned TargetShiftSize, 1835 unsigned &ShiftVal) { 1836 assert((MI.getOpcode() == TargetOpcode::G_SHL || 1837 MI.getOpcode() == TargetOpcode::G_LSHR || 1838 MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift"); 1839 1840 LLT Ty = MRI.getType(MI.getOperand(0).getReg()); 1841 if (Ty.isVector()) // TODO: 1842 return false; 1843 1844 // Don't narrow further than the requested size. 1845 unsigned Size = Ty.getSizeInBits(); 1846 if (Size <= TargetShiftSize) 1847 return false; 1848 1849 auto MaybeImmVal = 1850 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 1851 if (!MaybeImmVal) 1852 return false; 1853 1854 ShiftVal = MaybeImmVal->Value.getSExtValue(); 1855 return ShiftVal >= Size / 2 && ShiftVal < Size; 1856 } 1857 1858 void CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI, 1859 const unsigned &ShiftVal) { 1860 Register DstReg = MI.getOperand(0).getReg(); 1861 Register SrcReg = MI.getOperand(1).getReg(); 1862 LLT Ty = MRI.getType(SrcReg); 1863 unsigned Size = Ty.getSizeInBits(); 1864 unsigned HalfSize = Size / 2; 1865 assert(ShiftVal >= HalfSize); 1866 1867 LLT HalfTy = LLT::scalar(HalfSize); 1868 1869 Builder.setInstr(MI); 1870 auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg); 1871 unsigned NarrowShiftAmt = ShiftVal - HalfSize; 1872 1873 if (MI.getOpcode() == TargetOpcode::G_LSHR) { 1874 Register Narrowed = Unmerge.getReg(1); 1875 1876 // dst = G_LSHR s64:x, C for C >= 32 1877 // => 1878 // lo, hi = G_UNMERGE_VALUES x 1879 // dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0 1880 1881 if (NarrowShiftAmt != 0) { 1882 Narrowed = Builder.buildLShr(HalfTy, Narrowed, 1883 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0); 1884 } 1885 1886 auto Zero = Builder.buildConstant(HalfTy, 0); 1887 Builder.buildMerge(DstReg, { Narrowed, Zero }); 1888 } else if (MI.getOpcode() == TargetOpcode::G_SHL) { 1889 Register Narrowed = Unmerge.getReg(0); 1890 // dst = G_SHL s64:x, C for C >= 32 1891 // => 1892 // lo, hi = G_UNMERGE_VALUES x 1893 // dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32) 1894 if (NarrowShiftAmt != 0) { 1895 Narrowed = Builder.buildShl(HalfTy, Narrowed, 1896 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0); 1897 } 1898 1899 auto Zero = Builder.buildConstant(HalfTy, 0); 1900 Builder.buildMerge(DstReg, { Zero, Narrowed }); 1901 } else { 1902 assert(MI.getOpcode() == TargetOpcode::G_ASHR); 1903 auto Hi = Builder.buildAShr( 1904 HalfTy, Unmerge.getReg(1), 1905 Builder.buildConstant(HalfTy, HalfSize - 1)); 1906 1907 if (ShiftVal == HalfSize) { 1908 // (G_ASHR i64:x, 32) -> 1909 // G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31) 1910 Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi }); 1911 } else if (ShiftVal == Size - 1) { 1912 // Don't need a second shift. 1913 // (G_ASHR i64:x, 63) -> 1914 // %narrowed = (G_ASHR hi_32(x), 31) 1915 // G_MERGE_VALUES %narrowed, %narrowed 1916 Builder.buildMerge(DstReg, { Hi, Hi }); 1917 } else { 1918 auto Lo = Builder.buildAShr( 1919 HalfTy, Unmerge.getReg(1), 1920 Builder.buildConstant(HalfTy, ShiftVal - HalfSize)); 1921 1922 // (G_ASHR i64:x, C) ->, for C >= 32 1923 // G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31) 1924 Builder.buildMerge(DstReg, { Lo, Hi }); 1925 } 1926 } 1927 1928 MI.eraseFromParent(); 1929 } 1930 1931 bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI, 1932 unsigned TargetShiftAmount) { 1933 unsigned ShiftAmt; 1934 if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) { 1935 applyCombineShiftToUnmerge(MI, ShiftAmt); 1936 return true; 1937 } 1938 1939 return false; 1940 } 1941 1942 bool CombinerHelper::matchCombineI2PToP2I(MachineInstr &MI, Register &Reg) { 1943 assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR"); 1944 Register DstReg = MI.getOperand(0).getReg(); 1945 LLT DstTy = MRI.getType(DstReg); 1946 Register SrcReg = MI.getOperand(1).getReg(); 1947 return mi_match(SrcReg, MRI, 1948 m_GPtrToInt(m_all_of(m_SpecificType(DstTy), m_Reg(Reg)))); 1949 } 1950 1951 void CombinerHelper::applyCombineI2PToP2I(MachineInstr &MI, Register &Reg) { 1952 assert(MI.getOpcode() == TargetOpcode::G_INTTOPTR && "Expected a G_INTTOPTR"); 1953 Register DstReg = MI.getOperand(0).getReg(); 1954 Builder.setInstr(MI); 1955 Builder.buildCopy(DstReg, Reg); 1956 MI.eraseFromParent(); 1957 } 1958 1959 bool CombinerHelper::matchCombineP2IToI2P(MachineInstr &MI, Register &Reg) { 1960 assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT"); 1961 Register SrcReg = MI.getOperand(1).getReg(); 1962 return mi_match(SrcReg, MRI, m_GIntToPtr(m_Reg(Reg))); 1963 } 1964 1965 void CombinerHelper::applyCombineP2IToI2P(MachineInstr &MI, Register &Reg) { 1966 assert(MI.getOpcode() == TargetOpcode::G_PTRTOINT && "Expected a G_PTRTOINT"); 1967 Register DstReg = MI.getOperand(0).getReg(); 1968 Builder.setInstr(MI); 1969 Builder.buildZExtOrTrunc(DstReg, Reg); 1970 MI.eraseFromParent(); 1971 } 1972 1973 bool CombinerHelper::matchCombineAddP2IToPtrAdd( 1974 MachineInstr &MI, std::pair<Register, bool> &PtrReg) { 1975 assert(MI.getOpcode() == TargetOpcode::G_ADD); 1976 Register LHS = MI.getOperand(1).getReg(); 1977 Register RHS = MI.getOperand(2).getReg(); 1978 LLT IntTy = MRI.getType(LHS); 1979 1980 // G_PTR_ADD always has the pointer in the LHS, so we may need to commute the 1981 // instruction. 1982 PtrReg.second = false; 1983 for (Register SrcReg : {LHS, RHS}) { 1984 if (mi_match(SrcReg, MRI, m_GPtrToInt(m_Reg(PtrReg.first)))) { 1985 // Don't handle cases where the integer is implicitly converted to the 1986 // pointer width. 1987 LLT PtrTy = MRI.getType(PtrReg.first); 1988 if (PtrTy.getScalarSizeInBits() == IntTy.getScalarSizeInBits()) 1989 return true; 1990 } 1991 1992 PtrReg.second = true; 1993 } 1994 1995 return false; 1996 } 1997 1998 void CombinerHelper::applyCombineAddP2IToPtrAdd( 1999 MachineInstr &MI, std::pair<Register, bool> &PtrReg) { 2000 Register Dst = MI.getOperand(0).getReg(); 2001 Register LHS = MI.getOperand(1).getReg(); 2002 Register RHS = MI.getOperand(2).getReg(); 2003 2004 const bool DoCommute = PtrReg.second; 2005 if (DoCommute) 2006 std::swap(LHS, RHS); 2007 LHS = PtrReg.first; 2008 2009 LLT PtrTy = MRI.getType(LHS); 2010 2011 Builder.setInstrAndDebugLoc(MI); 2012 auto PtrAdd = Builder.buildPtrAdd(PtrTy, LHS, RHS); 2013 Builder.buildPtrToInt(Dst, PtrAdd); 2014 MI.eraseFromParent(); 2015 } 2016 2017 bool CombinerHelper::matchCombineConstPtrAddToI2P(MachineInstr &MI, 2018 int64_t &NewCst) { 2019 auto &PtrAdd = cast<GPtrAdd>(MI); 2020 Register LHS = PtrAdd.getBaseReg(); 2021 Register RHS = PtrAdd.getOffsetReg(); 2022 MachineRegisterInfo &MRI = Builder.getMF().getRegInfo(); 2023 2024 if (auto RHSCst = getIConstantVRegSExtVal(RHS, MRI)) { 2025 int64_t Cst; 2026 if (mi_match(LHS, MRI, m_GIntToPtr(m_ICst(Cst)))) { 2027 NewCst = Cst + *RHSCst; 2028 return true; 2029 } 2030 } 2031 2032 return false; 2033 } 2034 2035 void CombinerHelper::applyCombineConstPtrAddToI2P(MachineInstr &MI, 2036 int64_t &NewCst) { 2037 auto &PtrAdd = cast<GPtrAdd>(MI); 2038 Register Dst = PtrAdd.getReg(0); 2039 2040 Builder.setInstrAndDebugLoc(MI); 2041 Builder.buildConstant(Dst, NewCst); 2042 PtrAdd.eraseFromParent(); 2043 } 2044 2045 bool CombinerHelper::matchCombineAnyExtTrunc(MachineInstr &MI, Register &Reg) { 2046 assert(MI.getOpcode() == TargetOpcode::G_ANYEXT && "Expected a G_ANYEXT"); 2047 Register DstReg = MI.getOperand(0).getReg(); 2048 Register SrcReg = MI.getOperand(1).getReg(); 2049 LLT DstTy = MRI.getType(DstReg); 2050 return mi_match(SrcReg, MRI, 2051 m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy)))); 2052 } 2053 2054 bool CombinerHelper::matchCombineZextTrunc(MachineInstr &MI, Register &Reg) { 2055 assert(MI.getOpcode() == TargetOpcode::G_ZEXT && "Expected a G_ZEXT"); 2056 Register DstReg = MI.getOperand(0).getReg(); 2057 Register SrcReg = MI.getOperand(1).getReg(); 2058 LLT DstTy = MRI.getType(DstReg); 2059 if (mi_match(SrcReg, MRI, 2060 m_GTrunc(m_all_of(m_Reg(Reg), m_SpecificType(DstTy))))) { 2061 unsigned DstSize = DstTy.getScalarSizeInBits(); 2062 unsigned SrcSize = MRI.getType(SrcReg).getScalarSizeInBits(); 2063 return KB->getKnownBits(Reg).countMinLeadingZeros() >= DstSize - SrcSize; 2064 } 2065 return false; 2066 } 2067 2068 bool CombinerHelper::matchCombineExtOfExt( 2069 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 2070 assert((MI.getOpcode() == TargetOpcode::G_ANYEXT || 2071 MI.getOpcode() == TargetOpcode::G_SEXT || 2072 MI.getOpcode() == TargetOpcode::G_ZEXT) && 2073 "Expected a G_[ASZ]EXT"); 2074 Register SrcReg = MI.getOperand(1).getReg(); 2075 MachineInstr *SrcMI = MRI.getVRegDef(SrcReg); 2076 // Match exts with the same opcode, anyext([sz]ext) and sext(zext). 2077 unsigned Opc = MI.getOpcode(); 2078 unsigned SrcOpc = SrcMI->getOpcode(); 2079 if (Opc == SrcOpc || 2080 (Opc == TargetOpcode::G_ANYEXT && 2081 (SrcOpc == TargetOpcode::G_SEXT || SrcOpc == TargetOpcode::G_ZEXT)) || 2082 (Opc == TargetOpcode::G_SEXT && SrcOpc == TargetOpcode::G_ZEXT)) { 2083 MatchInfo = std::make_tuple(SrcMI->getOperand(1).getReg(), SrcOpc); 2084 return true; 2085 } 2086 return false; 2087 } 2088 2089 void CombinerHelper::applyCombineExtOfExt( 2090 MachineInstr &MI, std::tuple<Register, unsigned> &MatchInfo) { 2091 assert((MI.getOpcode() == TargetOpcode::G_ANYEXT || 2092 MI.getOpcode() == TargetOpcode::G_SEXT || 2093 MI.getOpcode() == TargetOpcode::G_ZEXT) && 2094 "Expected a G_[ASZ]EXT"); 2095 2096 Register Reg = std::get<0>(MatchInfo); 2097 unsigned SrcExtOp = std::get<1>(MatchInfo); 2098 2099 // Combine exts with the same opcode. 2100 if (MI.getOpcode() == SrcExtOp) { 2101 Observer.changingInstr(MI); 2102 MI.getOperand(1).setReg(Reg); 2103 Observer.changedInstr(MI); 2104 return; 2105 } 2106 2107 // Combine: 2108 // - anyext([sz]ext x) to [sz]ext x 2109 // - sext(zext x) to zext x 2110 if (MI.getOpcode() == TargetOpcode::G_ANYEXT || 2111 (MI.getOpcode() == TargetOpcode::G_SEXT && 2112 SrcExtOp == TargetOpcode::G_ZEXT)) { 2113 Register DstReg = MI.getOperand(0).getReg(); 2114 Builder.setInstrAndDebugLoc(MI); 2115 Builder.buildInstr(SrcExtOp, {DstReg}, {Reg}); 2116 MI.eraseFromParent(); 2117 } 2118 } 2119 2120 void CombinerHelper::applyCombineMulByNegativeOne(MachineInstr &MI) { 2121 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 2122 Register DstReg = MI.getOperand(0).getReg(); 2123 Register SrcReg = MI.getOperand(1).getReg(); 2124 LLT DstTy = MRI.getType(DstReg); 2125 2126 Builder.setInstrAndDebugLoc(MI); 2127 Builder.buildSub(DstReg, Builder.buildConstant(DstTy, 0), SrcReg, 2128 MI.getFlags()); 2129 MI.eraseFromParent(); 2130 } 2131 2132 bool CombinerHelper::matchCombineFNegOfFNeg(MachineInstr &MI, Register &Reg) { 2133 assert(MI.getOpcode() == TargetOpcode::G_FNEG && "Expected a G_FNEG"); 2134 Register SrcReg = MI.getOperand(1).getReg(); 2135 return mi_match(SrcReg, MRI, m_GFNeg(m_Reg(Reg))); 2136 } 2137 2138 bool CombinerHelper::matchCombineFAbsOfFAbs(MachineInstr &MI, Register &Src) { 2139 assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS"); 2140 Src = MI.getOperand(1).getReg(); 2141 Register AbsSrc; 2142 return mi_match(Src, MRI, m_GFabs(m_Reg(AbsSrc))); 2143 } 2144 2145 bool CombinerHelper::matchCombineFAbsOfFNeg(MachineInstr &MI, 2146 BuildFnTy &MatchInfo) { 2147 assert(MI.getOpcode() == TargetOpcode::G_FABS && "Expected a G_FABS"); 2148 Register Src = MI.getOperand(1).getReg(); 2149 Register NegSrc; 2150 2151 if (!mi_match(Src, MRI, m_GFNeg(m_Reg(NegSrc)))) 2152 return false; 2153 2154 MatchInfo = [=, &MI](MachineIRBuilder &B) { 2155 Observer.changingInstr(MI); 2156 MI.getOperand(1).setReg(NegSrc); 2157 Observer.changedInstr(MI); 2158 }; 2159 return true; 2160 } 2161 2162 bool CombinerHelper::matchCombineTruncOfExt( 2163 MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) { 2164 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2165 Register SrcReg = MI.getOperand(1).getReg(); 2166 MachineInstr *SrcMI = MRI.getVRegDef(SrcReg); 2167 unsigned SrcOpc = SrcMI->getOpcode(); 2168 if (SrcOpc == TargetOpcode::G_ANYEXT || SrcOpc == TargetOpcode::G_SEXT || 2169 SrcOpc == TargetOpcode::G_ZEXT) { 2170 MatchInfo = std::make_pair(SrcMI->getOperand(1).getReg(), SrcOpc); 2171 return true; 2172 } 2173 return false; 2174 } 2175 2176 void CombinerHelper::applyCombineTruncOfExt( 2177 MachineInstr &MI, std::pair<Register, unsigned> &MatchInfo) { 2178 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2179 Register SrcReg = MatchInfo.first; 2180 unsigned SrcExtOp = MatchInfo.second; 2181 Register DstReg = MI.getOperand(0).getReg(); 2182 LLT SrcTy = MRI.getType(SrcReg); 2183 LLT DstTy = MRI.getType(DstReg); 2184 if (SrcTy == DstTy) { 2185 MI.eraseFromParent(); 2186 replaceRegWith(MRI, DstReg, SrcReg); 2187 return; 2188 } 2189 Builder.setInstrAndDebugLoc(MI); 2190 if (SrcTy.getSizeInBits() < DstTy.getSizeInBits()) 2191 Builder.buildInstr(SrcExtOp, {DstReg}, {SrcReg}); 2192 else 2193 Builder.buildTrunc(DstReg, SrcReg); 2194 MI.eraseFromParent(); 2195 } 2196 2197 bool CombinerHelper::matchCombineTruncOfShl( 2198 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 2199 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2200 Register DstReg = MI.getOperand(0).getReg(); 2201 Register SrcReg = MI.getOperand(1).getReg(); 2202 LLT DstTy = MRI.getType(DstReg); 2203 Register ShiftSrc; 2204 Register ShiftAmt; 2205 2206 if (MRI.hasOneNonDBGUse(SrcReg) && 2207 mi_match(SrcReg, MRI, m_GShl(m_Reg(ShiftSrc), m_Reg(ShiftAmt))) && 2208 isLegalOrBeforeLegalizer( 2209 {TargetOpcode::G_SHL, 2210 {DstTy, getTargetLowering().getPreferredShiftAmountTy(DstTy)}})) { 2211 KnownBits Known = KB->getKnownBits(ShiftAmt); 2212 unsigned Size = DstTy.getSizeInBits(); 2213 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 2214 MatchInfo = std::make_pair(ShiftSrc, ShiftAmt); 2215 return true; 2216 } 2217 } 2218 return false; 2219 } 2220 2221 void CombinerHelper::applyCombineTruncOfShl( 2222 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 2223 assert(MI.getOpcode() == TargetOpcode::G_TRUNC && "Expected a G_TRUNC"); 2224 Register DstReg = MI.getOperand(0).getReg(); 2225 Register SrcReg = MI.getOperand(1).getReg(); 2226 LLT DstTy = MRI.getType(DstReg); 2227 MachineInstr *SrcMI = MRI.getVRegDef(SrcReg); 2228 2229 Register ShiftSrc = MatchInfo.first; 2230 Register ShiftAmt = MatchInfo.second; 2231 Builder.setInstrAndDebugLoc(MI); 2232 auto TruncShiftSrc = Builder.buildTrunc(DstTy, ShiftSrc); 2233 Builder.buildShl(DstReg, TruncShiftSrc, ShiftAmt, SrcMI->getFlags()); 2234 MI.eraseFromParent(); 2235 } 2236 2237 bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) { 2238 return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) { 2239 return MO.isReg() && 2240 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 2241 }); 2242 } 2243 2244 bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) { 2245 return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) { 2246 return !MO.isReg() || 2247 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 2248 }); 2249 } 2250 2251 bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) { 2252 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 2253 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask(); 2254 return all_of(Mask, [](int Elt) { return Elt < 0; }); 2255 } 2256 2257 bool CombinerHelper::matchUndefStore(MachineInstr &MI) { 2258 assert(MI.getOpcode() == TargetOpcode::G_STORE); 2259 return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(), 2260 MRI); 2261 } 2262 2263 bool CombinerHelper::matchUndefSelectCmp(MachineInstr &MI) { 2264 assert(MI.getOpcode() == TargetOpcode::G_SELECT); 2265 return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(1).getReg(), 2266 MRI); 2267 } 2268 2269 bool CombinerHelper::matchConstantSelectCmp(MachineInstr &MI, unsigned &OpIdx) { 2270 GSelect &SelMI = cast<GSelect>(MI); 2271 auto Cst = 2272 isConstantOrConstantSplatVector(*MRI.getVRegDef(SelMI.getCondReg()), MRI); 2273 if (!Cst) 2274 return false; 2275 OpIdx = Cst->isZero() ? 3 : 2; 2276 return true; 2277 } 2278 2279 bool CombinerHelper::eraseInst(MachineInstr &MI) { 2280 MI.eraseFromParent(); 2281 return true; 2282 } 2283 2284 bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1, 2285 const MachineOperand &MOP2) { 2286 if (!MOP1.isReg() || !MOP2.isReg()) 2287 return false; 2288 auto InstAndDef1 = getDefSrcRegIgnoringCopies(MOP1.getReg(), MRI); 2289 if (!InstAndDef1) 2290 return false; 2291 auto InstAndDef2 = getDefSrcRegIgnoringCopies(MOP2.getReg(), MRI); 2292 if (!InstAndDef2) 2293 return false; 2294 MachineInstr *I1 = InstAndDef1->MI; 2295 MachineInstr *I2 = InstAndDef2->MI; 2296 2297 // Handle a case like this: 2298 // 2299 // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>) 2300 // 2301 // Even though %0 and %1 are produced by the same instruction they are not 2302 // the same values. 2303 if (I1 == I2) 2304 return MOP1.getReg() == MOP2.getReg(); 2305 2306 // If we have an instruction which loads or stores, we can't guarantee that 2307 // it is identical. 2308 // 2309 // For example, we may have 2310 // 2311 // %x1 = G_LOAD %addr (load N from @somewhere) 2312 // ... 2313 // call @foo 2314 // ... 2315 // %x2 = G_LOAD %addr (load N from @somewhere) 2316 // ... 2317 // %or = G_OR %x1, %x2 2318 // 2319 // It's possible that @foo will modify whatever lives at the address we're 2320 // loading from. To be safe, let's just assume that all loads and stores 2321 // are different (unless we have something which is guaranteed to not 2322 // change.) 2323 if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr)) 2324 return false; 2325 2326 // Check for physical registers on the instructions first to avoid cases 2327 // like this: 2328 // 2329 // %a = COPY $physreg 2330 // ... 2331 // SOMETHING implicit-def $physreg 2332 // ... 2333 // %b = COPY $physreg 2334 // 2335 // These copies are not equivalent. 2336 if (any_of(I1->uses(), [](const MachineOperand &MO) { 2337 return MO.isReg() && MO.getReg().isPhysical(); 2338 })) { 2339 // Check if we have a case like this: 2340 // 2341 // %a = COPY $physreg 2342 // %b = COPY %a 2343 // 2344 // In this case, I1 and I2 will both be equal to %a = COPY $physreg. 2345 // From that, we know that they must have the same value, since they must 2346 // have come from the same COPY. 2347 return I1->isIdenticalTo(*I2); 2348 } 2349 2350 // We don't have any physical registers, so we don't necessarily need the 2351 // same vreg defs. 2352 // 2353 // On the off-chance that there's some target instruction feeding into the 2354 // instruction, let's use produceSameValue instead of isIdenticalTo. 2355 if (Builder.getTII().produceSameValue(*I1, *I2, &MRI)) { 2356 // Handle instructions with multiple defs that produce same values. Values 2357 // are same for operands with same index. 2358 // %0:_(s8), %1:_(s8), %2:_(s8), %3:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>) 2359 // %5:_(s8), %6:_(s8), %7:_(s8), %8:_(s8) = G_UNMERGE_VALUES %4:_(<4 x s8>) 2360 // I1 and I2 are different instructions but produce same values, 2361 // %1 and %6 are same, %1 and %7 are not the same value. 2362 return I1->findRegisterDefOperandIdx(InstAndDef1->Reg) == 2363 I2->findRegisterDefOperandIdx(InstAndDef2->Reg); 2364 } 2365 return false; 2366 } 2367 2368 bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) { 2369 if (!MOP.isReg()) 2370 return false; 2371 auto *MI = MRI.getVRegDef(MOP.getReg()); 2372 auto MaybeCst = isConstantOrConstantSplatVector(*MI, MRI); 2373 return MaybeCst.hasValue() && MaybeCst->getSExtValue() == C; 2374 } 2375 2376 bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI, 2377 unsigned OpIdx) { 2378 assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?"); 2379 Register OldReg = MI.getOperand(0).getReg(); 2380 Register Replacement = MI.getOperand(OpIdx).getReg(); 2381 assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?"); 2382 MI.eraseFromParent(); 2383 replaceRegWith(MRI, OldReg, Replacement); 2384 return true; 2385 } 2386 2387 bool CombinerHelper::replaceSingleDefInstWithReg(MachineInstr &MI, 2388 Register Replacement) { 2389 assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?"); 2390 Register OldReg = MI.getOperand(0).getReg(); 2391 assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?"); 2392 MI.eraseFromParent(); 2393 replaceRegWith(MRI, OldReg, Replacement); 2394 return true; 2395 } 2396 2397 bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) { 2398 assert(MI.getOpcode() == TargetOpcode::G_SELECT); 2399 // Match (cond ? x : x) 2400 return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) && 2401 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(), 2402 MRI); 2403 } 2404 2405 bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) { 2406 return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) && 2407 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(), 2408 MRI); 2409 } 2410 2411 bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) { 2412 return matchConstantOp(MI.getOperand(OpIdx), 0) && 2413 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(), 2414 MRI); 2415 } 2416 2417 bool CombinerHelper::matchOperandIsUndef(MachineInstr &MI, unsigned OpIdx) { 2418 MachineOperand &MO = MI.getOperand(OpIdx); 2419 return MO.isReg() && 2420 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 2421 } 2422 2423 bool CombinerHelper::matchOperandIsKnownToBeAPowerOfTwo(MachineInstr &MI, 2424 unsigned OpIdx) { 2425 MachineOperand &MO = MI.getOperand(OpIdx); 2426 return isKnownToBeAPowerOfTwo(MO.getReg(), MRI, KB); 2427 } 2428 2429 bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) { 2430 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 2431 Builder.setInstr(MI); 2432 Builder.buildFConstant(MI.getOperand(0), C); 2433 MI.eraseFromParent(); 2434 return true; 2435 } 2436 2437 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) { 2438 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 2439 Builder.setInstr(MI); 2440 Builder.buildConstant(MI.getOperand(0), C); 2441 MI.eraseFromParent(); 2442 return true; 2443 } 2444 2445 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, APInt C) { 2446 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 2447 Builder.setInstr(MI); 2448 Builder.buildConstant(MI.getOperand(0), C); 2449 MI.eraseFromParent(); 2450 return true; 2451 } 2452 2453 bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) { 2454 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 2455 Builder.setInstr(MI); 2456 Builder.buildUndef(MI.getOperand(0)); 2457 MI.eraseFromParent(); 2458 return true; 2459 } 2460 2461 bool CombinerHelper::matchSimplifyAddToSub( 2462 MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) { 2463 Register LHS = MI.getOperand(1).getReg(); 2464 Register RHS = MI.getOperand(2).getReg(); 2465 Register &NewLHS = std::get<0>(MatchInfo); 2466 Register &NewRHS = std::get<1>(MatchInfo); 2467 2468 // Helper lambda to check for opportunities for 2469 // ((0-A) + B) -> B - A 2470 // (A + (0-B)) -> A - B 2471 auto CheckFold = [&](Register &MaybeSub, Register &MaybeNewLHS) { 2472 if (!mi_match(MaybeSub, MRI, m_Neg(m_Reg(NewRHS)))) 2473 return false; 2474 NewLHS = MaybeNewLHS; 2475 return true; 2476 }; 2477 2478 return CheckFold(LHS, RHS) || CheckFold(RHS, LHS); 2479 } 2480 2481 bool CombinerHelper::matchCombineInsertVecElts( 2482 MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) { 2483 assert(MI.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT && 2484 "Invalid opcode"); 2485 Register DstReg = MI.getOperand(0).getReg(); 2486 LLT DstTy = MRI.getType(DstReg); 2487 assert(DstTy.isVector() && "Invalid G_INSERT_VECTOR_ELT?"); 2488 unsigned NumElts = DstTy.getNumElements(); 2489 // If this MI is part of a sequence of insert_vec_elts, then 2490 // don't do the combine in the middle of the sequence. 2491 if (MRI.hasOneUse(DstReg) && MRI.use_instr_begin(DstReg)->getOpcode() == 2492 TargetOpcode::G_INSERT_VECTOR_ELT) 2493 return false; 2494 MachineInstr *CurrInst = &MI; 2495 MachineInstr *TmpInst; 2496 int64_t IntImm; 2497 Register TmpReg; 2498 MatchInfo.resize(NumElts); 2499 while (mi_match( 2500 CurrInst->getOperand(0).getReg(), MRI, 2501 m_GInsertVecElt(m_MInstr(TmpInst), m_Reg(TmpReg), m_ICst(IntImm)))) { 2502 if (IntImm >= NumElts) 2503 return false; 2504 if (!MatchInfo[IntImm]) 2505 MatchInfo[IntImm] = TmpReg; 2506 CurrInst = TmpInst; 2507 } 2508 // Variable index. 2509 if (CurrInst->getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT) 2510 return false; 2511 if (TmpInst->getOpcode() == TargetOpcode::G_BUILD_VECTOR) { 2512 for (unsigned I = 1; I < TmpInst->getNumOperands(); ++I) { 2513 if (!MatchInfo[I - 1].isValid()) 2514 MatchInfo[I - 1] = TmpInst->getOperand(I).getReg(); 2515 } 2516 return true; 2517 } 2518 // If we didn't end in a G_IMPLICIT_DEF, bail out. 2519 return TmpInst->getOpcode() == TargetOpcode::G_IMPLICIT_DEF; 2520 } 2521 2522 void CombinerHelper::applyCombineInsertVecElts( 2523 MachineInstr &MI, SmallVectorImpl<Register> &MatchInfo) { 2524 Builder.setInstr(MI); 2525 Register UndefReg; 2526 auto GetUndef = [&]() { 2527 if (UndefReg) 2528 return UndefReg; 2529 LLT DstTy = MRI.getType(MI.getOperand(0).getReg()); 2530 UndefReg = Builder.buildUndef(DstTy.getScalarType()).getReg(0); 2531 return UndefReg; 2532 }; 2533 for (unsigned I = 0; I < MatchInfo.size(); ++I) { 2534 if (!MatchInfo[I]) 2535 MatchInfo[I] = GetUndef(); 2536 } 2537 Builder.buildBuildVector(MI.getOperand(0).getReg(), MatchInfo); 2538 MI.eraseFromParent(); 2539 } 2540 2541 void CombinerHelper::applySimplifyAddToSub( 2542 MachineInstr &MI, std::tuple<Register, Register> &MatchInfo) { 2543 Builder.setInstr(MI); 2544 Register SubLHS, SubRHS; 2545 std::tie(SubLHS, SubRHS) = MatchInfo; 2546 Builder.buildSub(MI.getOperand(0).getReg(), SubLHS, SubRHS); 2547 MI.eraseFromParent(); 2548 } 2549 2550 bool CombinerHelper::matchHoistLogicOpWithSameOpcodeHands( 2551 MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) { 2552 // Matches: logic (hand x, ...), (hand y, ...) -> hand (logic x, y), ... 2553 // 2554 // Creates the new hand + logic instruction (but does not insert them.) 2555 // 2556 // On success, MatchInfo is populated with the new instructions. These are 2557 // inserted in applyHoistLogicOpWithSameOpcodeHands. 2558 unsigned LogicOpcode = MI.getOpcode(); 2559 assert(LogicOpcode == TargetOpcode::G_AND || 2560 LogicOpcode == TargetOpcode::G_OR || 2561 LogicOpcode == TargetOpcode::G_XOR); 2562 MachineIRBuilder MIB(MI); 2563 Register Dst = MI.getOperand(0).getReg(); 2564 Register LHSReg = MI.getOperand(1).getReg(); 2565 Register RHSReg = MI.getOperand(2).getReg(); 2566 2567 // Don't recompute anything. 2568 if (!MRI.hasOneNonDBGUse(LHSReg) || !MRI.hasOneNonDBGUse(RHSReg)) 2569 return false; 2570 2571 // Make sure we have (hand x, ...), (hand y, ...) 2572 MachineInstr *LeftHandInst = getDefIgnoringCopies(LHSReg, MRI); 2573 MachineInstr *RightHandInst = getDefIgnoringCopies(RHSReg, MRI); 2574 if (!LeftHandInst || !RightHandInst) 2575 return false; 2576 unsigned HandOpcode = LeftHandInst->getOpcode(); 2577 if (HandOpcode != RightHandInst->getOpcode()) 2578 return false; 2579 if (!LeftHandInst->getOperand(1).isReg() || 2580 !RightHandInst->getOperand(1).isReg()) 2581 return false; 2582 2583 // Make sure the types match up, and if we're doing this post-legalization, 2584 // we end up with legal types. 2585 Register X = LeftHandInst->getOperand(1).getReg(); 2586 Register Y = RightHandInst->getOperand(1).getReg(); 2587 LLT XTy = MRI.getType(X); 2588 LLT YTy = MRI.getType(Y); 2589 if (XTy != YTy) 2590 return false; 2591 if (!isLegalOrBeforeLegalizer({LogicOpcode, {XTy, YTy}})) 2592 return false; 2593 2594 // Optional extra source register. 2595 Register ExtraHandOpSrcReg; 2596 switch (HandOpcode) { 2597 default: 2598 return false; 2599 case TargetOpcode::G_ANYEXT: 2600 case TargetOpcode::G_SEXT: 2601 case TargetOpcode::G_ZEXT: { 2602 // Match: logic (ext X), (ext Y) --> ext (logic X, Y) 2603 break; 2604 } 2605 case TargetOpcode::G_AND: 2606 case TargetOpcode::G_ASHR: 2607 case TargetOpcode::G_LSHR: 2608 case TargetOpcode::G_SHL: { 2609 // Match: logic (binop x, z), (binop y, z) -> binop (logic x, y), z 2610 MachineOperand &ZOp = LeftHandInst->getOperand(2); 2611 if (!matchEqualDefs(ZOp, RightHandInst->getOperand(2))) 2612 return false; 2613 ExtraHandOpSrcReg = ZOp.getReg(); 2614 break; 2615 } 2616 } 2617 2618 // Record the steps to build the new instructions. 2619 // 2620 // Steps to build (logic x, y) 2621 auto NewLogicDst = MRI.createGenericVirtualRegister(XTy); 2622 OperandBuildSteps LogicBuildSteps = { 2623 [=](MachineInstrBuilder &MIB) { MIB.addDef(NewLogicDst); }, 2624 [=](MachineInstrBuilder &MIB) { MIB.addReg(X); }, 2625 [=](MachineInstrBuilder &MIB) { MIB.addReg(Y); }}; 2626 InstructionBuildSteps LogicSteps(LogicOpcode, LogicBuildSteps); 2627 2628 // Steps to build hand (logic x, y), ...z 2629 OperandBuildSteps HandBuildSteps = { 2630 [=](MachineInstrBuilder &MIB) { MIB.addDef(Dst); }, 2631 [=](MachineInstrBuilder &MIB) { MIB.addReg(NewLogicDst); }}; 2632 if (ExtraHandOpSrcReg.isValid()) 2633 HandBuildSteps.push_back( 2634 [=](MachineInstrBuilder &MIB) { MIB.addReg(ExtraHandOpSrcReg); }); 2635 InstructionBuildSteps HandSteps(HandOpcode, HandBuildSteps); 2636 2637 MatchInfo = InstructionStepsMatchInfo({LogicSteps, HandSteps}); 2638 return true; 2639 } 2640 2641 void CombinerHelper::applyBuildInstructionSteps( 2642 MachineInstr &MI, InstructionStepsMatchInfo &MatchInfo) { 2643 assert(MatchInfo.InstrsToBuild.size() && 2644 "Expected at least one instr to build?"); 2645 Builder.setInstr(MI); 2646 for (auto &InstrToBuild : MatchInfo.InstrsToBuild) { 2647 assert(InstrToBuild.Opcode && "Expected a valid opcode?"); 2648 assert(InstrToBuild.OperandFns.size() && "Expected at least one operand?"); 2649 MachineInstrBuilder Instr = Builder.buildInstr(InstrToBuild.Opcode); 2650 for (auto &OperandFn : InstrToBuild.OperandFns) 2651 OperandFn(Instr); 2652 } 2653 MI.eraseFromParent(); 2654 } 2655 2656 bool CombinerHelper::matchAshrShlToSextInreg( 2657 MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) { 2658 assert(MI.getOpcode() == TargetOpcode::G_ASHR); 2659 int64_t ShlCst, AshrCst; 2660 Register Src; 2661 // FIXME: detect splat constant vectors. 2662 if (!mi_match(MI.getOperand(0).getReg(), MRI, 2663 m_GAShr(m_GShl(m_Reg(Src), m_ICst(ShlCst)), m_ICst(AshrCst)))) 2664 return false; 2665 if (ShlCst != AshrCst) 2666 return false; 2667 if (!isLegalOrBeforeLegalizer( 2668 {TargetOpcode::G_SEXT_INREG, {MRI.getType(Src)}})) 2669 return false; 2670 MatchInfo = std::make_tuple(Src, ShlCst); 2671 return true; 2672 } 2673 2674 void CombinerHelper::applyAshShlToSextInreg( 2675 MachineInstr &MI, std::tuple<Register, int64_t> &MatchInfo) { 2676 assert(MI.getOpcode() == TargetOpcode::G_ASHR); 2677 Register Src; 2678 int64_t ShiftAmt; 2679 std::tie(Src, ShiftAmt) = MatchInfo; 2680 unsigned Size = MRI.getType(Src).getScalarSizeInBits(); 2681 Builder.setInstrAndDebugLoc(MI); 2682 Builder.buildSExtInReg(MI.getOperand(0).getReg(), Src, Size - ShiftAmt); 2683 MI.eraseFromParent(); 2684 } 2685 2686 /// and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0 2687 bool CombinerHelper::matchOverlappingAnd( 2688 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 2689 assert(MI.getOpcode() == TargetOpcode::G_AND); 2690 2691 Register Dst = MI.getOperand(0).getReg(); 2692 LLT Ty = MRI.getType(Dst); 2693 2694 Register R; 2695 int64_t C1; 2696 int64_t C2; 2697 if (!mi_match( 2698 Dst, MRI, 2699 m_GAnd(m_GAnd(m_Reg(R), m_ICst(C1)), m_ICst(C2)))) 2700 return false; 2701 2702 MatchInfo = [=](MachineIRBuilder &B) { 2703 if (C1 & C2) { 2704 B.buildAnd(Dst, R, B.buildConstant(Ty, C1 & C2)); 2705 return; 2706 } 2707 auto Zero = B.buildConstant(Ty, 0); 2708 replaceRegWith(MRI, Dst, Zero->getOperand(0).getReg()); 2709 }; 2710 return true; 2711 } 2712 2713 bool CombinerHelper::matchRedundantAnd(MachineInstr &MI, 2714 Register &Replacement) { 2715 // Given 2716 // 2717 // %y:_(sN) = G_SOMETHING 2718 // %x:_(sN) = G_SOMETHING 2719 // %res:_(sN) = G_AND %x, %y 2720 // 2721 // Eliminate the G_AND when it is known that x & y == x or x & y == y. 2722 // 2723 // Patterns like this can appear as a result of legalization. E.g. 2724 // 2725 // %cmp:_(s32) = G_ICMP intpred(pred), %x(s32), %y 2726 // %one:_(s32) = G_CONSTANT i32 1 2727 // %and:_(s32) = G_AND %cmp, %one 2728 // 2729 // In this case, G_ICMP only produces a single bit, so x & 1 == x. 2730 assert(MI.getOpcode() == TargetOpcode::G_AND); 2731 if (!KB) 2732 return false; 2733 2734 Register AndDst = MI.getOperand(0).getReg(); 2735 LLT DstTy = MRI.getType(AndDst); 2736 2737 // FIXME: This should be removed once GISelKnownBits supports vectors. 2738 if (DstTy.isVector()) 2739 return false; 2740 2741 Register LHS = MI.getOperand(1).getReg(); 2742 Register RHS = MI.getOperand(2).getReg(); 2743 KnownBits LHSBits = KB->getKnownBits(LHS); 2744 KnownBits RHSBits = KB->getKnownBits(RHS); 2745 2746 // Check that x & Mask == x. 2747 // x & 1 == x, always 2748 // x & 0 == x, only if x is also 0 2749 // Meaning Mask has no effect if every bit is either one in Mask or zero in x. 2750 // 2751 // Check if we can replace AndDst with the LHS of the G_AND 2752 if (canReplaceReg(AndDst, LHS, MRI) && 2753 (LHSBits.Zero | RHSBits.One).isAllOnes()) { 2754 Replacement = LHS; 2755 return true; 2756 } 2757 2758 // Check if we can replace AndDst with the RHS of the G_AND 2759 if (canReplaceReg(AndDst, RHS, MRI) && 2760 (LHSBits.One | RHSBits.Zero).isAllOnes()) { 2761 Replacement = RHS; 2762 return true; 2763 } 2764 2765 return false; 2766 } 2767 2768 bool CombinerHelper::matchRedundantOr(MachineInstr &MI, Register &Replacement) { 2769 // Given 2770 // 2771 // %y:_(sN) = G_SOMETHING 2772 // %x:_(sN) = G_SOMETHING 2773 // %res:_(sN) = G_OR %x, %y 2774 // 2775 // Eliminate the G_OR when it is known that x | y == x or x | y == y. 2776 assert(MI.getOpcode() == TargetOpcode::G_OR); 2777 if (!KB) 2778 return false; 2779 2780 Register OrDst = MI.getOperand(0).getReg(); 2781 LLT DstTy = MRI.getType(OrDst); 2782 2783 // FIXME: This should be removed once GISelKnownBits supports vectors. 2784 if (DstTy.isVector()) 2785 return false; 2786 2787 Register LHS = MI.getOperand(1).getReg(); 2788 Register RHS = MI.getOperand(2).getReg(); 2789 KnownBits LHSBits = KB->getKnownBits(LHS); 2790 KnownBits RHSBits = KB->getKnownBits(RHS); 2791 2792 // Check that x | Mask == x. 2793 // x | 0 == x, always 2794 // x | 1 == x, only if x is also 1 2795 // Meaning Mask has no effect if every bit is either zero in Mask or one in x. 2796 // 2797 // Check if we can replace OrDst with the LHS of the G_OR 2798 if (canReplaceReg(OrDst, LHS, MRI) && 2799 (LHSBits.One | RHSBits.Zero).isAllOnes()) { 2800 Replacement = LHS; 2801 return true; 2802 } 2803 2804 // Check if we can replace OrDst with the RHS of the G_OR 2805 if (canReplaceReg(OrDst, RHS, MRI) && 2806 (LHSBits.Zero | RHSBits.One).isAllOnes()) { 2807 Replacement = RHS; 2808 return true; 2809 } 2810 2811 return false; 2812 } 2813 2814 bool CombinerHelper::matchRedundantSExtInReg(MachineInstr &MI) { 2815 // If the input is already sign extended, just drop the extension. 2816 Register Src = MI.getOperand(1).getReg(); 2817 unsigned ExtBits = MI.getOperand(2).getImm(); 2818 unsigned TypeSize = MRI.getType(Src).getScalarSizeInBits(); 2819 return KB->computeNumSignBits(Src) >= (TypeSize - ExtBits + 1); 2820 } 2821 2822 static bool isConstValidTrue(const TargetLowering &TLI, unsigned ScalarSizeBits, 2823 int64_t Cst, bool IsVector, bool IsFP) { 2824 // For i1, Cst will always be -1 regardless of boolean contents. 2825 return (ScalarSizeBits == 1 && Cst == -1) || 2826 isConstTrueVal(TLI, Cst, IsVector, IsFP); 2827 } 2828 2829 bool CombinerHelper::matchNotCmp(MachineInstr &MI, 2830 SmallVectorImpl<Register> &RegsToNegate) { 2831 assert(MI.getOpcode() == TargetOpcode::G_XOR); 2832 LLT Ty = MRI.getType(MI.getOperand(0).getReg()); 2833 const auto &TLI = *Builder.getMF().getSubtarget().getTargetLowering(); 2834 Register XorSrc; 2835 Register CstReg; 2836 // We match xor(src, true) here. 2837 if (!mi_match(MI.getOperand(0).getReg(), MRI, 2838 m_GXor(m_Reg(XorSrc), m_Reg(CstReg)))) 2839 return false; 2840 2841 if (!MRI.hasOneNonDBGUse(XorSrc)) 2842 return false; 2843 2844 // Check that XorSrc is the root of a tree of comparisons combined with ANDs 2845 // and ORs. The suffix of RegsToNegate starting from index I is used a work 2846 // list of tree nodes to visit. 2847 RegsToNegate.push_back(XorSrc); 2848 // Remember whether the comparisons are all integer or all floating point. 2849 bool IsInt = false; 2850 bool IsFP = false; 2851 for (unsigned I = 0; I < RegsToNegate.size(); ++I) { 2852 Register Reg = RegsToNegate[I]; 2853 if (!MRI.hasOneNonDBGUse(Reg)) 2854 return false; 2855 MachineInstr *Def = MRI.getVRegDef(Reg); 2856 switch (Def->getOpcode()) { 2857 default: 2858 // Don't match if the tree contains anything other than ANDs, ORs and 2859 // comparisons. 2860 return false; 2861 case TargetOpcode::G_ICMP: 2862 if (IsFP) 2863 return false; 2864 IsInt = true; 2865 // When we apply the combine we will invert the predicate. 2866 break; 2867 case TargetOpcode::G_FCMP: 2868 if (IsInt) 2869 return false; 2870 IsFP = true; 2871 // When we apply the combine we will invert the predicate. 2872 break; 2873 case TargetOpcode::G_AND: 2874 case TargetOpcode::G_OR: 2875 // Implement De Morgan's laws: 2876 // ~(x & y) -> ~x | ~y 2877 // ~(x | y) -> ~x & ~y 2878 // When we apply the combine we will change the opcode and recursively 2879 // negate the operands. 2880 RegsToNegate.push_back(Def->getOperand(1).getReg()); 2881 RegsToNegate.push_back(Def->getOperand(2).getReg()); 2882 break; 2883 } 2884 } 2885 2886 // Now we know whether the comparisons are integer or floating point, check 2887 // the constant in the xor. 2888 int64_t Cst; 2889 if (Ty.isVector()) { 2890 MachineInstr *CstDef = MRI.getVRegDef(CstReg); 2891 auto MaybeCst = getBuildVectorConstantSplat(*CstDef, MRI); 2892 if (!MaybeCst) 2893 return false; 2894 if (!isConstValidTrue(TLI, Ty.getScalarSizeInBits(), *MaybeCst, true, IsFP)) 2895 return false; 2896 } else { 2897 if (!mi_match(CstReg, MRI, m_ICst(Cst))) 2898 return false; 2899 if (!isConstValidTrue(TLI, Ty.getSizeInBits(), Cst, false, IsFP)) 2900 return false; 2901 } 2902 2903 return true; 2904 } 2905 2906 void CombinerHelper::applyNotCmp(MachineInstr &MI, 2907 SmallVectorImpl<Register> &RegsToNegate) { 2908 for (Register Reg : RegsToNegate) { 2909 MachineInstr *Def = MRI.getVRegDef(Reg); 2910 Observer.changingInstr(*Def); 2911 // For each comparison, invert the opcode. For each AND and OR, change the 2912 // opcode. 2913 switch (Def->getOpcode()) { 2914 default: 2915 llvm_unreachable("Unexpected opcode"); 2916 case TargetOpcode::G_ICMP: 2917 case TargetOpcode::G_FCMP: { 2918 MachineOperand &PredOp = Def->getOperand(1); 2919 CmpInst::Predicate NewP = CmpInst::getInversePredicate( 2920 (CmpInst::Predicate)PredOp.getPredicate()); 2921 PredOp.setPredicate(NewP); 2922 break; 2923 } 2924 case TargetOpcode::G_AND: 2925 Def->setDesc(Builder.getTII().get(TargetOpcode::G_OR)); 2926 break; 2927 case TargetOpcode::G_OR: 2928 Def->setDesc(Builder.getTII().get(TargetOpcode::G_AND)); 2929 break; 2930 } 2931 Observer.changedInstr(*Def); 2932 } 2933 2934 replaceRegWith(MRI, MI.getOperand(0).getReg(), MI.getOperand(1).getReg()); 2935 MI.eraseFromParent(); 2936 } 2937 2938 bool CombinerHelper::matchXorOfAndWithSameReg( 2939 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 2940 // Match (xor (and x, y), y) (or any of its commuted cases) 2941 assert(MI.getOpcode() == TargetOpcode::G_XOR); 2942 Register &X = MatchInfo.first; 2943 Register &Y = MatchInfo.second; 2944 Register AndReg = MI.getOperand(1).getReg(); 2945 Register SharedReg = MI.getOperand(2).getReg(); 2946 2947 // Find a G_AND on either side of the G_XOR. 2948 // Look for one of 2949 // 2950 // (xor (and x, y), SharedReg) 2951 // (xor SharedReg, (and x, y)) 2952 if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) { 2953 std::swap(AndReg, SharedReg); 2954 if (!mi_match(AndReg, MRI, m_GAnd(m_Reg(X), m_Reg(Y)))) 2955 return false; 2956 } 2957 2958 // Only do this if we'll eliminate the G_AND. 2959 if (!MRI.hasOneNonDBGUse(AndReg)) 2960 return false; 2961 2962 // We can combine if SharedReg is the same as either the LHS or RHS of the 2963 // G_AND. 2964 if (Y != SharedReg) 2965 std::swap(X, Y); 2966 return Y == SharedReg; 2967 } 2968 2969 void CombinerHelper::applyXorOfAndWithSameReg( 2970 MachineInstr &MI, std::pair<Register, Register> &MatchInfo) { 2971 // Fold (xor (and x, y), y) -> (and (not x), y) 2972 Builder.setInstrAndDebugLoc(MI); 2973 Register X, Y; 2974 std::tie(X, Y) = MatchInfo; 2975 auto Not = Builder.buildNot(MRI.getType(X), X); 2976 Observer.changingInstr(MI); 2977 MI.setDesc(Builder.getTII().get(TargetOpcode::G_AND)); 2978 MI.getOperand(1).setReg(Not->getOperand(0).getReg()); 2979 MI.getOperand(2).setReg(Y); 2980 Observer.changedInstr(MI); 2981 } 2982 2983 bool CombinerHelper::matchPtrAddZero(MachineInstr &MI) { 2984 auto &PtrAdd = cast<GPtrAdd>(MI); 2985 Register DstReg = PtrAdd.getReg(0); 2986 LLT Ty = MRI.getType(DstReg); 2987 const DataLayout &DL = Builder.getMF().getDataLayout(); 2988 2989 if (DL.isNonIntegralAddressSpace(Ty.getScalarType().getAddressSpace())) 2990 return false; 2991 2992 if (Ty.isPointer()) { 2993 auto ConstVal = getIConstantVRegVal(PtrAdd.getBaseReg(), MRI); 2994 return ConstVal && *ConstVal == 0; 2995 } 2996 2997 assert(Ty.isVector() && "Expecting a vector type"); 2998 const MachineInstr *VecMI = MRI.getVRegDef(PtrAdd.getBaseReg()); 2999 return isBuildVectorAllZeros(*VecMI, MRI); 3000 } 3001 3002 void CombinerHelper::applyPtrAddZero(MachineInstr &MI) { 3003 auto &PtrAdd = cast<GPtrAdd>(MI); 3004 Builder.setInstrAndDebugLoc(PtrAdd); 3005 Builder.buildIntToPtr(PtrAdd.getReg(0), PtrAdd.getOffsetReg()); 3006 PtrAdd.eraseFromParent(); 3007 } 3008 3009 /// The second source operand is known to be a power of 2. 3010 void CombinerHelper::applySimplifyURemByPow2(MachineInstr &MI) { 3011 Register DstReg = MI.getOperand(0).getReg(); 3012 Register Src0 = MI.getOperand(1).getReg(); 3013 Register Pow2Src1 = MI.getOperand(2).getReg(); 3014 LLT Ty = MRI.getType(DstReg); 3015 Builder.setInstrAndDebugLoc(MI); 3016 3017 // Fold (urem x, pow2) -> (and x, pow2-1) 3018 auto NegOne = Builder.buildConstant(Ty, -1); 3019 auto Add = Builder.buildAdd(Ty, Pow2Src1, NegOne); 3020 Builder.buildAnd(DstReg, Src0, Add); 3021 MI.eraseFromParent(); 3022 } 3023 3024 Optional<SmallVector<Register, 8>> 3025 CombinerHelper::findCandidatesForLoadOrCombine(const MachineInstr *Root) const { 3026 assert(Root->getOpcode() == TargetOpcode::G_OR && "Expected G_OR only!"); 3027 // We want to detect if Root is part of a tree which represents a bunch 3028 // of loads being merged into a larger load. We'll try to recognize patterns 3029 // like, for example: 3030 // 3031 // Reg Reg 3032 // \ / 3033 // OR_1 Reg 3034 // \ / 3035 // OR_2 3036 // \ Reg 3037 // .. / 3038 // Root 3039 // 3040 // Reg Reg Reg Reg 3041 // \ / \ / 3042 // OR_1 OR_2 3043 // \ / 3044 // \ / 3045 // ... 3046 // Root 3047 // 3048 // Each "Reg" may have been produced by a load + some arithmetic. This 3049 // function will save each of them. 3050 SmallVector<Register, 8> RegsToVisit; 3051 SmallVector<const MachineInstr *, 7> Ors = {Root}; 3052 3053 // In the "worst" case, we're dealing with a load for each byte. So, there 3054 // are at most #bytes - 1 ORs. 3055 const unsigned MaxIter = 3056 MRI.getType(Root->getOperand(0).getReg()).getSizeInBytes() - 1; 3057 for (unsigned Iter = 0; Iter < MaxIter; ++Iter) { 3058 if (Ors.empty()) 3059 break; 3060 const MachineInstr *Curr = Ors.pop_back_val(); 3061 Register OrLHS = Curr->getOperand(1).getReg(); 3062 Register OrRHS = Curr->getOperand(2).getReg(); 3063 3064 // In the combine, we want to elimate the entire tree. 3065 if (!MRI.hasOneNonDBGUse(OrLHS) || !MRI.hasOneNonDBGUse(OrRHS)) 3066 return None; 3067 3068 // If it's a G_OR, save it and continue to walk. If it's not, then it's 3069 // something that may be a load + arithmetic. 3070 if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrLHS, MRI)) 3071 Ors.push_back(Or); 3072 else 3073 RegsToVisit.push_back(OrLHS); 3074 if (const MachineInstr *Or = getOpcodeDef(TargetOpcode::G_OR, OrRHS, MRI)) 3075 Ors.push_back(Or); 3076 else 3077 RegsToVisit.push_back(OrRHS); 3078 } 3079 3080 // We're going to try and merge each register into a wider power-of-2 type, 3081 // so we ought to have an even number of registers. 3082 if (RegsToVisit.empty() || RegsToVisit.size() % 2 != 0) 3083 return None; 3084 return RegsToVisit; 3085 } 3086 3087 /// Helper function for findLoadOffsetsForLoadOrCombine. 3088 /// 3089 /// Check if \p Reg is the result of loading a \p MemSizeInBits wide value, 3090 /// and then moving that value into a specific byte offset. 3091 /// 3092 /// e.g. x[i] << 24 3093 /// 3094 /// \returns The load instruction and the byte offset it is moved into. 3095 static Optional<std::pair<GZExtLoad *, int64_t>> 3096 matchLoadAndBytePosition(Register Reg, unsigned MemSizeInBits, 3097 const MachineRegisterInfo &MRI) { 3098 assert(MRI.hasOneNonDBGUse(Reg) && 3099 "Expected Reg to only have one non-debug use?"); 3100 Register MaybeLoad; 3101 int64_t Shift; 3102 if (!mi_match(Reg, MRI, 3103 m_OneNonDBGUse(m_GShl(m_Reg(MaybeLoad), m_ICst(Shift))))) { 3104 Shift = 0; 3105 MaybeLoad = Reg; 3106 } 3107 3108 if (Shift % MemSizeInBits != 0) 3109 return None; 3110 3111 // TODO: Handle other types of loads. 3112 auto *Load = getOpcodeDef<GZExtLoad>(MaybeLoad, MRI); 3113 if (!Load) 3114 return None; 3115 3116 if (!Load->isUnordered() || Load->getMemSizeInBits() != MemSizeInBits) 3117 return None; 3118 3119 return std::make_pair(Load, Shift / MemSizeInBits); 3120 } 3121 3122 Optional<std::tuple<GZExtLoad *, int64_t, GZExtLoad *>> 3123 CombinerHelper::findLoadOffsetsForLoadOrCombine( 3124 SmallDenseMap<int64_t, int64_t, 8> &MemOffset2Idx, 3125 const SmallVector<Register, 8> &RegsToVisit, const unsigned MemSizeInBits) { 3126 3127 // Each load found for the pattern. There should be one for each RegsToVisit. 3128 SmallSetVector<const MachineInstr *, 8> Loads; 3129 3130 // The lowest index used in any load. (The lowest "i" for each x[i].) 3131 int64_t LowestIdx = INT64_MAX; 3132 3133 // The load which uses the lowest index. 3134 GZExtLoad *LowestIdxLoad = nullptr; 3135 3136 // Keeps track of the load indices we see. We shouldn't see any indices twice. 3137 SmallSet<int64_t, 8> SeenIdx; 3138 3139 // Ensure each load is in the same MBB. 3140 // TODO: Support multiple MachineBasicBlocks. 3141 MachineBasicBlock *MBB = nullptr; 3142 const MachineMemOperand *MMO = nullptr; 3143 3144 // Earliest instruction-order load in the pattern. 3145 GZExtLoad *EarliestLoad = nullptr; 3146 3147 // Latest instruction-order load in the pattern. 3148 GZExtLoad *LatestLoad = nullptr; 3149 3150 // Base pointer which every load should share. 3151 Register BasePtr; 3152 3153 // We want to find a load for each register. Each load should have some 3154 // appropriate bit twiddling arithmetic. During this loop, we will also keep 3155 // track of the load which uses the lowest index. Later, we will check if we 3156 // can use its pointer in the final, combined load. 3157 for (auto Reg : RegsToVisit) { 3158 // Find the load, and find the position that it will end up in (e.g. a 3159 // shifted) value. 3160 auto LoadAndPos = matchLoadAndBytePosition(Reg, MemSizeInBits, MRI); 3161 if (!LoadAndPos) 3162 return None; 3163 GZExtLoad *Load; 3164 int64_t DstPos; 3165 std::tie(Load, DstPos) = *LoadAndPos; 3166 3167 // TODO: Handle multiple MachineBasicBlocks. Currently not handled because 3168 // it is difficult to check for stores/calls/etc between loads. 3169 MachineBasicBlock *LoadMBB = Load->getParent(); 3170 if (!MBB) 3171 MBB = LoadMBB; 3172 if (LoadMBB != MBB) 3173 return None; 3174 3175 // Make sure that the MachineMemOperands of every seen load are compatible. 3176 auto &LoadMMO = Load->getMMO(); 3177 if (!MMO) 3178 MMO = &LoadMMO; 3179 if (MMO->getAddrSpace() != LoadMMO.getAddrSpace()) 3180 return None; 3181 3182 // Find out what the base pointer and index for the load is. 3183 Register LoadPtr; 3184 int64_t Idx; 3185 if (!mi_match(Load->getOperand(1).getReg(), MRI, 3186 m_GPtrAdd(m_Reg(LoadPtr), m_ICst(Idx)))) { 3187 LoadPtr = Load->getOperand(1).getReg(); 3188 Idx = 0; 3189 } 3190 3191 // Don't combine things like a[i], a[i] -> a bigger load. 3192 if (!SeenIdx.insert(Idx).second) 3193 return None; 3194 3195 // Every load must share the same base pointer; don't combine things like: 3196 // 3197 // a[i], b[i + 1] -> a bigger load. 3198 if (!BasePtr.isValid()) 3199 BasePtr = LoadPtr; 3200 if (BasePtr != LoadPtr) 3201 return None; 3202 3203 if (Idx < LowestIdx) { 3204 LowestIdx = Idx; 3205 LowestIdxLoad = Load; 3206 } 3207 3208 // Keep track of the byte offset that this load ends up at. If we have seen 3209 // the byte offset, then stop here. We do not want to combine: 3210 // 3211 // a[i] << 16, a[i + k] << 16 -> a bigger load. 3212 if (!MemOffset2Idx.try_emplace(DstPos, Idx).second) 3213 return None; 3214 Loads.insert(Load); 3215 3216 // Keep track of the position of the earliest/latest loads in the pattern. 3217 // We will check that there are no load fold barriers between them later 3218 // on. 3219 // 3220 // FIXME: Is there a better way to check for load fold barriers? 3221 if (!EarliestLoad || dominates(*Load, *EarliestLoad)) 3222 EarliestLoad = Load; 3223 if (!LatestLoad || dominates(*LatestLoad, *Load)) 3224 LatestLoad = Load; 3225 } 3226 3227 // We found a load for each register. Let's check if each load satisfies the 3228 // pattern. 3229 assert(Loads.size() == RegsToVisit.size() && 3230 "Expected to find a load for each register?"); 3231 assert(EarliestLoad != LatestLoad && EarliestLoad && 3232 LatestLoad && "Expected at least two loads?"); 3233 3234 // Check if there are any stores, calls, etc. between any of the loads. If 3235 // there are, then we can't safely perform the combine. 3236 // 3237 // MaxIter is chosen based off the (worst case) number of iterations it 3238 // typically takes to succeed in the LLVM test suite plus some padding. 3239 // 3240 // FIXME: Is there a better way to check for load fold barriers? 3241 const unsigned MaxIter = 20; 3242 unsigned Iter = 0; 3243 for (const auto &MI : instructionsWithoutDebug(EarliestLoad->getIterator(), 3244 LatestLoad->getIterator())) { 3245 if (Loads.count(&MI)) 3246 continue; 3247 if (MI.isLoadFoldBarrier()) 3248 return None; 3249 if (Iter++ == MaxIter) 3250 return None; 3251 } 3252 3253 return std::make_tuple(LowestIdxLoad, LowestIdx, LatestLoad); 3254 } 3255 3256 bool CombinerHelper::matchLoadOrCombine( 3257 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 3258 assert(MI.getOpcode() == TargetOpcode::G_OR); 3259 MachineFunction &MF = *MI.getMF(); 3260 // Assuming a little-endian target, transform: 3261 // s8 *a = ... 3262 // s32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 3263 // => 3264 // s32 val = *((i32)a) 3265 // 3266 // s8 *a = ... 3267 // s32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 3268 // => 3269 // s32 val = BSWAP(*((s32)a)) 3270 Register Dst = MI.getOperand(0).getReg(); 3271 LLT Ty = MRI.getType(Dst); 3272 if (Ty.isVector()) 3273 return false; 3274 3275 // We need to combine at least two loads into this type. Since the smallest 3276 // possible load is into a byte, we need at least a 16-bit wide type. 3277 const unsigned WideMemSizeInBits = Ty.getSizeInBits(); 3278 if (WideMemSizeInBits < 16 || WideMemSizeInBits % 8 != 0) 3279 return false; 3280 3281 // Match a collection of non-OR instructions in the pattern. 3282 auto RegsToVisit = findCandidatesForLoadOrCombine(&MI); 3283 if (!RegsToVisit) 3284 return false; 3285 3286 // We have a collection of non-OR instructions. Figure out how wide each of 3287 // the small loads should be based off of the number of potential loads we 3288 // found. 3289 const unsigned NarrowMemSizeInBits = WideMemSizeInBits / RegsToVisit->size(); 3290 if (NarrowMemSizeInBits % 8 != 0) 3291 return false; 3292 3293 // Check if each register feeding into each OR is a load from the same 3294 // base pointer + some arithmetic. 3295 // 3296 // e.g. a[0], a[1] << 8, a[2] << 16, etc. 3297 // 3298 // Also verify that each of these ends up putting a[i] into the same memory 3299 // offset as a load into a wide type would. 3300 SmallDenseMap<int64_t, int64_t, 8> MemOffset2Idx; 3301 GZExtLoad *LowestIdxLoad, *LatestLoad; 3302 int64_t LowestIdx; 3303 auto MaybeLoadInfo = findLoadOffsetsForLoadOrCombine( 3304 MemOffset2Idx, *RegsToVisit, NarrowMemSizeInBits); 3305 if (!MaybeLoadInfo) 3306 return false; 3307 std::tie(LowestIdxLoad, LowestIdx, LatestLoad) = *MaybeLoadInfo; 3308 3309 // We have a bunch of loads being OR'd together. Using the addresses + offsets 3310 // we found before, check if this corresponds to a big or little endian byte 3311 // pattern. If it does, then we can represent it using a load + possibly a 3312 // BSWAP. 3313 bool IsBigEndianTarget = MF.getDataLayout().isBigEndian(); 3314 Optional<bool> IsBigEndian = isBigEndian(MemOffset2Idx, LowestIdx); 3315 if (!IsBigEndian.hasValue()) 3316 return false; 3317 bool NeedsBSwap = IsBigEndianTarget != *IsBigEndian; 3318 if (NeedsBSwap && !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {Ty}})) 3319 return false; 3320 3321 // Make sure that the load from the lowest index produces offset 0 in the 3322 // final value. 3323 // 3324 // This ensures that we won't combine something like this: 3325 // 3326 // load x[i] -> byte 2 3327 // load x[i+1] -> byte 0 ---> wide_load x[i] 3328 // load x[i+2] -> byte 1 3329 const unsigned NumLoadsInTy = WideMemSizeInBits / NarrowMemSizeInBits; 3330 const unsigned ZeroByteOffset = 3331 *IsBigEndian 3332 ? bigEndianByteAt(NumLoadsInTy, 0) 3333 : littleEndianByteAt(NumLoadsInTy, 0); 3334 auto ZeroOffsetIdx = MemOffset2Idx.find(ZeroByteOffset); 3335 if (ZeroOffsetIdx == MemOffset2Idx.end() || 3336 ZeroOffsetIdx->second != LowestIdx) 3337 return false; 3338 3339 // We wil reuse the pointer from the load which ends up at byte offset 0. It 3340 // may not use index 0. 3341 Register Ptr = LowestIdxLoad->getPointerReg(); 3342 const MachineMemOperand &MMO = LowestIdxLoad->getMMO(); 3343 LegalityQuery::MemDesc MMDesc(MMO); 3344 MMDesc.MemoryTy = Ty; 3345 if (!isLegalOrBeforeLegalizer( 3346 {TargetOpcode::G_LOAD, {Ty, MRI.getType(Ptr)}, {MMDesc}})) 3347 return false; 3348 auto PtrInfo = MMO.getPointerInfo(); 3349 auto *NewMMO = MF.getMachineMemOperand(&MMO, PtrInfo, WideMemSizeInBits / 8); 3350 3351 // Load must be allowed and fast on the target. 3352 LLVMContext &C = MF.getFunction().getContext(); 3353 auto &DL = MF.getDataLayout(); 3354 bool Fast = false; 3355 if (!getTargetLowering().allowsMemoryAccess(C, DL, Ty, *NewMMO, &Fast) || 3356 !Fast) 3357 return false; 3358 3359 MatchInfo = [=](MachineIRBuilder &MIB) { 3360 MIB.setInstrAndDebugLoc(*LatestLoad); 3361 Register LoadDst = NeedsBSwap ? MRI.cloneVirtualRegister(Dst) : Dst; 3362 MIB.buildLoad(LoadDst, Ptr, *NewMMO); 3363 if (NeedsBSwap) 3364 MIB.buildBSwap(Dst, LoadDst); 3365 }; 3366 return true; 3367 } 3368 3369 /// Check if the store \p Store is a truncstore that can be merged. That is, 3370 /// it's a store of a shifted value of \p SrcVal. If \p SrcVal is an empty 3371 /// Register then it does not need to match and SrcVal is set to the source 3372 /// value found. 3373 /// On match, returns the start byte offset of the \p SrcVal that is being 3374 /// stored. 3375 static Optional<int64_t> getTruncStoreByteOffset(GStore &Store, Register &SrcVal, 3376 MachineRegisterInfo &MRI) { 3377 Register TruncVal; 3378 if (!mi_match(Store.getValueReg(), MRI, m_GTrunc(m_Reg(TruncVal)))) 3379 return None; 3380 3381 // The shift amount must be a constant multiple of the narrow type. 3382 // It is translated to the offset address in the wide source value "y". 3383 // 3384 // x = G_LSHR y, ShiftAmtC 3385 // s8 z = G_TRUNC x 3386 // store z, ... 3387 Register FoundSrcVal; 3388 int64_t ShiftAmt; 3389 if (!mi_match(TruncVal, MRI, 3390 m_any_of(m_GLShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt)), 3391 m_GAShr(m_Reg(FoundSrcVal), m_ICst(ShiftAmt))))) { 3392 if (!SrcVal.isValid() || TruncVal == SrcVal) { 3393 if (!SrcVal.isValid()) 3394 SrcVal = TruncVal; 3395 return 0; // If it's the lowest index store. 3396 } 3397 return None; 3398 } 3399 3400 unsigned NarrowBits = Store.getMMO().getMemoryType().getScalarSizeInBits(); 3401 if (ShiftAmt % NarrowBits!= 0) 3402 return None; 3403 const unsigned Offset = ShiftAmt / NarrowBits; 3404 3405 if (SrcVal.isValid() && FoundSrcVal != SrcVal) 3406 return None; 3407 3408 if (!SrcVal.isValid()) 3409 SrcVal = FoundSrcVal; 3410 else if (MRI.getType(SrcVal) != MRI.getType(FoundSrcVal)) 3411 return None; 3412 return Offset; 3413 } 3414 3415 /// Match a pattern where a wide type scalar value is stored by several narrow 3416 /// stores. Fold it into a single store or a BSWAP and a store if the targets 3417 /// supports it. 3418 /// 3419 /// Assuming little endian target: 3420 /// i8 *p = ... 3421 /// i32 val = ... 3422 /// p[0] = (val >> 0) & 0xFF; 3423 /// p[1] = (val >> 8) & 0xFF; 3424 /// p[2] = (val >> 16) & 0xFF; 3425 /// p[3] = (val >> 24) & 0xFF; 3426 /// => 3427 /// *((i32)p) = val; 3428 /// 3429 /// i8 *p = ... 3430 /// i32 val = ... 3431 /// p[0] = (val >> 24) & 0xFF; 3432 /// p[1] = (val >> 16) & 0xFF; 3433 /// p[2] = (val >> 8) & 0xFF; 3434 /// p[3] = (val >> 0) & 0xFF; 3435 /// => 3436 /// *((i32)p) = BSWAP(val); 3437 bool CombinerHelper::matchTruncStoreMerge(MachineInstr &MI, 3438 MergeTruncStoresInfo &MatchInfo) { 3439 auto &StoreMI = cast<GStore>(MI); 3440 LLT MemTy = StoreMI.getMMO().getMemoryType(); 3441 3442 // We only handle merging simple stores of 1-4 bytes. 3443 if (!MemTy.isScalar()) 3444 return false; 3445 switch (MemTy.getSizeInBits()) { 3446 case 8: 3447 case 16: 3448 case 32: 3449 break; 3450 default: 3451 return false; 3452 } 3453 if (!StoreMI.isSimple()) 3454 return false; 3455 3456 // We do a simple search for mergeable stores prior to this one. 3457 // Any potential alias hazard along the way terminates the search. 3458 SmallVector<GStore *> FoundStores; 3459 3460 // We're looking for: 3461 // 1) a (store(trunc(...))) 3462 // 2) of an LSHR/ASHR of a single wide value, by the appropriate shift to get 3463 // the partial value stored. 3464 // 3) where the offsets form either a little or big-endian sequence. 3465 3466 auto &LastStore = StoreMI; 3467 3468 // The single base pointer that all stores must use. 3469 Register BaseReg; 3470 int64_t LastOffset; 3471 if (!mi_match(LastStore.getPointerReg(), MRI, 3472 m_GPtrAdd(m_Reg(BaseReg), m_ICst(LastOffset)))) { 3473 BaseReg = LastStore.getPointerReg(); 3474 LastOffset = 0; 3475 } 3476 3477 GStore *LowestIdxStore = &LastStore; 3478 int64_t LowestIdxOffset = LastOffset; 3479 3480 Register WideSrcVal; 3481 auto LowestShiftAmt = getTruncStoreByteOffset(LastStore, WideSrcVal, MRI); 3482 if (!LowestShiftAmt) 3483 return false; // Didn't match a trunc. 3484 assert(WideSrcVal.isValid()); 3485 3486 LLT WideStoreTy = MRI.getType(WideSrcVal); 3487 // The wide type might not be a multiple of the memory type, e.g. s48 and s32. 3488 if (WideStoreTy.getSizeInBits() % MemTy.getSizeInBits() != 0) 3489 return false; 3490 const unsigned NumStoresRequired = 3491 WideStoreTy.getSizeInBits() / MemTy.getSizeInBits(); 3492 3493 SmallVector<int64_t, 8> OffsetMap(NumStoresRequired, INT64_MAX); 3494 OffsetMap[*LowestShiftAmt] = LastOffset; 3495 FoundStores.emplace_back(&LastStore); 3496 3497 // Search the block up for more stores. 3498 // We use a search threshold of 10 instructions here because the combiner 3499 // works top-down within a block, and we don't want to search an unbounded 3500 // number of predecessor instructions trying to find matching stores. 3501 // If we moved this optimization into a separate pass then we could probably 3502 // use a more efficient search without having a hard-coded threshold. 3503 const int MaxInstsToCheck = 10; 3504 int NumInstsChecked = 0; 3505 for (auto II = ++LastStore.getReverseIterator(); 3506 II != LastStore.getParent()->rend() && NumInstsChecked < MaxInstsToCheck; 3507 ++II) { 3508 NumInstsChecked++; 3509 GStore *NewStore; 3510 if ((NewStore = dyn_cast<GStore>(&*II))) { 3511 if (NewStore->getMMO().getMemoryType() != MemTy || !NewStore->isSimple()) 3512 break; 3513 } else if (II->isLoadFoldBarrier() || II->mayLoad()) { 3514 break; 3515 } else { 3516 continue; // This is a safe instruction we can look past. 3517 } 3518 3519 Register NewBaseReg; 3520 int64_t MemOffset; 3521 // Check we're storing to the same base + some offset. 3522 if (!mi_match(NewStore->getPointerReg(), MRI, 3523 m_GPtrAdd(m_Reg(NewBaseReg), m_ICst(MemOffset)))) { 3524 NewBaseReg = NewStore->getPointerReg(); 3525 MemOffset = 0; 3526 } 3527 if (BaseReg != NewBaseReg) 3528 break; 3529 3530 auto ShiftByteOffset = getTruncStoreByteOffset(*NewStore, WideSrcVal, MRI); 3531 if (!ShiftByteOffset) 3532 break; 3533 if (MemOffset < LowestIdxOffset) { 3534 LowestIdxOffset = MemOffset; 3535 LowestIdxStore = NewStore; 3536 } 3537 3538 // Map the offset in the store and the offset in the combined value, and 3539 // early return if it has been set before. 3540 if (*ShiftByteOffset < 0 || *ShiftByteOffset >= NumStoresRequired || 3541 OffsetMap[*ShiftByteOffset] != INT64_MAX) 3542 break; 3543 OffsetMap[*ShiftByteOffset] = MemOffset; 3544 3545 FoundStores.emplace_back(NewStore); 3546 // Reset counter since we've found a matching inst. 3547 NumInstsChecked = 0; 3548 if (FoundStores.size() == NumStoresRequired) 3549 break; 3550 } 3551 3552 if (FoundStores.size() != NumStoresRequired) { 3553 return false; 3554 } 3555 3556 const auto &DL = LastStore.getMF()->getDataLayout(); 3557 auto &C = LastStore.getMF()->getFunction().getContext(); 3558 // Check that a store of the wide type is both allowed and fast on the target 3559 bool Fast = false; 3560 bool Allowed = getTargetLowering().allowsMemoryAccess( 3561 C, DL, WideStoreTy, LowestIdxStore->getMMO(), &Fast); 3562 if (!Allowed || !Fast) 3563 return false; 3564 3565 // Check if the pieces of the value are going to the expected places in memory 3566 // to merge the stores. 3567 unsigned NarrowBits = MemTy.getScalarSizeInBits(); 3568 auto checkOffsets = [&](bool MatchLittleEndian) { 3569 if (MatchLittleEndian) { 3570 for (unsigned i = 0; i != NumStoresRequired; ++i) 3571 if (OffsetMap[i] != i * (NarrowBits / 8) + LowestIdxOffset) 3572 return false; 3573 } else { // MatchBigEndian by reversing loop counter. 3574 for (unsigned i = 0, j = NumStoresRequired - 1; i != NumStoresRequired; 3575 ++i, --j) 3576 if (OffsetMap[j] != i * (NarrowBits / 8) + LowestIdxOffset) 3577 return false; 3578 } 3579 return true; 3580 }; 3581 3582 // Check if the offsets line up for the native data layout of this target. 3583 bool NeedBswap = false; 3584 bool NeedRotate = false; 3585 if (!checkOffsets(DL.isLittleEndian())) { 3586 // Special-case: check if byte offsets line up for the opposite endian. 3587 if (NarrowBits == 8 && checkOffsets(DL.isBigEndian())) 3588 NeedBswap = true; 3589 else if (NumStoresRequired == 2 && checkOffsets(DL.isBigEndian())) 3590 NeedRotate = true; 3591 else 3592 return false; 3593 } 3594 3595 if (NeedBswap && 3596 !isLegalOrBeforeLegalizer({TargetOpcode::G_BSWAP, {WideStoreTy}})) 3597 return false; 3598 if (NeedRotate && 3599 !isLegalOrBeforeLegalizer({TargetOpcode::G_ROTR, {WideStoreTy}})) 3600 return false; 3601 3602 MatchInfo.NeedBSwap = NeedBswap; 3603 MatchInfo.NeedRotate = NeedRotate; 3604 MatchInfo.LowestIdxStore = LowestIdxStore; 3605 MatchInfo.WideSrcVal = WideSrcVal; 3606 MatchInfo.FoundStores = std::move(FoundStores); 3607 return true; 3608 } 3609 3610 void CombinerHelper::applyTruncStoreMerge(MachineInstr &MI, 3611 MergeTruncStoresInfo &MatchInfo) { 3612 3613 Builder.setInstrAndDebugLoc(MI); 3614 Register WideSrcVal = MatchInfo.WideSrcVal; 3615 LLT WideStoreTy = MRI.getType(WideSrcVal); 3616 3617 if (MatchInfo.NeedBSwap) { 3618 WideSrcVal = Builder.buildBSwap(WideStoreTy, WideSrcVal).getReg(0); 3619 } else if (MatchInfo.NeedRotate) { 3620 assert(WideStoreTy.getSizeInBits() % 2 == 0 && 3621 "Unexpected type for rotate"); 3622 auto RotAmt = 3623 Builder.buildConstant(WideStoreTy, WideStoreTy.getSizeInBits() / 2); 3624 WideSrcVal = 3625 Builder.buildRotateRight(WideStoreTy, WideSrcVal, RotAmt).getReg(0); 3626 } 3627 3628 Builder.buildStore(WideSrcVal, MatchInfo.LowestIdxStore->getPointerReg(), 3629 MatchInfo.LowestIdxStore->getMMO().getPointerInfo(), 3630 MatchInfo.LowestIdxStore->getMMO().getAlign()); 3631 3632 // Erase the old stores. 3633 for (auto *ST : MatchInfo.FoundStores) 3634 ST->eraseFromParent(); 3635 } 3636 3637 bool CombinerHelper::matchExtendThroughPhis(MachineInstr &MI, 3638 MachineInstr *&ExtMI) { 3639 assert(MI.getOpcode() == TargetOpcode::G_PHI); 3640 3641 Register DstReg = MI.getOperand(0).getReg(); 3642 3643 // TODO: Extending a vector may be expensive, don't do this until heuristics 3644 // are better. 3645 if (MRI.getType(DstReg).isVector()) 3646 return false; 3647 3648 // Try to match a phi, whose only use is an extend. 3649 if (!MRI.hasOneNonDBGUse(DstReg)) 3650 return false; 3651 ExtMI = &*MRI.use_instr_nodbg_begin(DstReg); 3652 switch (ExtMI->getOpcode()) { 3653 case TargetOpcode::G_ANYEXT: 3654 return true; // G_ANYEXT is usually free. 3655 case TargetOpcode::G_ZEXT: 3656 case TargetOpcode::G_SEXT: 3657 break; 3658 default: 3659 return false; 3660 } 3661 3662 // If the target is likely to fold this extend away, don't propagate. 3663 if (Builder.getTII().isExtendLikelyToBeFolded(*ExtMI, MRI)) 3664 return false; 3665 3666 // We don't want to propagate the extends unless there's a good chance that 3667 // they'll be optimized in some way. 3668 // Collect the unique incoming values. 3669 SmallPtrSet<MachineInstr *, 4> InSrcs; 3670 for (unsigned Idx = 1; Idx < MI.getNumOperands(); Idx += 2) { 3671 auto *DefMI = getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI); 3672 switch (DefMI->getOpcode()) { 3673 case TargetOpcode::G_LOAD: 3674 case TargetOpcode::G_TRUNC: 3675 case TargetOpcode::G_SEXT: 3676 case TargetOpcode::G_ZEXT: 3677 case TargetOpcode::G_ANYEXT: 3678 case TargetOpcode::G_CONSTANT: 3679 InSrcs.insert(getDefIgnoringCopies(MI.getOperand(Idx).getReg(), MRI)); 3680 // Don't try to propagate if there are too many places to create new 3681 // extends, chances are it'll increase code size. 3682 if (InSrcs.size() > 2) 3683 return false; 3684 break; 3685 default: 3686 return false; 3687 } 3688 } 3689 return true; 3690 } 3691 3692 void CombinerHelper::applyExtendThroughPhis(MachineInstr &MI, 3693 MachineInstr *&ExtMI) { 3694 assert(MI.getOpcode() == TargetOpcode::G_PHI); 3695 Register DstReg = ExtMI->getOperand(0).getReg(); 3696 LLT ExtTy = MRI.getType(DstReg); 3697 3698 // Propagate the extension into the block of each incoming reg's block. 3699 // Use a SetVector here because PHIs can have duplicate edges, and we want 3700 // deterministic iteration order. 3701 SmallSetVector<MachineInstr *, 8> SrcMIs; 3702 SmallDenseMap<MachineInstr *, MachineInstr *, 8> OldToNewSrcMap; 3703 for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); SrcIdx += 2) { 3704 auto *SrcMI = MRI.getVRegDef(MI.getOperand(SrcIdx).getReg()); 3705 if (!SrcMIs.insert(SrcMI)) 3706 continue; 3707 3708 // Build an extend after each src inst. 3709 auto *MBB = SrcMI->getParent(); 3710 MachineBasicBlock::iterator InsertPt = ++SrcMI->getIterator(); 3711 if (InsertPt != MBB->end() && InsertPt->isPHI()) 3712 InsertPt = MBB->getFirstNonPHI(); 3713 3714 Builder.setInsertPt(*SrcMI->getParent(), InsertPt); 3715 Builder.setDebugLoc(MI.getDebugLoc()); 3716 auto NewExt = Builder.buildExtOrTrunc(ExtMI->getOpcode(), ExtTy, 3717 SrcMI->getOperand(0).getReg()); 3718 OldToNewSrcMap[SrcMI] = NewExt; 3719 } 3720 3721 // Create a new phi with the extended inputs. 3722 Builder.setInstrAndDebugLoc(MI); 3723 auto NewPhi = Builder.buildInstrNoInsert(TargetOpcode::G_PHI); 3724 NewPhi.addDef(DstReg); 3725 for (unsigned SrcIdx = 1; SrcIdx < MI.getNumOperands(); ++SrcIdx) { 3726 auto &MO = MI.getOperand(SrcIdx); 3727 if (!MO.isReg()) { 3728 NewPhi.addMBB(MO.getMBB()); 3729 continue; 3730 } 3731 auto *NewSrc = OldToNewSrcMap[MRI.getVRegDef(MO.getReg())]; 3732 NewPhi.addUse(NewSrc->getOperand(0).getReg()); 3733 } 3734 Builder.insertInstr(NewPhi); 3735 ExtMI->eraseFromParent(); 3736 } 3737 3738 bool CombinerHelper::matchExtractVecEltBuildVec(MachineInstr &MI, 3739 Register &Reg) { 3740 assert(MI.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT); 3741 // If we have a constant index, look for a G_BUILD_VECTOR source 3742 // and find the source register that the index maps to. 3743 Register SrcVec = MI.getOperand(1).getReg(); 3744 LLT SrcTy = MRI.getType(SrcVec); 3745 if (!isLegalOrBeforeLegalizer( 3746 {TargetOpcode::G_BUILD_VECTOR, {SrcTy, SrcTy.getElementType()}})) 3747 return false; 3748 3749 auto Cst = getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 3750 if (!Cst || Cst->Value.getZExtValue() >= SrcTy.getNumElements()) 3751 return false; 3752 3753 unsigned VecIdx = Cst->Value.getZExtValue(); 3754 MachineInstr *BuildVecMI = 3755 getOpcodeDef(TargetOpcode::G_BUILD_VECTOR, SrcVec, MRI); 3756 if (!BuildVecMI) { 3757 BuildVecMI = getOpcodeDef(TargetOpcode::G_BUILD_VECTOR_TRUNC, SrcVec, MRI); 3758 if (!BuildVecMI) 3759 return false; 3760 LLT ScalarTy = MRI.getType(BuildVecMI->getOperand(1).getReg()); 3761 if (!isLegalOrBeforeLegalizer( 3762 {TargetOpcode::G_BUILD_VECTOR_TRUNC, {SrcTy, ScalarTy}})) 3763 return false; 3764 } 3765 3766 EVT Ty(getMVTForLLT(SrcTy)); 3767 if (!MRI.hasOneNonDBGUse(SrcVec) && 3768 !getTargetLowering().aggressivelyPreferBuildVectorSources(Ty)) 3769 return false; 3770 3771 Reg = BuildVecMI->getOperand(VecIdx + 1).getReg(); 3772 return true; 3773 } 3774 3775 void CombinerHelper::applyExtractVecEltBuildVec(MachineInstr &MI, 3776 Register &Reg) { 3777 // Check the type of the register, since it may have come from a 3778 // G_BUILD_VECTOR_TRUNC. 3779 LLT ScalarTy = MRI.getType(Reg); 3780 Register DstReg = MI.getOperand(0).getReg(); 3781 LLT DstTy = MRI.getType(DstReg); 3782 3783 Builder.setInstrAndDebugLoc(MI); 3784 if (ScalarTy != DstTy) { 3785 assert(ScalarTy.getSizeInBits() > DstTy.getSizeInBits()); 3786 Builder.buildTrunc(DstReg, Reg); 3787 MI.eraseFromParent(); 3788 return; 3789 } 3790 replaceSingleDefInstWithReg(MI, Reg); 3791 } 3792 3793 bool CombinerHelper::matchExtractAllEltsFromBuildVector( 3794 MachineInstr &MI, 3795 SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) { 3796 assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR); 3797 // This combine tries to find build_vector's which have every source element 3798 // extracted using G_EXTRACT_VECTOR_ELT. This can happen when transforms like 3799 // the masked load scalarization is run late in the pipeline. There's already 3800 // a combine for a similar pattern starting from the extract, but that 3801 // doesn't attempt to do it if there are multiple uses of the build_vector, 3802 // which in this case is true. Starting the combine from the build_vector 3803 // feels more natural than trying to find sibling nodes of extracts. 3804 // E.g. 3805 // %vec(<4 x s32>) = G_BUILD_VECTOR %s1(s32), %s2, %s3, %s4 3806 // %ext1 = G_EXTRACT_VECTOR_ELT %vec, 0 3807 // %ext2 = G_EXTRACT_VECTOR_ELT %vec, 1 3808 // %ext3 = G_EXTRACT_VECTOR_ELT %vec, 2 3809 // %ext4 = G_EXTRACT_VECTOR_ELT %vec, 3 3810 // ==> 3811 // replace ext{1,2,3,4} with %s{1,2,3,4} 3812 3813 Register DstReg = MI.getOperand(0).getReg(); 3814 LLT DstTy = MRI.getType(DstReg); 3815 unsigned NumElts = DstTy.getNumElements(); 3816 3817 SmallBitVector ExtractedElts(NumElts); 3818 for (auto &II : make_range(MRI.use_instr_nodbg_begin(DstReg), 3819 MRI.use_instr_nodbg_end())) { 3820 if (II.getOpcode() != TargetOpcode::G_EXTRACT_VECTOR_ELT) 3821 return false; 3822 auto Cst = getIConstantVRegVal(II.getOperand(2).getReg(), MRI); 3823 if (!Cst) 3824 return false; 3825 unsigned Idx = Cst.getValue().getZExtValue(); 3826 if (Idx >= NumElts) 3827 return false; // Out of range. 3828 ExtractedElts.set(Idx); 3829 SrcDstPairs.emplace_back( 3830 std::make_pair(MI.getOperand(Idx + 1).getReg(), &II)); 3831 } 3832 // Match if every element was extracted. 3833 return ExtractedElts.all(); 3834 } 3835 3836 void CombinerHelper::applyExtractAllEltsFromBuildVector( 3837 MachineInstr &MI, 3838 SmallVectorImpl<std::pair<Register, MachineInstr *>> &SrcDstPairs) { 3839 assert(MI.getOpcode() == TargetOpcode::G_BUILD_VECTOR); 3840 for (auto &Pair : SrcDstPairs) { 3841 auto *ExtMI = Pair.second; 3842 replaceRegWith(MRI, ExtMI->getOperand(0).getReg(), Pair.first); 3843 ExtMI->eraseFromParent(); 3844 } 3845 MI.eraseFromParent(); 3846 } 3847 3848 void CombinerHelper::applyBuildFn( 3849 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 3850 Builder.setInstrAndDebugLoc(MI); 3851 MatchInfo(Builder); 3852 MI.eraseFromParent(); 3853 } 3854 3855 void CombinerHelper::applyBuildFnNoErase( 3856 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 3857 Builder.setInstrAndDebugLoc(MI); 3858 MatchInfo(Builder); 3859 } 3860 3861 /// Match an FSHL or FSHR that can be combined to a ROTR or ROTL rotate. 3862 bool CombinerHelper::matchFunnelShiftToRotate(MachineInstr &MI) { 3863 unsigned Opc = MI.getOpcode(); 3864 assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR); 3865 Register X = MI.getOperand(1).getReg(); 3866 Register Y = MI.getOperand(2).getReg(); 3867 if (X != Y) 3868 return false; 3869 unsigned RotateOpc = 3870 Opc == TargetOpcode::G_FSHL ? TargetOpcode::G_ROTL : TargetOpcode::G_ROTR; 3871 return isLegalOrBeforeLegalizer({RotateOpc, {MRI.getType(X), MRI.getType(Y)}}); 3872 } 3873 3874 void CombinerHelper::applyFunnelShiftToRotate(MachineInstr &MI) { 3875 unsigned Opc = MI.getOpcode(); 3876 assert(Opc == TargetOpcode::G_FSHL || Opc == TargetOpcode::G_FSHR); 3877 bool IsFSHL = Opc == TargetOpcode::G_FSHL; 3878 Observer.changingInstr(MI); 3879 MI.setDesc(Builder.getTII().get(IsFSHL ? TargetOpcode::G_ROTL 3880 : TargetOpcode::G_ROTR)); 3881 MI.RemoveOperand(2); 3882 Observer.changedInstr(MI); 3883 } 3884 3885 // Fold (rot x, c) -> (rot x, c % BitSize) 3886 bool CombinerHelper::matchRotateOutOfRange(MachineInstr &MI) { 3887 assert(MI.getOpcode() == TargetOpcode::G_ROTL || 3888 MI.getOpcode() == TargetOpcode::G_ROTR); 3889 unsigned Bitsize = 3890 MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits(); 3891 Register AmtReg = MI.getOperand(2).getReg(); 3892 bool OutOfRange = false; 3893 auto MatchOutOfRange = [Bitsize, &OutOfRange](const Constant *C) { 3894 if (auto *CI = dyn_cast<ConstantInt>(C)) 3895 OutOfRange |= CI->getValue().uge(Bitsize); 3896 return true; 3897 }; 3898 return matchUnaryPredicate(MRI, AmtReg, MatchOutOfRange) && OutOfRange; 3899 } 3900 3901 void CombinerHelper::applyRotateOutOfRange(MachineInstr &MI) { 3902 assert(MI.getOpcode() == TargetOpcode::G_ROTL || 3903 MI.getOpcode() == TargetOpcode::G_ROTR); 3904 unsigned Bitsize = 3905 MRI.getType(MI.getOperand(0).getReg()).getScalarSizeInBits(); 3906 Builder.setInstrAndDebugLoc(MI); 3907 Register Amt = MI.getOperand(2).getReg(); 3908 LLT AmtTy = MRI.getType(Amt); 3909 auto Bits = Builder.buildConstant(AmtTy, Bitsize); 3910 Amt = Builder.buildURem(AmtTy, MI.getOperand(2).getReg(), Bits).getReg(0); 3911 Observer.changingInstr(MI); 3912 MI.getOperand(2).setReg(Amt); 3913 Observer.changedInstr(MI); 3914 } 3915 3916 bool CombinerHelper::matchICmpToTrueFalseKnownBits(MachineInstr &MI, 3917 int64_t &MatchInfo) { 3918 assert(MI.getOpcode() == TargetOpcode::G_ICMP); 3919 auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate()); 3920 auto KnownLHS = KB->getKnownBits(MI.getOperand(2).getReg()); 3921 auto KnownRHS = KB->getKnownBits(MI.getOperand(3).getReg()); 3922 Optional<bool> KnownVal; 3923 switch (Pred) { 3924 default: 3925 llvm_unreachable("Unexpected G_ICMP predicate?"); 3926 case CmpInst::ICMP_EQ: 3927 KnownVal = KnownBits::eq(KnownLHS, KnownRHS); 3928 break; 3929 case CmpInst::ICMP_NE: 3930 KnownVal = KnownBits::ne(KnownLHS, KnownRHS); 3931 break; 3932 case CmpInst::ICMP_SGE: 3933 KnownVal = KnownBits::sge(KnownLHS, KnownRHS); 3934 break; 3935 case CmpInst::ICMP_SGT: 3936 KnownVal = KnownBits::sgt(KnownLHS, KnownRHS); 3937 break; 3938 case CmpInst::ICMP_SLE: 3939 KnownVal = KnownBits::sle(KnownLHS, KnownRHS); 3940 break; 3941 case CmpInst::ICMP_SLT: 3942 KnownVal = KnownBits::slt(KnownLHS, KnownRHS); 3943 break; 3944 case CmpInst::ICMP_UGE: 3945 KnownVal = KnownBits::uge(KnownLHS, KnownRHS); 3946 break; 3947 case CmpInst::ICMP_UGT: 3948 KnownVal = KnownBits::ugt(KnownLHS, KnownRHS); 3949 break; 3950 case CmpInst::ICMP_ULE: 3951 KnownVal = KnownBits::ule(KnownLHS, KnownRHS); 3952 break; 3953 case CmpInst::ICMP_ULT: 3954 KnownVal = KnownBits::ult(KnownLHS, KnownRHS); 3955 break; 3956 } 3957 if (!KnownVal) 3958 return false; 3959 MatchInfo = 3960 *KnownVal 3961 ? getICmpTrueVal(getTargetLowering(), 3962 /*IsVector = */ 3963 MRI.getType(MI.getOperand(0).getReg()).isVector(), 3964 /* IsFP = */ false) 3965 : 0; 3966 return true; 3967 } 3968 3969 bool CombinerHelper::matchICmpToLHSKnownBits( 3970 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 3971 assert(MI.getOpcode() == TargetOpcode::G_ICMP); 3972 // Given: 3973 // 3974 // %x = G_WHATEVER (... x is known to be 0 or 1 ...) 3975 // %cmp = G_ICMP ne %x, 0 3976 // 3977 // Or: 3978 // 3979 // %x = G_WHATEVER (... x is known to be 0 or 1 ...) 3980 // %cmp = G_ICMP eq %x, 1 3981 // 3982 // We can replace %cmp with %x assuming true is 1 on the target. 3983 auto Pred = static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate()); 3984 if (!CmpInst::isEquality(Pred)) 3985 return false; 3986 Register Dst = MI.getOperand(0).getReg(); 3987 LLT DstTy = MRI.getType(Dst); 3988 if (getICmpTrueVal(getTargetLowering(), DstTy.isVector(), 3989 /* IsFP = */ false) != 1) 3990 return false; 3991 int64_t OneOrZero = Pred == CmpInst::ICMP_EQ; 3992 if (!mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(OneOrZero))) 3993 return false; 3994 Register LHS = MI.getOperand(2).getReg(); 3995 auto KnownLHS = KB->getKnownBits(LHS); 3996 if (KnownLHS.getMinValue() != 0 || KnownLHS.getMaxValue() != 1) 3997 return false; 3998 // Make sure replacing Dst with the LHS is a legal operation. 3999 LLT LHSTy = MRI.getType(LHS); 4000 unsigned LHSSize = LHSTy.getSizeInBits(); 4001 unsigned DstSize = DstTy.getSizeInBits(); 4002 unsigned Op = TargetOpcode::COPY; 4003 if (DstSize != LHSSize) 4004 Op = DstSize < LHSSize ? TargetOpcode::G_TRUNC : TargetOpcode::G_ZEXT; 4005 if (!isLegalOrBeforeLegalizer({Op, {DstTy, LHSTy}})) 4006 return false; 4007 MatchInfo = [=](MachineIRBuilder &B) { B.buildInstr(Op, {Dst}, {LHS}); }; 4008 return true; 4009 } 4010 4011 /// Form a G_SBFX from a G_SEXT_INREG fed by a right shift. 4012 bool CombinerHelper::matchBitfieldExtractFromSExtInReg( 4013 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 4014 assert(MI.getOpcode() == TargetOpcode::G_SEXT_INREG); 4015 Register Dst = MI.getOperand(0).getReg(); 4016 Register Src = MI.getOperand(1).getReg(); 4017 LLT Ty = MRI.getType(Src); 4018 LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty); 4019 if (!LI || !LI->isLegalOrCustom({TargetOpcode::G_SBFX, {Ty, ExtractTy}})) 4020 return false; 4021 int64_t Width = MI.getOperand(2).getImm(); 4022 Register ShiftSrc; 4023 int64_t ShiftImm; 4024 if (!mi_match( 4025 Src, MRI, 4026 m_OneNonDBGUse(m_any_of(m_GAShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)), 4027 m_GLShr(m_Reg(ShiftSrc), m_ICst(ShiftImm)))))) 4028 return false; 4029 if (ShiftImm < 0 || ShiftImm + Width > Ty.getScalarSizeInBits()) 4030 return false; 4031 4032 MatchInfo = [=](MachineIRBuilder &B) { 4033 auto Cst1 = B.buildConstant(ExtractTy, ShiftImm); 4034 auto Cst2 = B.buildConstant(ExtractTy, Width); 4035 B.buildSbfx(Dst, ShiftSrc, Cst1, Cst2); 4036 }; 4037 return true; 4038 } 4039 4040 /// Form a G_UBFX from "(a srl b) & mask", where b and mask are constants. 4041 bool CombinerHelper::matchBitfieldExtractFromAnd( 4042 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 4043 assert(MI.getOpcode() == TargetOpcode::G_AND); 4044 Register Dst = MI.getOperand(0).getReg(); 4045 LLT Ty = MRI.getType(Dst); 4046 if (!getTargetLowering().isConstantUnsignedBitfieldExtactLegal( 4047 TargetOpcode::G_UBFX, Ty, Ty)) 4048 return false; 4049 4050 int64_t AndImm, LSBImm; 4051 Register ShiftSrc; 4052 const unsigned Size = Ty.getScalarSizeInBits(); 4053 if (!mi_match(MI.getOperand(0).getReg(), MRI, 4054 m_GAnd(m_OneNonDBGUse(m_GLShr(m_Reg(ShiftSrc), m_ICst(LSBImm))), 4055 m_ICst(AndImm)))) 4056 return false; 4057 4058 // The mask is a mask of the low bits iff imm & (imm+1) == 0. 4059 auto MaybeMask = static_cast<uint64_t>(AndImm); 4060 if (MaybeMask & (MaybeMask + 1)) 4061 return false; 4062 4063 // LSB must fit within the register. 4064 if (static_cast<uint64_t>(LSBImm) >= Size) 4065 return false; 4066 4067 LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty); 4068 uint64_t Width = APInt(Size, AndImm).countTrailingOnes(); 4069 MatchInfo = [=](MachineIRBuilder &B) { 4070 auto WidthCst = B.buildConstant(ExtractTy, Width); 4071 auto LSBCst = B.buildConstant(ExtractTy, LSBImm); 4072 B.buildInstr(TargetOpcode::G_UBFX, {Dst}, {ShiftSrc, LSBCst, WidthCst}); 4073 }; 4074 return true; 4075 } 4076 4077 bool CombinerHelper::matchBitfieldExtractFromShr( 4078 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 4079 const unsigned Opcode = MI.getOpcode(); 4080 assert(Opcode == TargetOpcode::G_ASHR || Opcode == TargetOpcode::G_LSHR); 4081 4082 const Register Dst = MI.getOperand(0).getReg(); 4083 4084 const unsigned ExtrOpcode = Opcode == TargetOpcode::G_ASHR 4085 ? TargetOpcode::G_SBFX 4086 : TargetOpcode::G_UBFX; 4087 4088 // Check if the type we would use for the extract is legal 4089 LLT Ty = MRI.getType(Dst); 4090 LLT ExtractTy = getTargetLowering().getPreferredShiftAmountTy(Ty); 4091 if (!LI || !LI->isLegalOrCustom({ExtrOpcode, {Ty, ExtractTy}})) 4092 return false; 4093 4094 Register ShlSrc; 4095 int64_t ShrAmt; 4096 int64_t ShlAmt; 4097 const unsigned Size = Ty.getScalarSizeInBits(); 4098 4099 // Try to match shr (shl x, c1), c2 4100 if (!mi_match(Dst, MRI, 4101 m_BinOp(Opcode, 4102 m_OneNonDBGUse(m_GShl(m_Reg(ShlSrc), m_ICst(ShlAmt))), 4103 m_ICst(ShrAmt)))) 4104 return false; 4105 4106 // Make sure that the shift sizes can fit a bitfield extract 4107 if (ShlAmt < 0 || ShlAmt > ShrAmt || ShrAmt >= Size) 4108 return false; 4109 4110 // Skip this combine if the G_SEXT_INREG combine could handle it 4111 if (Opcode == TargetOpcode::G_ASHR && ShlAmt == ShrAmt) 4112 return false; 4113 4114 // Calculate start position and width of the extract 4115 const int64_t Pos = ShrAmt - ShlAmt; 4116 const int64_t Width = Size - ShrAmt; 4117 4118 MatchInfo = [=](MachineIRBuilder &B) { 4119 auto WidthCst = B.buildConstant(ExtractTy, Width); 4120 auto PosCst = B.buildConstant(ExtractTy, Pos); 4121 B.buildInstr(ExtrOpcode, {Dst}, {ShlSrc, PosCst, WidthCst}); 4122 }; 4123 return true; 4124 } 4125 4126 bool CombinerHelper::reassociationCanBreakAddressingModePattern( 4127 MachineInstr &PtrAdd) { 4128 assert(PtrAdd.getOpcode() == TargetOpcode::G_PTR_ADD); 4129 4130 Register Src1Reg = PtrAdd.getOperand(1).getReg(); 4131 MachineInstr *Src1Def = getOpcodeDef(TargetOpcode::G_PTR_ADD, Src1Reg, MRI); 4132 if (!Src1Def) 4133 return false; 4134 4135 Register Src2Reg = PtrAdd.getOperand(2).getReg(); 4136 4137 if (MRI.hasOneNonDBGUse(Src1Reg)) 4138 return false; 4139 4140 auto C1 = getIConstantVRegVal(Src1Def->getOperand(2).getReg(), MRI); 4141 if (!C1) 4142 return false; 4143 auto C2 = getIConstantVRegVal(Src2Reg, MRI); 4144 if (!C2) 4145 return false; 4146 4147 const APInt &C1APIntVal = *C1; 4148 const APInt &C2APIntVal = *C2; 4149 const int64_t CombinedValue = (C1APIntVal + C2APIntVal).getSExtValue(); 4150 4151 for (auto &UseMI : MRI.use_nodbg_instructions(Src1Reg)) { 4152 // This combine may end up running before ptrtoint/inttoptr combines 4153 // manage to eliminate redundant conversions, so try to look through them. 4154 MachineInstr *ConvUseMI = &UseMI; 4155 unsigned ConvUseOpc = ConvUseMI->getOpcode(); 4156 while (ConvUseOpc == TargetOpcode::G_INTTOPTR || 4157 ConvUseOpc == TargetOpcode::G_PTRTOINT) { 4158 Register DefReg = ConvUseMI->getOperand(0).getReg(); 4159 if (!MRI.hasOneNonDBGUse(DefReg)) 4160 break; 4161 ConvUseMI = &*MRI.use_instr_nodbg_begin(DefReg); 4162 ConvUseOpc = ConvUseMI->getOpcode(); 4163 } 4164 auto LoadStore = ConvUseOpc == TargetOpcode::G_LOAD || 4165 ConvUseOpc == TargetOpcode::G_STORE; 4166 if (!LoadStore) 4167 continue; 4168 // Is x[offset2] already not a legal addressing mode? If so then 4169 // reassociating the constants breaks nothing (we test offset2 because 4170 // that's the one we hope to fold into the load or store). 4171 TargetLoweringBase::AddrMode AM; 4172 AM.HasBaseReg = true; 4173 AM.BaseOffs = C2APIntVal.getSExtValue(); 4174 unsigned AS = 4175 MRI.getType(ConvUseMI->getOperand(1).getReg()).getAddressSpace(); 4176 Type *AccessTy = 4177 getTypeForLLT(MRI.getType(ConvUseMI->getOperand(0).getReg()), 4178 PtrAdd.getMF()->getFunction().getContext()); 4179 const auto &TLI = *PtrAdd.getMF()->getSubtarget().getTargetLowering(); 4180 if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM, 4181 AccessTy, AS)) 4182 continue; 4183 4184 // Would x[offset1+offset2] still be a legal addressing mode? 4185 AM.BaseOffs = CombinedValue; 4186 if (!TLI.isLegalAddressingMode(PtrAdd.getMF()->getDataLayout(), AM, 4187 AccessTy, AS)) 4188 return true; 4189 } 4190 4191 return false; 4192 } 4193 4194 bool CombinerHelper::matchReassocConstantInnerRHS(GPtrAdd &MI, 4195 MachineInstr *RHS, 4196 BuildFnTy &MatchInfo) { 4197 // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C) 4198 Register Src1Reg = MI.getOperand(1).getReg(); 4199 if (RHS->getOpcode() != TargetOpcode::G_ADD) 4200 return false; 4201 auto C2 = getIConstantVRegVal(RHS->getOperand(2).getReg(), MRI); 4202 if (!C2) 4203 return false; 4204 4205 MatchInfo = [=, &MI](MachineIRBuilder &B) { 4206 LLT PtrTy = MRI.getType(MI.getOperand(0).getReg()); 4207 4208 auto NewBase = 4209 Builder.buildPtrAdd(PtrTy, Src1Reg, RHS->getOperand(1).getReg()); 4210 Observer.changingInstr(MI); 4211 MI.getOperand(1).setReg(NewBase.getReg(0)); 4212 MI.getOperand(2).setReg(RHS->getOperand(2).getReg()); 4213 Observer.changedInstr(MI); 4214 }; 4215 return !reassociationCanBreakAddressingModePattern(MI); 4216 } 4217 4218 bool CombinerHelper::matchReassocConstantInnerLHS(GPtrAdd &MI, 4219 MachineInstr *LHS, 4220 MachineInstr *RHS, 4221 BuildFnTy &MatchInfo) { 4222 // G_PTR_ADD (G_PTR_ADD X, C), Y) -> (G_PTR_ADD (G_PTR_ADD(X, Y), C) 4223 // if and only if (G_PTR_ADD X, C) has one use. 4224 Register LHSBase; 4225 Optional<ValueAndVReg> LHSCstOff; 4226 if (!mi_match(MI.getBaseReg(), MRI, 4227 m_OneNonDBGUse(m_GPtrAdd(m_Reg(LHSBase), m_GCst(LHSCstOff))))) 4228 return false; 4229 4230 auto *LHSPtrAdd = cast<GPtrAdd>(LHS); 4231 MatchInfo = [=, &MI](MachineIRBuilder &B) { 4232 // When we change LHSPtrAdd's offset register we might cause it to use a reg 4233 // before its def. Sink the instruction so the outer PTR_ADD to ensure this 4234 // doesn't happen. 4235 LHSPtrAdd->moveBefore(&MI); 4236 Register RHSReg = MI.getOffsetReg(); 4237 Observer.changingInstr(MI); 4238 MI.getOperand(2).setReg(LHSCstOff->VReg); 4239 Observer.changedInstr(MI); 4240 Observer.changingInstr(*LHSPtrAdd); 4241 LHSPtrAdd->getOperand(2).setReg(RHSReg); 4242 Observer.changedInstr(*LHSPtrAdd); 4243 }; 4244 return !reassociationCanBreakAddressingModePattern(MI); 4245 } 4246 4247 bool CombinerHelper::matchReassocFoldConstantsInSubTree(GPtrAdd &MI, 4248 MachineInstr *LHS, 4249 MachineInstr *RHS, 4250 BuildFnTy &MatchInfo) { 4251 // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2) 4252 auto *LHSPtrAdd = dyn_cast<GPtrAdd>(LHS); 4253 if (!LHSPtrAdd) 4254 return false; 4255 4256 Register Src2Reg = MI.getOperand(2).getReg(); 4257 Register LHSSrc1 = LHSPtrAdd->getBaseReg(); 4258 Register LHSSrc2 = LHSPtrAdd->getOffsetReg(); 4259 auto C1 = getIConstantVRegVal(LHSSrc2, MRI); 4260 if (!C1) 4261 return false; 4262 auto C2 = getIConstantVRegVal(Src2Reg, MRI); 4263 if (!C2) 4264 return false; 4265 4266 MatchInfo = [=, &MI](MachineIRBuilder &B) { 4267 auto NewCst = B.buildConstant(MRI.getType(Src2Reg), *C1 + *C2); 4268 Observer.changingInstr(MI); 4269 MI.getOperand(1).setReg(LHSSrc1); 4270 MI.getOperand(2).setReg(NewCst.getReg(0)); 4271 Observer.changedInstr(MI); 4272 }; 4273 return !reassociationCanBreakAddressingModePattern(MI); 4274 } 4275 4276 bool CombinerHelper::matchReassocPtrAdd(MachineInstr &MI, 4277 BuildFnTy &MatchInfo) { 4278 auto &PtrAdd = cast<GPtrAdd>(MI); 4279 // We're trying to match a few pointer computation patterns here for 4280 // re-association opportunities. 4281 // 1) Isolating a constant operand to be on the RHS, e.g.: 4282 // G_PTR_ADD(BASE, G_ADD(X, C)) -> G_PTR_ADD(G_PTR_ADD(BASE, X), C) 4283 // 4284 // 2) Folding two constants in each sub-tree as long as such folding 4285 // doesn't break a legal addressing mode. 4286 // G_PTR_ADD(G_PTR_ADD(BASE, C1), C2) -> G_PTR_ADD(BASE, C1+C2) 4287 // 4288 // 3) Move a constant from the LHS of an inner op to the RHS of the outer. 4289 // G_PTR_ADD (G_PTR_ADD X, C), Y) -> G_PTR_ADD (G_PTR_ADD(X, Y), C) 4290 // iif (G_PTR_ADD X, C) has one use. 4291 MachineInstr *LHS = MRI.getVRegDef(PtrAdd.getBaseReg()); 4292 MachineInstr *RHS = MRI.getVRegDef(PtrAdd.getOffsetReg()); 4293 4294 // Try to match example 2. 4295 if (matchReassocFoldConstantsInSubTree(PtrAdd, LHS, RHS, MatchInfo)) 4296 return true; 4297 4298 // Try to match example 3. 4299 if (matchReassocConstantInnerLHS(PtrAdd, LHS, RHS, MatchInfo)) 4300 return true; 4301 4302 // Try to match example 1. 4303 if (matchReassocConstantInnerRHS(PtrAdd, RHS, MatchInfo)) 4304 return true; 4305 4306 return false; 4307 } 4308 4309 bool CombinerHelper::matchConstantFold(MachineInstr &MI, APInt &MatchInfo) { 4310 Register Op1 = MI.getOperand(1).getReg(); 4311 Register Op2 = MI.getOperand(2).getReg(); 4312 auto MaybeCst = ConstantFoldBinOp(MI.getOpcode(), Op1, Op2, MRI); 4313 if (!MaybeCst) 4314 return false; 4315 MatchInfo = *MaybeCst; 4316 return true; 4317 } 4318 4319 bool CombinerHelper::matchNarrowBinopFeedingAnd( 4320 MachineInstr &MI, std::function<void(MachineIRBuilder &)> &MatchInfo) { 4321 // Look for a binop feeding into an AND with a mask: 4322 // 4323 // %add = G_ADD %lhs, %rhs 4324 // %and = G_AND %add, 000...11111111 4325 // 4326 // Check if it's possible to perform the binop at a narrower width and zext 4327 // back to the original width like so: 4328 // 4329 // %narrow_lhs = G_TRUNC %lhs 4330 // %narrow_rhs = G_TRUNC %rhs 4331 // %narrow_add = G_ADD %narrow_lhs, %narrow_rhs 4332 // %new_add = G_ZEXT %narrow_add 4333 // %and = G_AND %new_add, 000...11111111 4334 // 4335 // This can allow later combines to eliminate the G_AND if it turns out 4336 // that the mask is irrelevant. 4337 assert(MI.getOpcode() == TargetOpcode::G_AND); 4338 Register Dst = MI.getOperand(0).getReg(); 4339 Register AndLHS = MI.getOperand(1).getReg(); 4340 Register AndRHS = MI.getOperand(2).getReg(); 4341 LLT WideTy = MRI.getType(Dst); 4342 4343 // If the potential binop has more than one use, then it's possible that one 4344 // of those uses will need its full width. 4345 if (!WideTy.isScalar() || !MRI.hasOneNonDBGUse(AndLHS)) 4346 return false; 4347 4348 // Check if the LHS feeding the AND is impacted by the high bits that we're 4349 // masking out. 4350 // 4351 // e.g. for 64-bit x, y: 4352 // 4353 // add_64(x, y) & 65535 == zext(add_16(trunc(x), trunc(y))) & 65535 4354 MachineInstr *LHSInst = getDefIgnoringCopies(AndLHS, MRI); 4355 if (!LHSInst) 4356 return false; 4357 unsigned LHSOpc = LHSInst->getOpcode(); 4358 switch (LHSOpc) { 4359 default: 4360 return false; 4361 case TargetOpcode::G_ADD: 4362 case TargetOpcode::G_SUB: 4363 case TargetOpcode::G_MUL: 4364 case TargetOpcode::G_AND: 4365 case TargetOpcode::G_OR: 4366 case TargetOpcode::G_XOR: 4367 break; 4368 } 4369 4370 // Find the mask on the RHS. 4371 auto Cst = getIConstantVRegValWithLookThrough(AndRHS, MRI); 4372 if (!Cst) 4373 return false; 4374 auto Mask = Cst->Value; 4375 if (!Mask.isMask()) 4376 return false; 4377 4378 // No point in combining if there's nothing to truncate. 4379 unsigned NarrowWidth = Mask.countTrailingOnes(); 4380 if (NarrowWidth == WideTy.getSizeInBits()) 4381 return false; 4382 LLT NarrowTy = LLT::scalar(NarrowWidth); 4383 4384 // Check if adding the zext + truncates could be harmful. 4385 auto &MF = *MI.getMF(); 4386 const auto &TLI = getTargetLowering(); 4387 LLVMContext &Ctx = MF.getFunction().getContext(); 4388 auto &DL = MF.getDataLayout(); 4389 if (!TLI.isTruncateFree(WideTy, NarrowTy, DL, Ctx) || 4390 !TLI.isZExtFree(NarrowTy, WideTy, DL, Ctx)) 4391 return false; 4392 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_TRUNC, {NarrowTy, WideTy}}) || 4393 !isLegalOrBeforeLegalizer({TargetOpcode::G_ZEXT, {WideTy, NarrowTy}})) 4394 return false; 4395 Register BinOpLHS = LHSInst->getOperand(1).getReg(); 4396 Register BinOpRHS = LHSInst->getOperand(2).getReg(); 4397 MatchInfo = [=, &MI](MachineIRBuilder &B) { 4398 auto NarrowLHS = Builder.buildTrunc(NarrowTy, BinOpLHS); 4399 auto NarrowRHS = Builder.buildTrunc(NarrowTy, BinOpRHS); 4400 auto NarrowBinOp = 4401 Builder.buildInstr(LHSOpc, {NarrowTy}, {NarrowLHS, NarrowRHS}); 4402 auto Ext = Builder.buildZExt(WideTy, NarrowBinOp); 4403 Observer.changingInstr(MI); 4404 MI.getOperand(1).setReg(Ext.getReg(0)); 4405 Observer.changedInstr(MI); 4406 }; 4407 return true; 4408 } 4409 4410 bool CombinerHelper::matchMulOBy2(MachineInstr &MI, BuildFnTy &MatchInfo) { 4411 unsigned Opc = MI.getOpcode(); 4412 assert(Opc == TargetOpcode::G_UMULO || Opc == TargetOpcode::G_SMULO); 4413 // Check for a constant 2 or a splat of 2 on the RHS. 4414 auto RHS = MI.getOperand(3).getReg(); 4415 bool IsVector = MRI.getType(RHS).isVector(); 4416 if (!IsVector && !mi_match(MI.getOperand(3).getReg(), MRI, m_SpecificICst(2))) 4417 return false; 4418 if (IsVector) { 4419 // FIXME: There's no mi_match pattern for this yet. 4420 auto *RHSDef = getDefIgnoringCopies(RHS, MRI); 4421 if (!RHSDef) 4422 return false; 4423 auto Splat = getBuildVectorConstantSplat(*RHSDef, MRI); 4424 if (!Splat || *Splat != 2) 4425 return false; 4426 } 4427 4428 MatchInfo = [=, &MI](MachineIRBuilder &B) { 4429 Observer.changingInstr(MI); 4430 unsigned NewOpc = Opc == TargetOpcode::G_UMULO ? TargetOpcode::G_UADDO 4431 : TargetOpcode::G_SADDO; 4432 MI.setDesc(Builder.getTII().get(NewOpc)); 4433 MI.getOperand(3).setReg(MI.getOperand(2).getReg()); 4434 Observer.changedInstr(MI); 4435 }; 4436 return true; 4437 } 4438 4439 MachineInstr *CombinerHelper::buildUDivUsingMul(MachineInstr &MI) { 4440 assert(MI.getOpcode() == TargetOpcode::G_UDIV); 4441 auto &UDiv = cast<GenericMachineInstr>(MI); 4442 Register Dst = UDiv.getReg(0); 4443 Register LHS = UDiv.getReg(1); 4444 Register RHS = UDiv.getReg(2); 4445 LLT Ty = MRI.getType(Dst); 4446 LLT ScalarTy = Ty.getScalarType(); 4447 const unsigned EltBits = ScalarTy.getScalarSizeInBits(); 4448 LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty); 4449 LLT ScalarShiftAmtTy = ShiftAmtTy.getScalarType(); 4450 auto &MIB = Builder; 4451 MIB.setInstrAndDebugLoc(MI); 4452 4453 bool UseNPQ = false; 4454 SmallVector<Register, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 4455 4456 auto BuildUDIVPattern = [&](const Constant *C) { 4457 auto *CI = cast<ConstantInt>(C); 4458 const APInt &Divisor = CI->getValue(); 4459 UnsignedDivisonByConstantInfo magics = 4460 UnsignedDivisonByConstantInfo::get(Divisor); 4461 unsigned PreShift = 0, PostShift = 0; 4462 4463 // If the divisor is even, we can avoid using the expensive fixup by 4464 // shifting the divided value upfront. 4465 if (magics.IsAdd != 0 && !Divisor[0]) { 4466 PreShift = Divisor.countTrailingZeros(); 4467 // Get magic number for the shifted divisor. 4468 magics = 4469 UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift); 4470 assert(magics.IsAdd == 0 && "Should use cheap fixup now"); 4471 } 4472 4473 APInt Magic = magics.Magic; 4474 4475 unsigned SelNPQ; 4476 if (magics.IsAdd == 0 || Divisor.isOneValue()) { 4477 assert(magics.ShiftAmount < Divisor.getBitWidth() && 4478 "We shouldn't generate an undefined shift!"); 4479 PostShift = magics.ShiftAmount; 4480 SelNPQ = false; 4481 } else { 4482 PostShift = magics.ShiftAmount - 1; 4483 SelNPQ = true; 4484 } 4485 4486 PreShifts.push_back( 4487 MIB.buildConstant(ScalarShiftAmtTy, PreShift).getReg(0)); 4488 MagicFactors.push_back(MIB.buildConstant(ScalarTy, Magic).getReg(0)); 4489 NPQFactors.push_back( 4490 MIB.buildConstant(ScalarTy, 4491 SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 4492 : APInt::getZero(EltBits)) 4493 .getReg(0)); 4494 PostShifts.push_back( 4495 MIB.buildConstant(ScalarShiftAmtTy, PostShift).getReg(0)); 4496 UseNPQ |= SelNPQ; 4497 return true; 4498 }; 4499 4500 // Collect the shifts/magic values from each element. 4501 bool Matched = matchUnaryPredicate(MRI, RHS, BuildUDIVPattern); 4502 (void)Matched; 4503 assert(Matched && "Expected unary predicate match to succeed"); 4504 4505 Register PreShift, PostShift, MagicFactor, NPQFactor; 4506 auto *RHSDef = getOpcodeDef<GBuildVector>(RHS, MRI); 4507 if (RHSDef) { 4508 PreShift = MIB.buildBuildVector(ShiftAmtTy, PreShifts).getReg(0); 4509 MagicFactor = MIB.buildBuildVector(Ty, MagicFactors).getReg(0); 4510 NPQFactor = MIB.buildBuildVector(Ty, NPQFactors).getReg(0); 4511 PostShift = MIB.buildBuildVector(ShiftAmtTy, PostShifts).getReg(0); 4512 } else { 4513 assert(MRI.getType(RHS).isScalar() && 4514 "Non-build_vector operation should have been a scalar"); 4515 PreShift = PreShifts[0]; 4516 MagicFactor = MagicFactors[0]; 4517 PostShift = PostShifts[0]; 4518 } 4519 4520 Register Q = LHS; 4521 Q = MIB.buildLShr(Ty, Q, PreShift).getReg(0); 4522 4523 // Multiply the numerator (operand 0) by the magic value. 4524 Q = MIB.buildUMulH(Ty, Q, MagicFactor).getReg(0); 4525 4526 if (UseNPQ) { 4527 Register NPQ = MIB.buildSub(Ty, LHS, Q).getReg(0); 4528 4529 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 4530 // G_UMULH to act as a SRL-by-1 for NPQ, else multiply by zero. 4531 if (Ty.isVector()) 4532 NPQ = MIB.buildUMulH(Ty, NPQ, NPQFactor).getReg(0); 4533 else 4534 NPQ = MIB.buildLShr(Ty, NPQ, MIB.buildConstant(ShiftAmtTy, 1)).getReg(0); 4535 4536 Q = MIB.buildAdd(Ty, NPQ, Q).getReg(0); 4537 } 4538 4539 Q = MIB.buildLShr(Ty, Q, PostShift).getReg(0); 4540 auto One = MIB.buildConstant(Ty, 1); 4541 auto IsOne = MIB.buildICmp( 4542 CmpInst::Predicate::ICMP_EQ, 4543 Ty.isScalar() ? LLT::scalar(1) : Ty.changeElementSize(1), RHS, One); 4544 return MIB.buildSelect(Ty, IsOne, LHS, Q); 4545 } 4546 4547 bool CombinerHelper::matchUDivByConst(MachineInstr &MI) { 4548 assert(MI.getOpcode() == TargetOpcode::G_UDIV); 4549 Register Dst = MI.getOperand(0).getReg(); 4550 Register RHS = MI.getOperand(2).getReg(); 4551 LLT DstTy = MRI.getType(Dst); 4552 auto *RHSDef = MRI.getVRegDef(RHS); 4553 if (!isConstantOrConstantVector(*RHSDef, MRI)) 4554 return false; 4555 4556 auto &MF = *MI.getMF(); 4557 AttributeList Attr = MF.getFunction().getAttributes(); 4558 const auto &TLI = getTargetLowering(); 4559 LLVMContext &Ctx = MF.getFunction().getContext(); 4560 auto &DL = MF.getDataLayout(); 4561 if (TLI.isIntDivCheap(getApproximateEVTForLLT(DstTy, DL, Ctx), Attr)) 4562 return false; 4563 4564 // Don't do this for minsize because the instruction sequence is usually 4565 // larger. 4566 if (MF.getFunction().hasMinSize()) 4567 return false; 4568 4569 // Don't do this if the types are not going to be legal. 4570 if (LI) { 4571 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_MUL, {DstTy, DstTy}})) 4572 return false; 4573 if (!isLegalOrBeforeLegalizer({TargetOpcode::G_UMULH, {DstTy}})) 4574 return false; 4575 if (!isLegalOrBeforeLegalizer( 4576 {TargetOpcode::G_ICMP, 4577 {DstTy.isVector() ? DstTy.changeElementSize(1) : LLT::scalar(1), 4578 DstTy}})) 4579 return false; 4580 } 4581 4582 auto CheckEltValue = [&](const Constant *C) { 4583 if (auto *CI = dyn_cast_or_null<ConstantInt>(C)) 4584 return !CI->isZero(); 4585 return false; 4586 }; 4587 return matchUnaryPredicate(MRI, RHS, CheckEltValue); 4588 } 4589 4590 void CombinerHelper::applyUDivByConst(MachineInstr &MI) { 4591 auto *NewMI = buildUDivUsingMul(MI); 4592 replaceSingleDefInstWithReg(MI, NewMI->getOperand(0).getReg()); 4593 } 4594 4595 bool CombinerHelper::matchUMulHToLShr(MachineInstr &MI) { 4596 assert(MI.getOpcode() == TargetOpcode::G_UMULH); 4597 Register RHS = MI.getOperand(2).getReg(); 4598 Register Dst = MI.getOperand(0).getReg(); 4599 LLT Ty = MRI.getType(Dst); 4600 LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty); 4601 auto MatchPow2ExceptOne = [&](const Constant *C) { 4602 if (auto *CI = dyn_cast<ConstantInt>(C)) 4603 return CI->getValue().isPowerOf2() && !CI->getValue().isOne(); 4604 return false; 4605 }; 4606 if (!matchUnaryPredicate(MRI, RHS, MatchPow2ExceptOne, false)) 4607 return false; 4608 return isLegalOrBeforeLegalizer({TargetOpcode::G_LSHR, {Ty, ShiftAmtTy}}); 4609 } 4610 4611 void CombinerHelper::applyUMulHToLShr(MachineInstr &MI) { 4612 Register LHS = MI.getOperand(1).getReg(); 4613 Register RHS = MI.getOperand(2).getReg(); 4614 Register Dst = MI.getOperand(0).getReg(); 4615 LLT Ty = MRI.getType(Dst); 4616 LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty); 4617 unsigned NumEltBits = Ty.getScalarSizeInBits(); 4618 4619 Builder.setInstrAndDebugLoc(MI); 4620 auto LogBase2 = buildLogBase2(RHS, Builder); 4621 auto ShiftAmt = 4622 Builder.buildSub(Ty, Builder.buildConstant(Ty, NumEltBits), LogBase2); 4623 auto Trunc = Builder.buildZExtOrTrunc(ShiftAmtTy, ShiftAmt); 4624 Builder.buildLShr(Dst, LHS, Trunc); 4625 MI.eraseFromParent(); 4626 } 4627 4628 bool CombinerHelper::matchRedundantNegOperands(MachineInstr &MI, 4629 BuildFnTy &MatchInfo) { 4630 unsigned Opc = MI.getOpcode(); 4631 assert(Opc == TargetOpcode::G_FADD || Opc == TargetOpcode::G_FSUB || 4632 Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV || 4633 Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA); 4634 4635 Register Dst = MI.getOperand(0).getReg(); 4636 Register X = MI.getOperand(1).getReg(); 4637 Register Y = MI.getOperand(2).getReg(); 4638 LLT Type = MRI.getType(Dst); 4639 4640 // fold (fadd x, fneg(y)) -> (fsub x, y) 4641 // fold (fadd fneg(y), x) -> (fsub x, y) 4642 // G_ADD is commutative so both cases are checked by m_GFAdd 4643 if (mi_match(Dst, MRI, m_GFAdd(m_Reg(X), m_GFNeg(m_Reg(Y)))) && 4644 isLegalOrBeforeLegalizer({TargetOpcode::G_FSUB, {Type}})) { 4645 Opc = TargetOpcode::G_FSUB; 4646 } 4647 /// fold (fsub x, fneg(y)) -> (fadd x, y) 4648 else if (mi_match(Dst, MRI, m_GFSub(m_Reg(X), m_GFNeg(m_Reg(Y)))) && 4649 isLegalOrBeforeLegalizer({TargetOpcode::G_FADD, {Type}})) { 4650 Opc = TargetOpcode::G_FADD; 4651 } 4652 // fold (fmul fneg(x), fneg(y)) -> (fmul x, y) 4653 // fold (fdiv fneg(x), fneg(y)) -> (fdiv x, y) 4654 // fold (fmad fneg(x), fneg(y), z) -> (fmad x, y, z) 4655 // fold (fma fneg(x), fneg(y), z) -> (fma x, y, z) 4656 else if ((Opc == TargetOpcode::G_FMUL || Opc == TargetOpcode::G_FDIV || 4657 Opc == TargetOpcode::G_FMAD || Opc == TargetOpcode::G_FMA) && 4658 mi_match(X, MRI, m_GFNeg(m_Reg(X))) && 4659 mi_match(Y, MRI, m_GFNeg(m_Reg(Y)))) { 4660 // no opcode change 4661 } else 4662 return false; 4663 4664 MatchInfo = [=, &MI](MachineIRBuilder &B) { 4665 Observer.changingInstr(MI); 4666 MI.setDesc(B.getTII().get(Opc)); 4667 MI.getOperand(1).setReg(X); 4668 MI.getOperand(2).setReg(Y); 4669 Observer.changedInstr(MI); 4670 }; 4671 return true; 4672 } 4673 4674 bool CombinerHelper::tryCombine(MachineInstr &MI) { 4675 if (tryCombineCopy(MI)) 4676 return true; 4677 if (tryCombineExtendingLoads(MI)) 4678 return true; 4679 if (tryCombineIndexedLoadStore(MI)) 4680 return true; 4681 return false; 4682 } 4683