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/CodeGen/GlobalISel/Combiner.h" 10 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" 11 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 12 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" 13 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 14 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h" 15 #include "llvm/CodeGen/GlobalISel/Utils.h" 16 #include "llvm/CodeGen/MachineDominators.h" 17 #include "llvm/CodeGen/MachineFrameInfo.h" 18 #include "llvm/CodeGen/MachineInstr.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/TargetInstrInfo.h" 21 #include "llvm/CodeGen/TargetLowering.h" 22 #include "llvm/Support/MathExtras.h" 23 #include "llvm/Target/TargetMachine.h" 24 25 #define DEBUG_TYPE "gi-combiner" 26 27 using namespace llvm; 28 using namespace MIPatternMatch; 29 30 // Option to allow testing of the combiner while no targets know about indexed 31 // addressing. 32 static cl::opt<bool> 33 ForceLegalIndexing("force-legal-indexing", cl::Hidden, cl::init(false), 34 cl::desc("Force all indexed operations to be " 35 "legal for the GlobalISel combiner")); 36 37 38 CombinerHelper::CombinerHelper(GISelChangeObserver &Observer, 39 MachineIRBuilder &B, GISelKnownBits *KB, 40 MachineDominatorTree *MDT, 41 const LegalizerInfo *LI) 42 : Builder(B), MRI(Builder.getMF().getRegInfo()), Observer(Observer), 43 KB(KB), MDT(MDT), LI(LI) { 44 (void)this->KB; 45 } 46 47 void CombinerHelper::replaceRegWith(MachineRegisterInfo &MRI, Register FromReg, 48 Register ToReg) const { 49 Observer.changingAllUsesOfReg(MRI, FromReg); 50 51 if (MRI.constrainRegAttrs(ToReg, FromReg)) 52 MRI.replaceRegWith(FromReg, ToReg); 53 else 54 Builder.buildCopy(ToReg, FromReg); 55 56 Observer.finishedChangingAllUsesOfReg(); 57 } 58 59 void CombinerHelper::replaceRegOpWith(MachineRegisterInfo &MRI, 60 MachineOperand &FromRegOp, 61 Register ToReg) const { 62 assert(FromRegOp.getParent() && "Expected an operand in an MI"); 63 Observer.changingInstr(*FromRegOp.getParent()); 64 65 FromRegOp.setReg(ToReg); 66 67 Observer.changedInstr(*FromRegOp.getParent()); 68 } 69 70 bool CombinerHelper::tryCombineCopy(MachineInstr &MI) { 71 if (matchCombineCopy(MI)) { 72 applyCombineCopy(MI); 73 return true; 74 } 75 return false; 76 } 77 bool CombinerHelper::matchCombineCopy(MachineInstr &MI) { 78 if (MI.getOpcode() != TargetOpcode::COPY) 79 return false; 80 Register DstReg = MI.getOperand(0).getReg(); 81 Register SrcReg = MI.getOperand(1).getReg(); 82 return canReplaceReg(DstReg, SrcReg, MRI); 83 } 84 void CombinerHelper::applyCombineCopy(MachineInstr &MI) { 85 Register DstReg = MI.getOperand(0).getReg(); 86 Register SrcReg = MI.getOperand(1).getReg(); 87 MI.eraseFromParent(); 88 replaceRegWith(MRI, DstReg, SrcReg); 89 } 90 91 bool CombinerHelper::tryCombineConcatVectors(MachineInstr &MI) { 92 bool IsUndef = false; 93 SmallVector<Register, 4> Ops; 94 if (matchCombineConcatVectors(MI, IsUndef, Ops)) { 95 applyCombineConcatVectors(MI, IsUndef, Ops); 96 return true; 97 } 98 return false; 99 } 100 101 bool CombinerHelper::matchCombineConcatVectors(MachineInstr &MI, bool &IsUndef, 102 SmallVectorImpl<Register> &Ops) { 103 assert(MI.getOpcode() == TargetOpcode::G_CONCAT_VECTORS && 104 "Invalid instruction"); 105 IsUndef = true; 106 MachineInstr *Undef = nullptr; 107 108 // Walk over all the operands of concat vectors and check if they are 109 // build_vector themselves or undef. 110 // Then collect their operands in Ops. 111 for (const MachineOperand &MO : MI.uses()) { 112 Register Reg = MO.getReg(); 113 MachineInstr *Def = MRI.getVRegDef(Reg); 114 assert(Def && "Operand not defined"); 115 switch (Def->getOpcode()) { 116 case TargetOpcode::G_BUILD_VECTOR: 117 IsUndef = false; 118 // Remember the operands of the build_vector to fold 119 // them into the yet-to-build flattened concat vectors. 120 for (const MachineOperand &BuildVecMO : Def->uses()) 121 Ops.push_back(BuildVecMO.getReg()); 122 break; 123 case TargetOpcode::G_IMPLICIT_DEF: { 124 LLT OpType = MRI.getType(Reg); 125 // Keep one undef value for all the undef operands. 126 if (!Undef) { 127 Builder.setInsertPt(*MI.getParent(), MI); 128 Undef = Builder.buildUndef(OpType.getScalarType()); 129 } 130 assert(MRI.getType(Undef->getOperand(0).getReg()) == 131 OpType.getScalarType() && 132 "All undefs should have the same type"); 133 // Break the undef vector in as many scalar elements as needed 134 // for the flattening. 135 for (unsigned EltIdx = 0, EltEnd = OpType.getNumElements(); 136 EltIdx != EltEnd; ++EltIdx) 137 Ops.push_back(Undef->getOperand(0).getReg()); 138 break; 139 } 140 default: 141 return false; 142 } 143 } 144 return true; 145 } 146 void CombinerHelper::applyCombineConcatVectors( 147 MachineInstr &MI, bool IsUndef, const ArrayRef<Register> Ops) { 148 // We determined that the concat_vectors can be flatten. 149 // Generate the flattened build_vector. 150 Register DstReg = MI.getOperand(0).getReg(); 151 Builder.setInsertPt(*MI.getParent(), MI); 152 Register NewDstReg = MRI.cloneVirtualRegister(DstReg); 153 154 // Note: IsUndef is sort of redundant. We could have determine it by 155 // checking that at all Ops are undef. Alternatively, we could have 156 // generate a build_vector of undefs and rely on another combine to 157 // clean that up. For now, given we already gather this information 158 // in tryCombineConcatVectors, just save compile time and issue the 159 // right thing. 160 if (IsUndef) 161 Builder.buildUndef(NewDstReg); 162 else 163 Builder.buildBuildVector(NewDstReg, Ops); 164 MI.eraseFromParent(); 165 replaceRegWith(MRI, DstReg, NewDstReg); 166 } 167 168 bool CombinerHelper::tryCombineShuffleVector(MachineInstr &MI) { 169 SmallVector<Register, 4> Ops; 170 if (matchCombineShuffleVector(MI, Ops)) { 171 applyCombineShuffleVector(MI, Ops); 172 return true; 173 } 174 return false; 175 } 176 177 bool CombinerHelper::matchCombineShuffleVector(MachineInstr &MI, 178 SmallVectorImpl<Register> &Ops) { 179 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR && 180 "Invalid instruction kind"); 181 LLT DstType = MRI.getType(MI.getOperand(0).getReg()); 182 Register Src1 = MI.getOperand(1).getReg(); 183 LLT SrcType = MRI.getType(Src1); 184 // As bizarre as it may look, shuffle vector can actually produce 185 // scalar! This is because at the IR level a <1 x ty> shuffle 186 // vector is perfectly valid. 187 unsigned DstNumElts = DstType.isVector() ? DstType.getNumElements() : 1; 188 unsigned SrcNumElts = SrcType.isVector() ? SrcType.getNumElements() : 1; 189 190 // If the resulting vector is smaller than the size of the source 191 // vectors being concatenated, we won't be able to replace the 192 // shuffle vector into a concat_vectors. 193 // 194 // Note: We may still be able to produce a concat_vectors fed by 195 // extract_vector_elt and so on. It is less clear that would 196 // be better though, so don't bother for now. 197 // 198 // If the destination is a scalar, the size of the sources doesn't 199 // matter. we will lower the shuffle to a plain copy. This will 200 // work only if the source and destination have the same size. But 201 // that's covered by the next condition. 202 // 203 // TODO: If the size between the source and destination don't match 204 // we could still emit an extract vector element in that case. 205 if (DstNumElts < 2 * SrcNumElts && DstNumElts != 1) 206 return false; 207 208 // Check that the shuffle mask can be broken evenly between the 209 // different sources. 210 if (DstNumElts % SrcNumElts != 0) 211 return false; 212 213 // Mask length is a multiple of the source vector length. 214 // Check if the shuffle is some kind of concatenation of the input 215 // vectors. 216 unsigned NumConcat = DstNumElts / SrcNumElts; 217 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 218 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask(); 219 for (unsigned i = 0; i != DstNumElts; ++i) { 220 int Idx = Mask[i]; 221 // Undef value. 222 if (Idx < 0) 223 continue; 224 // Ensure the indices in each SrcType sized piece are sequential and that 225 // the same source is used for the whole piece. 226 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 227 (ConcatSrcs[i / SrcNumElts] >= 0 && 228 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) 229 return false; 230 // Remember which source this index came from. 231 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 232 } 233 234 // The shuffle is concatenating multiple vectors together. 235 // Collect the different operands for that. 236 Register UndefReg; 237 Register Src2 = MI.getOperand(2).getReg(); 238 for (auto Src : ConcatSrcs) { 239 if (Src < 0) { 240 if (!UndefReg) { 241 Builder.setInsertPt(*MI.getParent(), MI); 242 UndefReg = Builder.buildUndef(SrcType).getReg(0); 243 } 244 Ops.push_back(UndefReg); 245 } else if (Src == 0) 246 Ops.push_back(Src1); 247 else 248 Ops.push_back(Src2); 249 } 250 return true; 251 } 252 253 void CombinerHelper::applyCombineShuffleVector(MachineInstr &MI, 254 const ArrayRef<Register> Ops) { 255 Register DstReg = MI.getOperand(0).getReg(); 256 Builder.setInsertPt(*MI.getParent(), MI); 257 Register NewDstReg = MRI.cloneVirtualRegister(DstReg); 258 259 if (Ops.size() == 1) 260 Builder.buildCopy(NewDstReg, Ops[0]); 261 else 262 Builder.buildMerge(NewDstReg, Ops); 263 264 MI.eraseFromParent(); 265 replaceRegWith(MRI, DstReg, NewDstReg); 266 } 267 268 namespace { 269 270 /// Select a preference between two uses. CurrentUse is the current preference 271 /// while *ForCandidate is attributes of the candidate under consideration. 272 PreferredTuple ChoosePreferredUse(PreferredTuple &CurrentUse, 273 const LLT TyForCandidate, 274 unsigned OpcodeForCandidate, 275 MachineInstr *MIForCandidate) { 276 if (!CurrentUse.Ty.isValid()) { 277 if (CurrentUse.ExtendOpcode == OpcodeForCandidate || 278 CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT) 279 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 280 return CurrentUse; 281 } 282 283 // We permit the extend to hoist through basic blocks but this is only 284 // sensible if the target has extending loads. If you end up lowering back 285 // into a load and extend during the legalizer then the end result is 286 // hoisting the extend up to the load. 287 288 // Prefer defined extensions to undefined extensions as these are more 289 // likely to reduce the number of instructions. 290 if (OpcodeForCandidate == TargetOpcode::G_ANYEXT && 291 CurrentUse.ExtendOpcode != TargetOpcode::G_ANYEXT) 292 return CurrentUse; 293 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ANYEXT && 294 OpcodeForCandidate != TargetOpcode::G_ANYEXT) 295 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 296 297 // Prefer sign extensions to zero extensions as sign-extensions tend to be 298 // more expensive. 299 if (CurrentUse.Ty == TyForCandidate) { 300 if (CurrentUse.ExtendOpcode == TargetOpcode::G_SEXT && 301 OpcodeForCandidate == TargetOpcode::G_ZEXT) 302 return CurrentUse; 303 else if (CurrentUse.ExtendOpcode == TargetOpcode::G_ZEXT && 304 OpcodeForCandidate == TargetOpcode::G_SEXT) 305 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 306 } 307 308 // This is potentially target specific. We've chosen the largest type 309 // because G_TRUNC is usually free. One potential catch with this is that 310 // some targets have a reduced number of larger registers than smaller 311 // registers and this choice potentially increases the live-range for the 312 // larger value. 313 if (TyForCandidate.getSizeInBits() > CurrentUse.Ty.getSizeInBits()) { 314 return {TyForCandidate, OpcodeForCandidate, MIForCandidate}; 315 } 316 return CurrentUse; 317 } 318 319 /// Find a suitable place to insert some instructions and insert them. This 320 /// function accounts for special cases like inserting before a PHI node. 321 /// The current strategy for inserting before PHI's is to duplicate the 322 /// instructions for each predecessor. However, while that's ok for G_TRUNC 323 /// on most targets since it generally requires no code, other targets/cases may 324 /// want to try harder to find a dominating block. 325 static void InsertInsnsWithoutSideEffectsBeforeUse( 326 MachineIRBuilder &Builder, MachineInstr &DefMI, MachineOperand &UseMO, 327 std::function<void(MachineBasicBlock *, MachineBasicBlock::iterator, 328 MachineOperand &UseMO)> 329 Inserter) { 330 MachineInstr &UseMI = *UseMO.getParent(); 331 332 MachineBasicBlock *InsertBB = UseMI.getParent(); 333 334 // If the use is a PHI then we want the predecessor block instead. 335 if (UseMI.isPHI()) { 336 MachineOperand *PredBB = std::next(&UseMO); 337 InsertBB = PredBB->getMBB(); 338 } 339 340 // If the block is the same block as the def then we want to insert just after 341 // the def instead of at the start of the block. 342 if (InsertBB == DefMI.getParent()) { 343 MachineBasicBlock::iterator InsertPt = &DefMI; 344 Inserter(InsertBB, std::next(InsertPt), UseMO); 345 return; 346 } 347 348 // Otherwise we want the start of the BB 349 Inserter(InsertBB, InsertBB->getFirstNonPHI(), UseMO); 350 } 351 } // end anonymous namespace 352 353 bool CombinerHelper::tryCombineExtendingLoads(MachineInstr &MI) { 354 PreferredTuple Preferred; 355 if (matchCombineExtendingLoads(MI, Preferred)) { 356 applyCombineExtendingLoads(MI, Preferred); 357 return true; 358 } 359 return false; 360 } 361 362 bool CombinerHelper::matchCombineExtendingLoads(MachineInstr &MI, 363 PreferredTuple &Preferred) { 364 // We match the loads and follow the uses to the extend instead of matching 365 // the extends and following the def to the load. This is because the load 366 // must remain in the same position for correctness (unless we also add code 367 // to find a safe place to sink it) whereas the extend is freely movable. 368 // It also prevents us from duplicating the load for the volatile case or just 369 // for performance. 370 371 if (MI.getOpcode() != TargetOpcode::G_LOAD && 372 MI.getOpcode() != TargetOpcode::G_SEXTLOAD && 373 MI.getOpcode() != TargetOpcode::G_ZEXTLOAD) 374 return false; 375 376 auto &LoadValue = MI.getOperand(0); 377 assert(LoadValue.isReg() && "Result wasn't a register?"); 378 379 LLT LoadValueTy = MRI.getType(LoadValue.getReg()); 380 if (!LoadValueTy.isScalar()) 381 return false; 382 383 // Most architectures are going to legalize <s8 loads into at least a 1 byte 384 // load, and the MMOs can only describe memory accesses in multiples of bytes. 385 // If we try to perform extload combining on those, we can end up with 386 // %a(s8) = extload %ptr (load 1 byte from %ptr) 387 // ... which is an illegal extload instruction. 388 if (LoadValueTy.getSizeInBits() < 8) 389 return false; 390 391 // For non power-of-2 types, they will very likely be legalized into multiple 392 // loads. Don't bother trying to match them into extending loads. 393 if (!isPowerOf2_32(LoadValueTy.getSizeInBits())) 394 return false; 395 396 // Find the preferred type aside from the any-extends (unless it's the only 397 // one) and non-extending ops. We'll emit an extending load to that type and 398 // and emit a variant of (extend (trunc X)) for the others according to the 399 // relative type sizes. At the same time, pick an extend to use based on the 400 // extend involved in the chosen type. 401 unsigned PreferredOpcode = MI.getOpcode() == TargetOpcode::G_LOAD 402 ? TargetOpcode::G_ANYEXT 403 : MI.getOpcode() == TargetOpcode::G_SEXTLOAD 404 ? TargetOpcode::G_SEXT 405 : TargetOpcode::G_ZEXT; 406 Preferred = {LLT(), PreferredOpcode, nullptr}; 407 for (auto &UseMI : MRI.use_nodbg_instructions(LoadValue.getReg())) { 408 if (UseMI.getOpcode() == TargetOpcode::G_SEXT || 409 UseMI.getOpcode() == TargetOpcode::G_ZEXT || 410 (UseMI.getOpcode() == TargetOpcode::G_ANYEXT)) { 411 // Check for legality. 412 if (LI) { 413 LegalityQuery::MemDesc MMDesc; 414 const auto &MMO = **MI.memoperands_begin(); 415 MMDesc.SizeInBits = MMO.getSizeInBits(); 416 MMDesc.AlignInBits = MMO.getAlign().value() * 8; 417 MMDesc.Ordering = MMO.getOrdering(); 418 LLT UseTy = MRI.getType(UseMI.getOperand(0).getReg()); 419 LLT SrcTy = MRI.getType(MI.getOperand(1).getReg()); 420 if (LI->getAction({MI.getOpcode(), {UseTy, SrcTy}, {MMDesc}}).Action != 421 LegalizeActions::Legal) 422 continue; 423 } 424 Preferred = ChoosePreferredUse(Preferred, 425 MRI.getType(UseMI.getOperand(0).getReg()), 426 UseMI.getOpcode(), &UseMI); 427 } 428 } 429 430 // There were no extends 431 if (!Preferred.MI) 432 return false; 433 // It should be impossible to chose an extend without selecting a different 434 // type since by definition the result of an extend is larger. 435 assert(Preferred.Ty != LoadValueTy && "Extending to same type?"); 436 437 LLVM_DEBUG(dbgs() << "Preferred use is: " << *Preferred.MI); 438 return true; 439 } 440 441 void CombinerHelper::applyCombineExtendingLoads(MachineInstr &MI, 442 PreferredTuple &Preferred) { 443 // Rewrite the load to the chosen extending load. 444 Register ChosenDstReg = Preferred.MI->getOperand(0).getReg(); 445 446 // Inserter to insert a truncate back to the original type at a given point 447 // with some basic CSE to limit truncate duplication to one per BB. 448 DenseMap<MachineBasicBlock *, MachineInstr *> EmittedInsns; 449 auto InsertTruncAt = [&](MachineBasicBlock *InsertIntoBB, 450 MachineBasicBlock::iterator InsertBefore, 451 MachineOperand &UseMO) { 452 MachineInstr *PreviouslyEmitted = EmittedInsns.lookup(InsertIntoBB); 453 if (PreviouslyEmitted) { 454 Observer.changingInstr(*UseMO.getParent()); 455 UseMO.setReg(PreviouslyEmitted->getOperand(0).getReg()); 456 Observer.changedInstr(*UseMO.getParent()); 457 return; 458 } 459 460 Builder.setInsertPt(*InsertIntoBB, InsertBefore); 461 Register NewDstReg = MRI.cloneVirtualRegister(MI.getOperand(0).getReg()); 462 MachineInstr *NewMI = Builder.buildTrunc(NewDstReg, ChosenDstReg); 463 EmittedInsns[InsertIntoBB] = NewMI; 464 replaceRegOpWith(MRI, UseMO, NewDstReg); 465 }; 466 467 Observer.changingInstr(MI); 468 MI.setDesc( 469 Builder.getTII().get(Preferred.ExtendOpcode == TargetOpcode::G_SEXT 470 ? TargetOpcode::G_SEXTLOAD 471 : Preferred.ExtendOpcode == TargetOpcode::G_ZEXT 472 ? TargetOpcode::G_ZEXTLOAD 473 : TargetOpcode::G_LOAD)); 474 475 // Rewrite all the uses to fix up the types. 476 auto &LoadValue = MI.getOperand(0); 477 SmallVector<MachineOperand *, 4> Uses; 478 for (auto &UseMO : MRI.use_operands(LoadValue.getReg())) 479 Uses.push_back(&UseMO); 480 481 for (auto *UseMO : Uses) { 482 MachineInstr *UseMI = UseMO->getParent(); 483 484 // If the extend is compatible with the preferred extend then we should fix 485 // up the type and extend so that it uses the preferred use. 486 if (UseMI->getOpcode() == Preferred.ExtendOpcode || 487 UseMI->getOpcode() == TargetOpcode::G_ANYEXT) { 488 Register UseDstReg = UseMI->getOperand(0).getReg(); 489 MachineOperand &UseSrcMO = UseMI->getOperand(1); 490 const LLT UseDstTy = MRI.getType(UseDstReg); 491 if (UseDstReg != ChosenDstReg) { 492 if (Preferred.Ty == UseDstTy) { 493 // If the use has the same type as the preferred use, then merge 494 // the vregs and erase the extend. For example: 495 // %1:_(s8) = G_LOAD ... 496 // %2:_(s32) = G_SEXT %1(s8) 497 // %3:_(s32) = G_ANYEXT %1(s8) 498 // ... = ... %3(s32) 499 // rewrites to: 500 // %2:_(s32) = G_SEXTLOAD ... 501 // ... = ... %2(s32) 502 replaceRegWith(MRI, UseDstReg, ChosenDstReg); 503 Observer.erasingInstr(*UseMO->getParent()); 504 UseMO->getParent()->eraseFromParent(); 505 } else if (Preferred.Ty.getSizeInBits() < UseDstTy.getSizeInBits()) { 506 // If the preferred size is smaller, then keep the extend but extend 507 // from the result of the extending load. For example: 508 // %1:_(s8) = G_LOAD ... 509 // %2:_(s32) = G_SEXT %1(s8) 510 // %3:_(s64) = G_ANYEXT %1(s8) 511 // ... = ... %3(s64) 512 /// rewrites to: 513 // %2:_(s32) = G_SEXTLOAD ... 514 // %3:_(s64) = G_ANYEXT %2:_(s32) 515 // ... = ... %3(s64) 516 replaceRegOpWith(MRI, UseSrcMO, ChosenDstReg); 517 } else { 518 // If the preferred size is large, then insert a truncate. For 519 // example: 520 // %1:_(s8) = G_LOAD ... 521 // %2:_(s64) = G_SEXT %1(s8) 522 // %3:_(s32) = G_ZEXT %1(s8) 523 // ... = ... %3(s32) 524 /// rewrites to: 525 // %2:_(s64) = G_SEXTLOAD ... 526 // %4:_(s8) = G_TRUNC %2:_(s32) 527 // %3:_(s64) = G_ZEXT %2:_(s8) 528 // ... = ... %3(s64) 529 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, 530 InsertTruncAt); 531 } 532 continue; 533 } 534 // The use is (one of) the uses of the preferred use we chose earlier. 535 // We're going to update the load to def this value later so just erase 536 // the old extend. 537 Observer.erasingInstr(*UseMO->getParent()); 538 UseMO->getParent()->eraseFromParent(); 539 continue; 540 } 541 542 // The use isn't an extend. Truncate back to the type we originally loaded. 543 // This is free on many targets. 544 InsertInsnsWithoutSideEffectsBeforeUse(Builder, MI, *UseMO, InsertTruncAt); 545 } 546 547 MI.getOperand(0).setReg(ChosenDstReg); 548 Observer.changedInstr(MI); 549 } 550 551 bool CombinerHelper::isPredecessor(const MachineInstr &DefMI, 552 const MachineInstr &UseMI) { 553 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() && 554 "shouldn't consider debug uses"); 555 assert(DefMI.getParent() == UseMI.getParent()); 556 if (&DefMI == &UseMI) 557 return false; 558 559 // Loop through the basic block until we find one of the instructions. 560 MachineBasicBlock::const_iterator I = DefMI.getParent()->begin(); 561 for (; &*I != &DefMI && &*I != &UseMI; ++I) 562 return &*I == &DefMI; 563 564 llvm_unreachable("Block must contain instructions"); 565 } 566 567 bool CombinerHelper::dominates(const MachineInstr &DefMI, 568 const MachineInstr &UseMI) { 569 assert(!DefMI.isDebugInstr() && !UseMI.isDebugInstr() && 570 "shouldn't consider debug uses"); 571 if (MDT) 572 return MDT->dominates(&DefMI, &UseMI); 573 else if (DefMI.getParent() != UseMI.getParent()) 574 return false; 575 576 return isPredecessor(DefMI, UseMI); 577 } 578 579 bool CombinerHelper::findPostIndexCandidate(MachineInstr &MI, Register &Addr, 580 Register &Base, Register &Offset) { 581 auto &MF = *MI.getParent()->getParent(); 582 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 583 584 #ifndef NDEBUG 585 unsigned Opcode = MI.getOpcode(); 586 assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD || 587 Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE); 588 #endif 589 590 Base = MI.getOperand(1).getReg(); 591 MachineInstr *BaseDef = MRI.getUniqueVRegDef(Base); 592 if (BaseDef && BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) 593 return false; 594 595 LLVM_DEBUG(dbgs() << "Searching for post-indexing opportunity for: " << MI); 596 597 for (auto &Use : MRI.use_nodbg_instructions(Base)) { 598 if (Use.getOpcode() != TargetOpcode::G_PTR_ADD) 599 continue; 600 601 Offset = Use.getOperand(2).getReg(); 602 if (!ForceLegalIndexing && 603 !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ false, MRI)) { 604 LLVM_DEBUG(dbgs() << " Ignoring candidate with illegal addrmode: " 605 << Use); 606 continue; 607 } 608 609 // Make sure the offset calculation is before the potentially indexed op. 610 // FIXME: we really care about dependency here. The offset calculation might 611 // be movable. 612 MachineInstr *OffsetDef = MRI.getUniqueVRegDef(Offset); 613 if (!OffsetDef || !dominates(*OffsetDef, MI)) { 614 LLVM_DEBUG(dbgs() << " Ignoring candidate with offset after mem-op: " 615 << Use); 616 continue; 617 } 618 619 // FIXME: check whether all uses of Base are load/store with foldable 620 // addressing modes. If so, using the normal addr-modes is better than 621 // forming an indexed one. 622 623 bool MemOpDominatesAddrUses = true; 624 for (auto &PtrAddUse : 625 MRI.use_nodbg_instructions(Use.getOperand(0).getReg())) { 626 if (!dominates(MI, PtrAddUse)) { 627 MemOpDominatesAddrUses = false; 628 break; 629 } 630 } 631 632 if (!MemOpDominatesAddrUses) { 633 LLVM_DEBUG( 634 dbgs() << " Ignoring candidate as memop does not dominate uses: " 635 << Use); 636 continue; 637 } 638 639 LLVM_DEBUG(dbgs() << " Found match: " << Use); 640 Addr = Use.getOperand(0).getReg(); 641 return true; 642 } 643 644 return false; 645 } 646 647 bool CombinerHelper::findPreIndexCandidate(MachineInstr &MI, Register &Addr, 648 Register &Base, Register &Offset) { 649 auto &MF = *MI.getParent()->getParent(); 650 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 651 652 #ifndef NDEBUG 653 unsigned Opcode = MI.getOpcode(); 654 assert(Opcode == TargetOpcode::G_LOAD || Opcode == TargetOpcode::G_SEXTLOAD || 655 Opcode == TargetOpcode::G_ZEXTLOAD || Opcode == TargetOpcode::G_STORE); 656 #endif 657 658 Addr = MI.getOperand(1).getReg(); 659 MachineInstr *AddrDef = getOpcodeDef(TargetOpcode::G_PTR_ADD, Addr, MRI); 660 if (!AddrDef || MRI.hasOneNonDBGUse(Addr)) 661 return false; 662 663 Base = AddrDef->getOperand(1).getReg(); 664 Offset = AddrDef->getOperand(2).getReg(); 665 666 LLVM_DEBUG(dbgs() << "Found potential pre-indexed load_store: " << MI); 667 668 if (!ForceLegalIndexing && 669 !TLI.isIndexingLegal(MI, Base, Offset, /*IsPre*/ true, MRI)) { 670 LLVM_DEBUG(dbgs() << " Skipping, not legal for target"); 671 return false; 672 } 673 674 MachineInstr *BaseDef = getDefIgnoringCopies(Base, MRI); 675 if (BaseDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) { 676 LLVM_DEBUG(dbgs() << " Skipping, frame index would need copy anyway."); 677 return false; 678 } 679 680 if (MI.getOpcode() == TargetOpcode::G_STORE) { 681 // Would require a copy. 682 if (Base == MI.getOperand(0).getReg()) { 683 LLVM_DEBUG(dbgs() << " Skipping, storing base so need copy anyway."); 684 return false; 685 } 686 687 // We're expecting one use of Addr in MI, but it could also be the 688 // value stored, which isn't actually dominated by the instruction. 689 if (MI.getOperand(0).getReg() == Addr) { 690 LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses"); 691 return false; 692 } 693 } 694 695 // FIXME: check whether all uses of the base pointer are constant PtrAdds. 696 // That might allow us to end base's liveness here by adjusting the constant. 697 698 for (auto &UseMI : MRI.use_nodbg_instructions(Addr)) { 699 if (!dominates(MI, UseMI)) { 700 LLVM_DEBUG(dbgs() << " Skipping, does not dominate all addr uses."); 701 return false; 702 } 703 } 704 705 return true; 706 } 707 708 bool CombinerHelper::tryCombineIndexedLoadStore(MachineInstr &MI) { 709 IndexedLoadStoreMatchInfo MatchInfo; 710 if (matchCombineIndexedLoadStore(MI, MatchInfo)) { 711 applyCombineIndexedLoadStore(MI, MatchInfo); 712 return true; 713 } 714 return false; 715 } 716 717 bool CombinerHelper::matchCombineIndexedLoadStore(MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) { 718 unsigned Opcode = MI.getOpcode(); 719 if (Opcode != TargetOpcode::G_LOAD && Opcode != TargetOpcode::G_SEXTLOAD && 720 Opcode != TargetOpcode::G_ZEXTLOAD && Opcode != TargetOpcode::G_STORE) 721 return false; 722 723 MatchInfo.IsPre = findPreIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base, 724 MatchInfo.Offset); 725 if (!MatchInfo.IsPre && 726 !findPostIndexCandidate(MI, MatchInfo.Addr, MatchInfo.Base, 727 MatchInfo.Offset)) 728 return false; 729 730 return true; 731 } 732 733 void CombinerHelper::applyCombineIndexedLoadStore( 734 MachineInstr &MI, IndexedLoadStoreMatchInfo &MatchInfo) { 735 MachineInstr &AddrDef = *MRI.getUniqueVRegDef(MatchInfo.Addr); 736 MachineIRBuilder MIRBuilder(MI); 737 unsigned Opcode = MI.getOpcode(); 738 bool IsStore = Opcode == TargetOpcode::G_STORE; 739 unsigned NewOpcode; 740 switch (Opcode) { 741 case TargetOpcode::G_LOAD: 742 NewOpcode = TargetOpcode::G_INDEXED_LOAD; 743 break; 744 case TargetOpcode::G_SEXTLOAD: 745 NewOpcode = TargetOpcode::G_INDEXED_SEXTLOAD; 746 break; 747 case TargetOpcode::G_ZEXTLOAD: 748 NewOpcode = TargetOpcode::G_INDEXED_ZEXTLOAD; 749 break; 750 case TargetOpcode::G_STORE: 751 NewOpcode = TargetOpcode::G_INDEXED_STORE; 752 break; 753 default: 754 llvm_unreachable("Unknown load/store opcode"); 755 } 756 757 auto MIB = MIRBuilder.buildInstr(NewOpcode); 758 if (IsStore) { 759 MIB.addDef(MatchInfo.Addr); 760 MIB.addUse(MI.getOperand(0).getReg()); 761 } else { 762 MIB.addDef(MI.getOperand(0).getReg()); 763 MIB.addDef(MatchInfo.Addr); 764 } 765 766 MIB.addUse(MatchInfo.Base); 767 MIB.addUse(MatchInfo.Offset); 768 MIB.addImm(MatchInfo.IsPre); 769 MI.eraseFromParent(); 770 AddrDef.eraseFromParent(); 771 772 LLVM_DEBUG(dbgs() << " Combinined to indexed operation"); 773 } 774 775 bool CombinerHelper::matchElideBrByInvertingCond(MachineInstr &MI) { 776 if (MI.getOpcode() != TargetOpcode::G_BR) 777 return false; 778 779 // Try to match the following: 780 // bb1: 781 // %c(s32) = G_ICMP pred, %a, %b 782 // %c1(s1) = G_TRUNC %c(s32) 783 // G_BRCOND %c1, %bb2 784 // G_BR %bb3 785 // bb2: 786 // ... 787 // bb3: 788 789 // The above pattern does not have a fall through to the successor bb2, always 790 // resulting in a branch no matter which path is taken. Here we try to find 791 // and replace that pattern with conditional branch to bb3 and otherwise 792 // fallthrough to bb2. 793 794 MachineBasicBlock *MBB = MI.getParent(); 795 MachineBasicBlock::iterator BrIt(MI); 796 if (BrIt == MBB->begin()) 797 return false; 798 assert(std::next(BrIt) == MBB->end() && "expected G_BR to be a terminator"); 799 800 MachineInstr *BrCond = &*std::prev(BrIt); 801 if (BrCond->getOpcode() != TargetOpcode::G_BRCOND) 802 return false; 803 804 // Check that the next block is the conditional branch target. 805 if (!MBB->isLayoutSuccessor(BrCond->getOperand(1).getMBB())) 806 return false; 807 808 MachineInstr *CmpMI = MRI.getVRegDef(BrCond->getOperand(0).getReg()); 809 if (!CmpMI || CmpMI->getOpcode() != TargetOpcode::G_ICMP || 810 !MRI.hasOneNonDBGUse(CmpMI->getOperand(0).getReg())) 811 return false; 812 return true; 813 } 814 815 bool CombinerHelper::tryElideBrByInvertingCond(MachineInstr &MI) { 816 if (!matchElideBrByInvertingCond(MI)) 817 return false; 818 applyElideBrByInvertingCond(MI); 819 return true; 820 } 821 822 void CombinerHelper::applyElideBrByInvertingCond(MachineInstr &MI) { 823 MachineBasicBlock *BrTarget = MI.getOperand(0).getMBB(); 824 MachineBasicBlock::iterator BrIt(MI); 825 MachineInstr *BrCond = &*std::prev(BrIt); 826 MachineInstr *CmpMI = MRI.getVRegDef(BrCond->getOperand(0).getReg()); 827 828 CmpInst::Predicate InversePred = CmpInst::getInversePredicate( 829 (CmpInst::Predicate)CmpMI->getOperand(1).getPredicate()); 830 831 // Invert the G_ICMP condition. 832 Observer.changingInstr(*CmpMI); 833 CmpMI->getOperand(1).setPredicate(InversePred); 834 Observer.changedInstr(*CmpMI); 835 836 // Change the conditional branch target. 837 Observer.changingInstr(*BrCond); 838 BrCond->getOperand(1).setMBB(BrTarget); 839 Observer.changedInstr(*BrCond); 840 MI.eraseFromParent(); 841 } 842 843 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) { 844 // On Darwin, -Os means optimize for size without hurting performance, so 845 // only really optimize for size when -Oz (MinSize) is used. 846 if (MF.getTarget().getTargetTriple().isOSDarwin()) 847 return MF.getFunction().hasMinSize(); 848 return MF.getFunction().hasOptSize(); 849 } 850 851 // Returns a list of types to use for memory op lowering in MemOps. A partial 852 // port of findOptimalMemOpLowering in TargetLowering. 853 static bool findGISelOptimalMemOpLowering(std::vector<LLT> &MemOps, 854 unsigned Limit, const MemOp &Op, 855 unsigned DstAS, unsigned SrcAS, 856 const AttributeList &FuncAttributes, 857 const TargetLowering &TLI) { 858 if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign()) 859 return false; 860 861 LLT Ty = TLI.getOptimalMemOpLLT(Op, FuncAttributes); 862 863 if (Ty == LLT()) { 864 // Use the largest scalar type whose alignment constraints are satisfied. 865 // We only need to check DstAlign here as SrcAlign is always greater or 866 // equal to DstAlign (or zero). 867 Ty = LLT::scalar(64); 868 if (Op.isFixedDstAlign()) 869 while (Op.getDstAlign() < Ty.getSizeInBytes() && 870 !TLI.allowsMisalignedMemoryAccesses(Ty, DstAS, 871 Op.getDstAlign().value())) 872 Ty = LLT::scalar(Ty.getSizeInBytes()); 873 assert(Ty.getSizeInBits() > 0 && "Could not find valid type"); 874 // FIXME: check for the largest legal type we can load/store to. 875 } 876 877 unsigned NumMemOps = 0; 878 uint64_t Size = Op.size(); 879 while (Size) { 880 unsigned TySize = Ty.getSizeInBytes(); 881 while (TySize > Size) { 882 // For now, only use non-vector load / store's for the left-over pieces. 883 LLT NewTy = Ty; 884 // FIXME: check for mem op safety and legality of the types. Not all of 885 // SDAGisms map cleanly to GISel concepts. 886 if (NewTy.isVector()) 887 NewTy = NewTy.getSizeInBits() > 64 ? LLT::scalar(64) : LLT::scalar(32); 888 NewTy = LLT::scalar(PowerOf2Floor(NewTy.getSizeInBits() - 1)); 889 unsigned NewTySize = NewTy.getSizeInBytes(); 890 assert(NewTySize > 0 && "Could not find appropriate type"); 891 892 // If the new LLT cannot cover all of the remaining bits, then consider 893 // issuing a (or a pair of) unaligned and overlapping load / store. 894 bool Fast; 895 // Need to get a VT equivalent for allowMisalignedMemoryAccesses(). 896 MVT VT = getMVTForLLT(Ty); 897 if (NumMemOps && Op.allowOverlap() && NewTySize < Size && 898 TLI.allowsMisalignedMemoryAccesses( 899 VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign().value() : 0, 900 MachineMemOperand::MONone, &Fast) && 901 Fast) 902 TySize = Size; 903 else { 904 Ty = NewTy; 905 TySize = NewTySize; 906 } 907 } 908 909 if (++NumMemOps > Limit) 910 return false; 911 912 MemOps.push_back(Ty); 913 Size -= TySize; 914 } 915 916 return true; 917 } 918 919 static Type *getTypeForLLT(LLT Ty, LLVMContext &C) { 920 if (Ty.isVector()) 921 return VectorType::get(IntegerType::get(C, Ty.getScalarSizeInBits()), 922 Ty.getNumElements()); 923 return IntegerType::get(C, Ty.getSizeInBits()); 924 } 925 926 // Get a vectorized representation of the memset value operand, GISel edition. 927 static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB) { 928 MachineRegisterInfo &MRI = *MIB.getMRI(); 929 unsigned NumBits = Ty.getScalarSizeInBits(); 930 auto ValVRegAndVal = getConstantVRegValWithLookThrough(Val, MRI); 931 if (!Ty.isVector() && ValVRegAndVal) { 932 unsigned KnownVal = ValVRegAndVal->Value; 933 APInt Scalar = APInt(8, KnownVal); 934 APInt SplatVal = APInt::getSplat(NumBits, Scalar); 935 return MIB.buildConstant(Ty, SplatVal).getReg(0); 936 } 937 938 // Extend the byte value to the larger type, and then multiply by a magic 939 // value 0x010101... in order to replicate it across every byte. 940 LLT ExtType = Ty.getScalarType(); 941 auto ZExt = MIB.buildZExtOrTrunc(ExtType, Val); 942 if (NumBits > 8) { 943 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 944 auto MagicMI = MIB.buildConstant(ExtType, Magic); 945 Val = MIB.buildMul(ExtType, ZExt, MagicMI).getReg(0); 946 } 947 948 // For vector types create a G_BUILD_VECTOR. 949 if (Ty.isVector()) 950 Val = MIB.buildSplatVector(Ty, Val).getReg(0); 951 952 return Val; 953 } 954 955 bool CombinerHelper::optimizeMemset(MachineInstr &MI, Register Dst, 956 Register Val, unsigned KnownLen, 957 Align Alignment, bool IsVolatile) { 958 auto &MF = *MI.getParent()->getParent(); 959 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 960 auto &DL = MF.getDataLayout(); 961 LLVMContext &C = MF.getFunction().getContext(); 962 963 assert(KnownLen != 0 && "Have a zero length memset length!"); 964 965 bool DstAlignCanChange = false; 966 MachineFrameInfo &MFI = MF.getFrameInfo(); 967 bool OptSize = shouldLowerMemFuncForSize(MF); 968 969 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI); 970 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex())) 971 DstAlignCanChange = true; 972 973 unsigned Limit = TLI.getMaxStoresPerMemset(OptSize); 974 std::vector<LLT> MemOps; 975 976 const auto &DstMMO = **MI.memoperands_begin(); 977 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo(); 978 979 auto ValVRegAndVal = getConstantVRegValWithLookThrough(Val, MRI); 980 bool IsZeroVal = ValVRegAndVal && ValVRegAndVal->Value == 0; 981 982 if (!findGISelOptimalMemOpLowering(MemOps, Limit, 983 MemOp::Set(KnownLen, DstAlignCanChange, 984 Alignment, 985 /*IsZeroMemset=*/IsZeroVal, 986 /*IsVolatile=*/IsVolatile), 987 DstPtrInfo.getAddrSpace(), ~0u, 988 MF.getFunction().getAttributes(), TLI)) 989 return false; 990 991 if (DstAlignCanChange) { 992 // Get an estimate of the type from the LLT. 993 Type *IRTy = getTypeForLLT(MemOps[0], C); 994 Align NewAlign = DL.getABITypeAlign(IRTy); 995 if (NewAlign > Alignment) { 996 Alignment = NewAlign; 997 unsigned FI = FIDef->getOperand(1).getIndex(); 998 // Give the stack frame object a larger alignment if needed. 999 if (MFI.getObjectAlign(FI) < Alignment) 1000 MFI.setObjectAlignment(FI, Alignment); 1001 } 1002 } 1003 1004 MachineIRBuilder MIB(MI); 1005 // Find the largest store and generate the bit pattern for it. 1006 LLT LargestTy = MemOps[0]; 1007 for (unsigned i = 1; i < MemOps.size(); i++) 1008 if (MemOps[i].getSizeInBits() > LargestTy.getSizeInBits()) 1009 LargestTy = MemOps[i]; 1010 1011 // The memset stored value is always defined as an s8, so in order to make it 1012 // work with larger store types we need to repeat the bit pattern across the 1013 // wider type. 1014 Register MemSetValue = getMemsetValue(Val, LargestTy, MIB); 1015 1016 if (!MemSetValue) 1017 return false; 1018 1019 // Generate the stores. For each store type in the list, we generate the 1020 // matching store of that type to the destination address. 1021 LLT PtrTy = MRI.getType(Dst); 1022 unsigned DstOff = 0; 1023 unsigned Size = KnownLen; 1024 for (unsigned I = 0; I < MemOps.size(); I++) { 1025 LLT Ty = MemOps[I]; 1026 unsigned TySize = Ty.getSizeInBytes(); 1027 if (TySize > Size) { 1028 // Issuing an unaligned load / store pair that overlaps with the previous 1029 // pair. Adjust the offset accordingly. 1030 assert(I == MemOps.size() - 1 && I != 0); 1031 DstOff -= TySize - Size; 1032 } 1033 1034 // If this store is smaller than the largest store see whether we can get 1035 // the smaller value for free with a truncate. 1036 Register Value = MemSetValue; 1037 if (Ty.getSizeInBits() < LargestTy.getSizeInBits()) { 1038 MVT VT = getMVTForLLT(Ty); 1039 MVT LargestVT = getMVTForLLT(LargestTy); 1040 if (!LargestTy.isVector() && !Ty.isVector() && 1041 TLI.isTruncateFree(LargestVT, VT)) 1042 Value = MIB.buildTrunc(Ty, MemSetValue).getReg(0); 1043 else 1044 Value = getMemsetValue(Val, Ty, MIB); 1045 if (!Value) 1046 return false; 1047 } 1048 1049 auto *StoreMMO = 1050 MF.getMachineMemOperand(&DstMMO, DstOff, Ty.getSizeInBytes()); 1051 1052 Register Ptr = Dst; 1053 if (DstOff != 0) { 1054 auto Offset = 1055 MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), DstOff); 1056 Ptr = MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0); 1057 } 1058 1059 MIB.buildStore(Value, Ptr, *StoreMMO); 1060 DstOff += Ty.getSizeInBytes(); 1061 Size -= TySize; 1062 } 1063 1064 MI.eraseFromParent(); 1065 return true; 1066 } 1067 1068 bool CombinerHelper::optimizeMemcpy(MachineInstr &MI, Register Dst, 1069 Register Src, unsigned KnownLen, 1070 Align DstAlign, Align SrcAlign, 1071 bool IsVolatile) { 1072 auto &MF = *MI.getParent()->getParent(); 1073 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 1074 auto &DL = MF.getDataLayout(); 1075 LLVMContext &C = MF.getFunction().getContext(); 1076 1077 assert(KnownLen != 0 && "Have a zero length memcpy length!"); 1078 1079 bool DstAlignCanChange = false; 1080 MachineFrameInfo &MFI = MF.getFrameInfo(); 1081 bool OptSize = shouldLowerMemFuncForSize(MF); 1082 Align Alignment = commonAlignment(DstAlign, SrcAlign); 1083 1084 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI); 1085 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex())) 1086 DstAlignCanChange = true; 1087 1088 // FIXME: infer better src pointer alignment like SelectionDAG does here. 1089 // FIXME: also use the equivalent of isMemSrcFromConstant and alwaysinlining 1090 // if the memcpy is in a tail call position. 1091 1092 unsigned Limit = TLI.getMaxStoresPerMemcpy(OptSize); 1093 std::vector<LLT> MemOps; 1094 1095 const auto &DstMMO = **MI.memoperands_begin(); 1096 const auto &SrcMMO = **std::next(MI.memoperands_begin()); 1097 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo(); 1098 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo(); 1099 1100 if (!findGISelOptimalMemOpLowering( 1101 MemOps, Limit, 1102 MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign, 1103 IsVolatile), 1104 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 1105 MF.getFunction().getAttributes(), TLI)) 1106 return false; 1107 1108 if (DstAlignCanChange) { 1109 // Get an estimate of the type from the LLT. 1110 Type *IRTy = getTypeForLLT(MemOps[0], C); 1111 Align NewAlign = DL.getABITypeAlign(IRTy); 1112 1113 // Don't promote to an alignment that would require dynamic stack 1114 // realignment. 1115 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1116 if (!TRI->needsStackRealignment(MF)) 1117 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 1118 NewAlign = NewAlign / 2; 1119 1120 if (NewAlign > Alignment) { 1121 Alignment = NewAlign; 1122 unsigned FI = FIDef->getOperand(1).getIndex(); 1123 // Give the stack frame object a larger alignment if needed. 1124 if (MFI.getObjectAlign(FI) < Alignment) 1125 MFI.setObjectAlignment(FI, Alignment); 1126 } 1127 } 1128 1129 LLVM_DEBUG(dbgs() << "Inlining memcpy: " << MI << " into loads & stores\n"); 1130 1131 MachineIRBuilder MIB(MI); 1132 // Now we need to emit a pair of load and stores for each of the types we've 1133 // collected. I.e. for each type, generate a load from the source pointer of 1134 // that type width, and then generate a corresponding store to the dest buffer 1135 // of that value loaded. This can result in a sequence of loads and stores 1136 // mixed types, depending on what the target specifies as good types to use. 1137 unsigned CurrOffset = 0; 1138 LLT PtrTy = MRI.getType(Src); 1139 unsigned Size = KnownLen; 1140 for (auto CopyTy : MemOps) { 1141 // Issuing an unaligned load / store pair that overlaps with the previous 1142 // pair. Adjust the offset accordingly. 1143 if (CopyTy.getSizeInBytes() > Size) 1144 CurrOffset -= CopyTy.getSizeInBytes() - Size; 1145 1146 // Construct MMOs for the accesses. 1147 auto *LoadMMO = 1148 MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes()); 1149 auto *StoreMMO = 1150 MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes()); 1151 1152 // Create the load. 1153 Register LoadPtr = Src; 1154 Register Offset; 1155 if (CurrOffset != 0) { 1156 Offset = MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset) 1157 .getReg(0); 1158 LoadPtr = MIB.buildPtrAdd(PtrTy, Src, Offset).getReg(0); 1159 } 1160 auto LdVal = MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO); 1161 1162 // Create the store. 1163 Register StorePtr = 1164 CurrOffset == 0 ? Dst : MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0); 1165 MIB.buildStore(LdVal, StorePtr, *StoreMMO); 1166 CurrOffset += CopyTy.getSizeInBytes(); 1167 Size -= CopyTy.getSizeInBytes(); 1168 } 1169 1170 MI.eraseFromParent(); 1171 return true; 1172 } 1173 1174 bool CombinerHelper::optimizeMemmove(MachineInstr &MI, Register Dst, 1175 Register Src, unsigned KnownLen, 1176 Align DstAlign, Align SrcAlign, 1177 bool IsVolatile) { 1178 auto &MF = *MI.getParent()->getParent(); 1179 const auto &TLI = *MF.getSubtarget().getTargetLowering(); 1180 auto &DL = MF.getDataLayout(); 1181 LLVMContext &C = MF.getFunction().getContext(); 1182 1183 assert(KnownLen != 0 && "Have a zero length memmove length!"); 1184 1185 bool DstAlignCanChange = false; 1186 MachineFrameInfo &MFI = MF.getFrameInfo(); 1187 bool OptSize = shouldLowerMemFuncForSize(MF); 1188 Align Alignment = commonAlignment(DstAlign, SrcAlign); 1189 1190 MachineInstr *FIDef = getOpcodeDef(TargetOpcode::G_FRAME_INDEX, Dst, MRI); 1191 if (FIDef && !MFI.isFixedObjectIndex(FIDef->getOperand(1).getIndex())) 1192 DstAlignCanChange = true; 1193 1194 unsigned Limit = TLI.getMaxStoresPerMemmove(OptSize); 1195 std::vector<LLT> MemOps; 1196 1197 const auto &DstMMO = **MI.memoperands_begin(); 1198 const auto &SrcMMO = **std::next(MI.memoperands_begin()); 1199 MachinePointerInfo DstPtrInfo = DstMMO.getPointerInfo(); 1200 MachinePointerInfo SrcPtrInfo = SrcMMO.getPointerInfo(); 1201 1202 // FIXME: SelectionDAG always passes false for 'AllowOverlap', apparently due 1203 // to a bug in it's findOptimalMemOpLowering implementation. For now do the 1204 // same thing here. 1205 if (!findGISelOptimalMemOpLowering( 1206 MemOps, Limit, 1207 MemOp::Copy(KnownLen, DstAlignCanChange, Alignment, SrcAlign, 1208 /*IsVolatile*/ true), 1209 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 1210 MF.getFunction().getAttributes(), TLI)) 1211 return false; 1212 1213 if (DstAlignCanChange) { 1214 // Get an estimate of the type from the LLT. 1215 Type *IRTy = getTypeForLLT(MemOps[0], C); 1216 Align NewAlign = DL.getABITypeAlign(IRTy); 1217 1218 // Don't promote to an alignment that would require dynamic stack 1219 // realignment. 1220 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1221 if (!TRI->needsStackRealignment(MF)) 1222 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 1223 NewAlign = NewAlign / 2; 1224 1225 if (NewAlign > Alignment) { 1226 Alignment = NewAlign; 1227 unsigned FI = FIDef->getOperand(1).getIndex(); 1228 // Give the stack frame object a larger alignment if needed. 1229 if (MFI.getObjectAlign(FI) < Alignment) 1230 MFI.setObjectAlignment(FI, Alignment); 1231 } 1232 } 1233 1234 LLVM_DEBUG(dbgs() << "Inlining memmove: " << MI << " into loads & stores\n"); 1235 1236 MachineIRBuilder MIB(MI); 1237 // Memmove requires that we perform the loads first before issuing the stores. 1238 // Apart from that, this loop is pretty much doing the same thing as the 1239 // memcpy codegen function. 1240 unsigned CurrOffset = 0; 1241 LLT PtrTy = MRI.getType(Src); 1242 SmallVector<Register, 16> LoadVals; 1243 for (auto CopyTy : MemOps) { 1244 // Construct MMO for the load. 1245 auto *LoadMMO = 1246 MF.getMachineMemOperand(&SrcMMO, CurrOffset, CopyTy.getSizeInBytes()); 1247 1248 // Create the load. 1249 Register LoadPtr = Src; 1250 if (CurrOffset != 0) { 1251 auto Offset = 1252 MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset); 1253 LoadPtr = MIB.buildPtrAdd(PtrTy, Src, Offset).getReg(0); 1254 } 1255 LoadVals.push_back(MIB.buildLoad(CopyTy, LoadPtr, *LoadMMO).getReg(0)); 1256 CurrOffset += CopyTy.getSizeInBytes(); 1257 } 1258 1259 CurrOffset = 0; 1260 for (unsigned I = 0; I < MemOps.size(); ++I) { 1261 LLT CopyTy = MemOps[I]; 1262 // Now store the values loaded. 1263 auto *StoreMMO = 1264 MF.getMachineMemOperand(&DstMMO, CurrOffset, CopyTy.getSizeInBytes()); 1265 1266 Register StorePtr = Dst; 1267 if (CurrOffset != 0) { 1268 auto Offset = 1269 MIB.buildConstant(LLT::scalar(PtrTy.getSizeInBits()), CurrOffset); 1270 StorePtr = MIB.buildPtrAdd(PtrTy, Dst, Offset).getReg(0); 1271 } 1272 MIB.buildStore(LoadVals[I], StorePtr, *StoreMMO); 1273 CurrOffset += CopyTy.getSizeInBytes(); 1274 } 1275 MI.eraseFromParent(); 1276 return true; 1277 } 1278 1279 bool CombinerHelper::tryCombineMemCpyFamily(MachineInstr &MI, unsigned MaxLen) { 1280 // This combine is fairly complex so it's not written with a separate 1281 // matcher function. 1282 assert(MI.getOpcode() == TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS); 1283 Intrinsic::ID ID = (Intrinsic::ID)MI.getIntrinsicID(); 1284 assert((ID == Intrinsic::memcpy || ID == Intrinsic::memmove || 1285 ID == Intrinsic::memset) && 1286 "Expected a memcpy like intrinsic"); 1287 1288 auto MMOIt = MI.memoperands_begin(); 1289 const MachineMemOperand *MemOp = *MMOIt; 1290 bool IsVolatile = MemOp->isVolatile(); 1291 // Don't try to optimize volatile. 1292 if (IsVolatile) 1293 return false; 1294 1295 Align DstAlign = MemOp->getBaseAlign(); 1296 Align SrcAlign; 1297 Register Dst = MI.getOperand(1).getReg(); 1298 Register Src = MI.getOperand(2).getReg(); 1299 Register Len = MI.getOperand(3).getReg(); 1300 1301 if (ID != Intrinsic::memset) { 1302 assert(MMOIt != MI.memoperands_end() && "Expected a second MMO on MI"); 1303 MemOp = *(++MMOIt); 1304 SrcAlign = MemOp->getBaseAlign(); 1305 } 1306 1307 // See if this is a constant length copy 1308 auto LenVRegAndVal = getConstantVRegValWithLookThrough(Len, MRI); 1309 if (!LenVRegAndVal) 1310 return false; // Leave it to the legalizer to lower it to a libcall. 1311 unsigned KnownLen = LenVRegAndVal->Value; 1312 1313 if (KnownLen == 0) { 1314 MI.eraseFromParent(); 1315 return true; 1316 } 1317 1318 if (MaxLen && KnownLen > MaxLen) 1319 return false; 1320 1321 if (ID == Intrinsic::memcpy) 1322 return optimizeMemcpy(MI, Dst, Src, KnownLen, DstAlign, SrcAlign, IsVolatile); 1323 if (ID == Intrinsic::memmove) 1324 return optimizeMemmove(MI, Dst, Src, KnownLen, DstAlign, SrcAlign, IsVolatile); 1325 if (ID == Intrinsic::memset) 1326 return optimizeMemset(MI, Dst, Src, KnownLen, DstAlign, IsVolatile); 1327 return false; 1328 } 1329 1330 bool CombinerHelper::matchPtrAddImmedChain(MachineInstr &MI, 1331 PtrAddChain &MatchInfo) { 1332 // We're trying to match the following pattern: 1333 // %t1 = G_PTR_ADD %base, G_CONSTANT imm1 1334 // %root = G_PTR_ADD %t1, G_CONSTANT imm2 1335 // --> 1336 // %root = G_PTR_ADD %base, G_CONSTANT (imm1 + imm2) 1337 1338 if (MI.getOpcode() != TargetOpcode::G_PTR_ADD) 1339 return false; 1340 1341 Register Add2 = MI.getOperand(1).getReg(); 1342 Register Imm1 = MI.getOperand(2).getReg(); 1343 auto MaybeImmVal = getConstantVRegValWithLookThrough(Imm1, MRI); 1344 if (!MaybeImmVal) 1345 return false; 1346 1347 MachineInstr *Add2Def = MRI.getUniqueVRegDef(Add2); 1348 if (!Add2Def || Add2Def->getOpcode() != TargetOpcode::G_PTR_ADD) 1349 return false; 1350 1351 Register Base = Add2Def->getOperand(1).getReg(); 1352 Register Imm2 = Add2Def->getOperand(2).getReg(); 1353 auto MaybeImm2Val = getConstantVRegValWithLookThrough(Imm2, MRI); 1354 if (!MaybeImm2Val) 1355 return false; 1356 1357 // Pass the combined immediate to the apply function. 1358 MatchInfo.Imm = MaybeImmVal->Value + MaybeImm2Val->Value; 1359 MatchInfo.Base = Base; 1360 return true; 1361 } 1362 1363 bool CombinerHelper::applyPtrAddImmedChain(MachineInstr &MI, 1364 PtrAddChain &MatchInfo) { 1365 assert(MI.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD"); 1366 MachineIRBuilder MIB(MI); 1367 LLT OffsetTy = MRI.getType(MI.getOperand(2).getReg()); 1368 auto NewOffset = MIB.buildConstant(OffsetTy, MatchInfo.Imm); 1369 Observer.changingInstr(MI); 1370 MI.getOperand(1).setReg(MatchInfo.Base); 1371 MI.getOperand(2).setReg(NewOffset.getReg(0)); 1372 Observer.changedInstr(MI); 1373 return true; 1374 } 1375 1376 bool CombinerHelper::matchCombineMulToShl(MachineInstr &MI, 1377 unsigned &ShiftVal) { 1378 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 1379 auto MaybeImmVal = 1380 getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 1381 if (!MaybeImmVal || !isPowerOf2_64(MaybeImmVal->Value)) 1382 return false; 1383 ShiftVal = Log2_64(MaybeImmVal->Value); 1384 return true; 1385 } 1386 1387 bool CombinerHelper::applyCombineMulToShl(MachineInstr &MI, 1388 unsigned &ShiftVal) { 1389 assert(MI.getOpcode() == TargetOpcode::G_MUL && "Expected a G_MUL"); 1390 MachineIRBuilder MIB(MI); 1391 LLT ShiftTy = MRI.getType(MI.getOperand(0).getReg()); 1392 auto ShiftCst = MIB.buildConstant(ShiftTy, ShiftVal); 1393 Observer.changingInstr(MI); 1394 MI.setDesc(MIB.getTII().get(TargetOpcode::G_SHL)); 1395 MI.getOperand(2).setReg(ShiftCst.getReg(0)); 1396 Observer.changedInstr(MI); 1397 return true; 1398 } 1399 1400 bool CombinerHelper::matchCombineShiftToUnmerge(MachineInstr &MI, 1401 unsigned TargetShiftSize, 1402 unsigned &ShiftVal) { 1403 assert((MI.getOpcode() == TargetOpcode::G_SHL || 1404 MI.getOpcode() == TargetOpcode::G_LSHR || 1405 MI.getOpcode() == TargetOpcode::G_ASHR) && "Expected a shift"); 1406 1407 LLT Ty = MRI.getType(MI.getOperand(0).getReg()); 1408 if (Ty.isVector()) // TODO: 1409 return false; 1410 1411 // Don't narrow further than the requested size. 1412 unsigned Size = Ty.getSizeInBits(); 1413 if (Size <= TargetShiftSize) 1414 return false; 1415 1416 auto MaybeImmVal = 1417 getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI); 1418 if (!MaybeImmVal) 1419 return false; 1420 1421 ShiftVal = MaybeImmVal->Value; 1422 return ShiftVal >= Size / 2 && ShiftVal < Size; 1423 } 1424 1425 bool CombinerHelper::applyCombineShiftToUnmerge(MachineInstr &MI, 1426 const unsigned &ShiftVal) { 1427 Register DstReg = MI.getOperand(0).getReg(); 1428 Register SrcReg = MI.getOperand(1).getReg(); 1429 LLT Ty = MRI.getType(SrcReg); 1430 unsigned Size = Ty.getSizeInBits(); 1431 unsigned HalfSize = Size / 2; 1432 assert(ShiftVal >= HalfSize); 1433 1434 LLT HalfTy = LLT::scalar(HalfSize); 1435 1436 Builder.setInstr(MI); 1437 auto Unmerge = Builder.buildUnmerge(HalfTy, SrcReg); 1438 unsigned NarrowShiftAmt = ShiftVal - HalfSize; 1439 1440 if (MI.getOpcode() == TargetOpcode::G_LSHR) { 1441 Register Narrowed = Unmerge.getReg(1); 1442 1443 // dst = G_LSHR s64:x, C for C >= 32 1444 // => 1445 // lo, hi = G_UNMERGE_VALUES x 1446 // dst = G_MERGE_VALUES (G_LSHR hi, C - 32), 0 1447 1448 if (NarrowShiftAmt != 0) { 1449 Narrowed = Builder.buildLShr(HalfTy, Narrowed, 1450 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0); 1451 } 1452 1453 auto Zero = Builder.buildConstant(HalfTy, 0); 1454 Builder.buildMerge(DstReg, { Narrowed, Zero }); 1455 } else if (MI.getOpcode() == TargetOpcode::G_SHL) { 1456 Register Narrowed = Unmerge.getReg(0); 1457 // dst = G_SHL s64:x, C for C >= 32 1458 // => 1459 // lo, hi = G_UNMERGE_VALUES x 1460 // dst = G_MERGE_VALUES 0, (G_SHL hi, C - 32) 1461 if (NarrowShiftAmt != 0) { 1462 Narrowed = Builder.buildShl(HalfTy, Narrowed, 1463 Builder.buildConstant(HalfTy, NarrowShiftAmt)).getReg(0); 1464 } 1465 1466 auto Zero = Builder.buildConstant(HalfTy, 0); 1467 Builder.buildMerge(DstReg, { Zero, Narrowed }); 1468 } else { 1469 assert(MI.getOpcode() == TargetOpcode::G_ASHR); 1470 auto Hi = Builder.buildAShr( 1471 HalfTy, Unmerge.getReg(1), 1472 Builder.buildConstant(HalfTy, HalfSize - 1)); 1473 1474 if (ShiftVal == HalfSize) { 1475 // (G_ASHR i64:x, 32) -> 1476 // G_MERGE_VALUES hi_32(x), (G_ASHR hi_32(x), 31) 1477 Builder.buildMerge(DstReg, { Unmerge.getReg(1), Hi }); 1478 } else if (ShiftVal == Size - 1) { 1479 // Don't need a second shift. 1480 // (G_ASHR i64:x, 63) -> 1481 // %narrowed = (G_ASHR hi_32(x), 31) 1482 // G_MERGE_VALUES %narrowed, %narrowed 1483 Builder.buildMerge(DstReg, { Hi, Hi }); 1484 } else { 1485 auto Lo = Builder.buildAShr( 1486 HalfTy, Unmerge.getReg(1), 1487 Builder.buildConstant(HalfTy, ShiftVal - HalfSize)); 1488 1489 // (G_ASHR i64:x, C) ->, for C >= 32 1490 // G_MERGE_VALUES (G_ASHR hi_32(x), C - 32), (G_ASHR hi_32(x), 31) 1491 Builder.buildMerge(DstReg, { Lo, Hi }); 1492 } 1493 } 1494 1495 MI.eraseFromParent(); 1496 return true; 1497 } 1498 1499 bool CombinerHelper::tryCombineShiftToUnmerge(MachineInstr &MI, 1500 unsigned TargetShiftAmount) { 1501 unsigned ShiftAmt; 1502 if (matchCombineShiftToUnmerge(MI, TargetShiftAmount, ShiftAmt)) { 1503 applyCombineShiftToUnmerge(MI, ShiftAmt); 1504 return true; 1505 } 1506 1507 return false; 1508 } 1509 1510 bool CombinerHelper::matchAnyExplicitUseIsUndef(MachineInstr &MI) { 1511 return any_of(MI.explicit_uses(), [this](const MachineOperand &MO) { 1512 return MO.isReg() && 1513 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 1514 }); 1515 } 1516 1517 bool CombinerHelper::matchAllExplicitUsesAreUndef(MachineInstr &MI) { 1518 return all_of(MI.explicit_uses(), [this](const MachineOperand &MO) { 1519 return !MO.isReg() || 1520 getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MO.getReg(), MRI); 1521 }); 1522 } 1523 1524 bool CombinerHelper::matchUndefShuffleVectorMask(MachineInstr &MI) { 1525 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR); 1526 ArrayRef<int> Mask = MI.getOperand(3).getShuffleMask(); 1527 return all_of(Mask, [](int Elt) { return Elt < 0; }); 1528 } 1529 1530 bool CombinerHelper::matchUndefStore(MachineInstr &MI) { 1531 assert(MI.getOpcode() == TargetOpcode::G_STORE); 1532 return getOpcodeDef(TargetOpcode::G_IMPLICIT_DEF, MI.getOperand(0).getReg(), 1533 MRI); 1534 } 1535 1536 bool CombinerHelper::eraseInst(MachineInstr &MI) { 1537 MI.eraseFromParent(); 1538 return true; 1539 } 1540 1541 bool CombinerHelper::matchEqualDefs(const MachineOperand &MOP1, 1542 const MachineOperand &MOP2) { 1543 if (!MOP1.isReg() || !MOP2.isReg()) 1544 return false; 1545 MachineInstr *I1 = getDefIgnoringCopies(MOP1.getReg(), MRI); 1546 if (!I1) 1547 return false; 1548 MachineInstr *I2 = getDefIgnoringCopies(MOP2.getReg(), MRI); 1549 if (!I2) 1550 return false; 1551 1552 // Handle a case like this: 1553 // 1554 // %0:_(s64), %1:_(s64) = G_UNMERGE_VALUES %2:_(<2 x s64>) 1555 // 1556 // Even though %0 and %1 are produced by the same instruction they are not 1557 // the same values. 1558 if (I1 == I2) 1559 return MOP1.getReg() == MOP2.getReg(); 1560 1561 // If we have an instruction which loads or stores, we can't guarantee that 1562 // it is identical. 1563 // 1564 // For example, we may have 1565 // 1566 // %x1 = G_LOAD %addr (load N from @somewhere) 1567 // ... 1568 // call @foo 1569 // ... 1570 // %x2 = G_LOAD %addr (load N from @somewhere) 1571 // ... 1572 // %or = G_OR %x1, %x2 1573 // 1574 // It's possible that @foo will modify whatever lives at the address we're 1575 // loading from. To be safe, let's just assume that all loads and stores 1576 // are different (unless we have something which is guaranteed to not 1577 // change.) 1578 if (I1->mayLoadOrStore() && !I1->isDereferenceableInvariantLoad(nullptr)) 1579 return false; 1580 1581 // Check for physical registers on the instructions first to avoid cases 1582 // like this: 1583 // 1584 // %a = COPY $physreg 1585 // ... 1586 // SOMETHING implicit-def $physreg 1587 // ... 1588 // %b = COPY $physreg 1589 // 1590 // These copies are not equivalent. 1591 if (any_of(I1->uses(), [](const MachineOperand &MO) { 1592 return MO.isReg() && MO.getReg().isPhysical(); 1593 })) { 1594 // Check if we have a case like this: 1595 // 1596 // %a = COPY $physreg 1597 // %b = COPY %a 1598 // 1599 // In this case, I1 and I2 will both be equal to %a = COPY $physreg. 1600 // From that, we know that they must have the same value, since they must 1601 // have come from the same COPY. 1602 return I1->isIdenticalTo(*I2); 1603 } 1604 1605 // We don't have any physical registers, so we don't necessarily need the 1606 // same vreg defs. 1607 // 1608 // On the off-chance that there's some target instruction feeding into the 1609 // instruction, let's use produceSameValue instead of isIdenticalTo. 1610 return Builder.getTII().produceSameValue(*I1, *I2, &MRI); 1611 } 1612 1613 bool CombinerHelper::matchConstantOp(const MachineOperand &MOP, int64_t C) { 1614 if (!MOP.isReg()) 1615 return false; 1616 int64_t Cst; 1617 return mi_match(MOP.getReg(), MRI, m_ICst(Cst)) && Cst == C; 1618 } 1619 1620 bool CombinerHelper::replaceSingleDefInstWithOperand(MachineInstr &MI, 1621 unsigned OpIdx) { 1622 assert(MI.getNumExplicitDefs() == 1 && "Expected one explicit def?"); 1623 Register OldReg = MI.getOperand(0).getReg(); 1624 Register Replacement = MI.getOperand(OpIdx).getReg(); 1625 assert(canReplaceReg(OldReg, Replacement, MRI) && "Cannot replace register?"); 1626 MI.eraseFromParent(); 1627 replaceRegWith(MRI, OldReg, Replacement); 1628 return true; 1629 } 1630 1631 bool CombinerHelper::matchSelectSameVal(MachineInstr &MI) { 1632 assert(MI.getOpcode() == TargetOpcode::G_SELECT); 1633 // Match (cond ? x : x) 1634 return matchEqualDefs(MI.getOperand(2), MI.getOperand(3)) && 1635 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(2).getReg(), 1636 MRI); 1637 } 1638 1639 bool CombinerHelper::matchBinOpSameVal(MachineInstr &MI) { 1640 return matchEqualDefs(MI.getOperand(1), MI.getOperand(2)) && 1641 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(), 1642 MRI); 1643 } 1644 1645 bool CombinerHelper::matchOperandIsZero(MachineInstr &MI, unsigned OpIdx) { 1646 return matchConstantOp(MI.getOperand(OpIdx), 0) && 1647 canReplaceReg(MI.getOperand(0).getReg(), MI.getOperand(OpIdx).getReg(), 1648 MRI); 1649 } 1650 1651 bool CombinerHelper::replaceInstWithFConstant(MachineInstr &MI, double C) { 1652 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 1653 Builder.setInstr(MI); 1654 Builder.buildFConstant(MI.getOperand(0), C); 1655 MI.eraseFromParent(); 1656 return true; 1657 } 1658 1659 bool CombinerHelper::replaceInstWithConstant(MachineInstr &MI, int64_t C) { 1660 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 1661 Builder.setInstr(MI); 1662 Builder.buildConstant(MI.getOperand(0), C); 1663 MI.eraseFromParent(); 1664 return true; 1665 } 1666 1667 bool CombinerHelper::replaceInstWithUndef(MachineInstr &MI) { 1668 assert(MI.getNumDefs() == 1 && "Expected only one def?"); 1669 Builder.setInstr(MI); 1670 Builder.buildUndef(MI.getOperand(0)); 1671 MI.eraseFromParent(); 1672 return true; 1673 } 1674 1675 bool CombinerHelper::tryCombine(MachineInstr &MI) { 1676 if (tryCombineCopy(MI)) 1677 return true; 1678 if (tryCombineExtendingLoads(MI)) 1679 return true; 1680 if (tryCombineIndexedLoadStore(MI)) 1681 return true; 1682 return false; 1683 } 1684