1 //===- PeepholeOptimizer.cpp - Peephole Optimizations ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Perform peephole optimizations on the machine code: 10 // 11 // - Optimize Extensions 12 // 13 // Optimization of sign / zero extension instructions. It may be extended to 14 // handle other instructions with similar properties. 15 // 16 // On some targets, some instructions, e.g. X86 sign / zero extension, may 17 // leave the source value in the lower part of the result. This optimization 18 // will replace some uses of the pre-extension value with uses of the 19 // sub-register of the results. 20 // 21 // - Optimize Comparisons 22 // 23 // Optimization of comparison instructions. For instance, in this code: 24 // 25 // sub r1, 1 26 // cmp r1, 0 27 // bz L1 28 // 29 // If the "sub" instruction all ready sets (or could be modified to set) the 30 // same flag that the "cmp" instruction sets and that "bz" uses, then we can 31 // eliminate the "cmp" instruction. 32 // 33 // Another instance, in this code: 34 // 35 // sub r1, r3 | sub r1, imm 36 // cmp r3, r1 or cmp r1, r3 | cmp r1, imm 37 // bge L1 38 // 39 // If the branch instruction can use flag from "sub", then we can replace 40 // "sub" with "subs" and eliminate the "cmp" instruction. 41 // 42 // - Optimize Loads: 43 // 44 // Loads that can be folded into a later instruction. A load is foldable 45 // if it loads to virtual registers and the virtual register defined has 46 // a single use. 47 // 48 // - Optimize Copies and Bitcast (more generally, target specific copies): 49 // 50 // Rewrite copies and bitcasts to avoid cross register bank copies 51 // when possible. 52 // E.g., Consider the following example, where capital and lower 53 // letters denote different register file: 54 // b = copy A <-- cross-bank copy 55 // C = copy b <-- cross-bank copy 56 // => 57 // b = copy A <-- cross-bank copy 58 // C = copy A <-- same-bank copy 59 // 60 // E.g., for bitcast: 61 // b = bitcast A <-- cross-bank copy 62 // C = bitcast b <-- cross-bank copy 63 // => 64 // b = bitcast A <-- cross-bank copy 65 // C = copy A <-- same-bank copy 66 //===----------------------------------------------------------------------===// 67 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/SmallPtrSet.h" 70 #include "llvm/ADT/SmallSet.h" 71 #include "llvm/ADT/SmallVector.h" 72 #include "llvm/ADT/Statistic.h" 73 #include "llvm/CodeGen/MachineBasicBlock.h" 74 #include "llvm/CodeGen/MachineDominators.h" 75 #include "llvm/CodeGen/MachineFunction.h" 76 #include "llvm/CodeGen/MachineFunctionPass.h" 77 #include "llvm/CodeGen/MachineInstr.h" 78 #include "llvm/CodeGen/MachineInstrBuilder.h" 79 #include "llvm/CodeGen/MachineLoopInfo.h" 80 #include "llvm/CodeGen/MachineOperand.h" 81 #include "llvm/CodeGen/MachineRegisterInfo.h" 82 #include "llvm/CodeGen/TargetInstrInfo.h" 83 #include "llvm/CodeGen/TargetOpcodes.h" 84 #include "llvm/CodeGen/TargetRegisterInfo.h" 85 #include "llvm/CodeGen/TargetSubtargetInfo.h" 86 #include "llvm/InitializePasses.h" 87 #include "llvm/MC/LaneBitmask.h" 88 #include "llvm/MC/MCInstrDesc.h" 89 #include "llvm/Pass.h" 90 #include "llvm/Support/CommandLine.h" 91 #include "llvm/Support/Debug.h" 92 #include "llvm/Support/raw_ostream.h" 93 #include <cassert> 94 #include <cstdint> 95 #include <memory> 96 #include <utility> 97 98 using namespace llvm; 99 using RegSubRegPair = TargetInstrInfo::RegSubRegPair; 100 using RegSubRegPairAndIdx = TargetInstrInfo::RegSubRegPairAndIdx; 101 102 #define DEBUG_TYPE "peephole-opt" 103 104 // Optimize Extensions 105 static cl::opt<bool> 106 Aggressive("aggressive-ext-opt", cl::Hidden, 107 cl::desc("Aggressive extension optimization")); 108 109 static cl::opt<bool> 110 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false), 111 cl::desc("Disable the peephole optimizer")); 112 113 /// Specifiy whether or not the value tracking looks through 114 /// complex instructions. When this is true, the value tracker 115 /// bails on everything that is not a copy or a bitcast. 116 static cl::opt<bool> 117 DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false), 118 cl::desc("Disable advanced copy optimization")); 119 120 static cl::opt<bool> DisableNAPhysCopyOpt( 121 "disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false), 122 cl::desc("Disable non-allocatable physical register copy optimization")); 123 124 // Limit the number of PHI instructions to process 125 // in PeepholeOptimizer::getNextSource. 126 static cl::opt<unsigned> RewritePHILimit( 127 "rewrite-phi-limit", cl::Hidden, cl::init(10), 128 cl::desc("Limit the length of PHI chains to lookup")); 129 130 // Limit the length of recurrence chain when evaluating the benefit of 131 // commuting operands. 132 static cl::opt<unsigned> MaxRecurrenceChain( 133 "recurrence-chain-limit", cl::Hidden, cl::init(3), 134 cl::desc("Maximum length of recurrence chain when evaluating the benefit " 135 "of commuting operands")); 136 137 138 STATISTIC(NumReuse, "Number of extension results reused"); 139 STATISTIC(NumCmps, "Number of compares eliminated"); 140 STATISTIC(NumImmFold, "Number of move immediate folded"); 141 STATISTIC(NumLoadFold, "Number of loads folded"); 142 STATISTIC(NumSelects, "Number of selects optimized"); 143 STATISTIC(NumUncoalescableCopies, "Number of uncoalescable copies optimized"); 144 STATISTIC(NumRewrittenCopies, "Number of copies rewritten"); 145 STATISTIC(NumNAPhysCopies, "Number of non-allocatable physical copies removed"); 146 147 namespace { 148 149 class ValueTrackerResult; 150 class RecurrenceInstr; 151 152 class PeepholeOptimizer : public MachineFunctionPass, 153 private MachineFunction::Delegate { 154 const TargetInstrInfo *TII = nullptr; 155 const TargetRegisterInfo *TRI = nullptr; 156 MachineRegisterInfo *MRI = nullptr; 157 MachineDominatorTree *DT = nullptr; // Machine dominator tree 158 MachineLoopInfo *MLI = nullptr; 159 160 public: 161 static char ID; // Pass identification 162 163 PeepholeOptimizer() : MachineFunctionPass(ID) { 164 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry()); 165 } 166 167 bool runOnMachineFunction(MachineFunction &MF) override; 168 169 void getAnalysisUsage(AnalysisUsage &AU) const override { 170 AU.setPreservesCFG(); 171 MachineFunctionPass::getAnalysisUsage(AU); 172 AU.addRequired<MachineLoopInfoWrapperPass>(); 173 AU.addPreserved<MachineLoopInfoWrapperPass>(); 174 if (Aggressive) { 175 AU.addRequired<MachineDominatorTreeWrapperPass>(); 176 AU.addPreserved<MachineDominatorTreeWrapperPass>(); 177 } 178 } 179 180 MachineFunctionProperties getRequiredProperties() const override { 181 return MachineFunctionProperties() 182 .set(MachineFunctionProperties::Property::IsSSA); 183 } 184 185 /// Track Def -> Use info used for rewriting copies. 186 using RewriteMapTy = SmallDenseMap<RegSubRegPair, ValueTrackerResult>; 187 188 /// Sequence of instructions that formulate recurrence cycle. 189 using RecurrenceCycle = SmallVector<RecurrenceInstr, 4>; 190 191 private: 192 bool optimizeCmpInstr(MachineInstr &MI); 193 bool optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB, 194 SmallPtrSetImpl<MachineInstr*> &LocalMIs); 195 bool optimizeSelect(MachineInstr &MI, 196 SmallPtrSetImpl<MachineInstr *> &LocalMIs); 197 bool optimizeCondBranch(MachineInstr &MI); 198 bool optimizeCoalescableCopy(MachineInstr &MI); 199 bool optimizeUncoalescableCopy(MachineInstr &MI, 200 SmallPtrSetImpl<MachineInstr *> &LocalMIs); 201 bool optimizeRecurrence(MachineInstr &PHI); 202 bool findNextSource(RegSubRegPair RegSubReg, RewriteMapTy &RewriteMap); 203 bool isMoveImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs, 204 DenseMap<Register, MachineInstr *> &ImmDefMIs); 205 bool foldImmediate(MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs, 206 DenseMap<Register, MachineInstr *> &ImmDefMIs, 207 bool &Deleted); 208 209 /// Finds recurrence cycles, but only ones that formulated around 210 /// a def operand and a use operand that are tied. If there is a use 211 /// operand commutable with the tied use operand, find recurrence cycle 212 /// along that operand as well. 213 bool findTargetRecurrence(Register Reg, 214 const SmallSet<Register, 2> &TargetReg, 215 RecurrenceCycle &RC); 216 217 /// If copy instruction \p MI is a virtual register copy or a copy of a 218 /// constant physical register to a virtual register, track it in the 219 /// set CopySrcMIs. If this virtual register was previously seen as a 220 /// copy, replace the uses of this copy with the previously seen copy's 221 /// destination register. 222 bool foldRedundantCopy(MachineInstr &MI); 223 224 /// Is the register \p Reg a non-allocatable physical register? 225 bool isNAPhysCopy(Register Reg); 226 227 /// If copy instruction \p MI is a non-allocatable virtual<->physical 228 /// register copy, track it in the \p NAPhysToVirtMIs map. If this 229 /// non-allocatable physical register was previously copied to a virtual 230 /// registered and hasn't been clobbered, the virt->phys copy can be 231 /// deleted. 232 bool foldRedundantNAPhysCopy( 233 MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs); 234 235 bool isLoadFoldable(MachineInstr &MI, 236 SmallSet<Register, 16> &FoldAsLoadDefCandidates); 237 238 /// Check whether \p MI is understood by the register coalescer 239 /// but may require some rewriting. 240 bool isCoalescableCopy(const MachineInstr &MI) { 241 // SubregToRegs are not interesting, because they are already register 242 // coalescer friendly. 243 return MI.isCopy() || (!DisableAdvCopyOpt && 244 (MI.isRegSequence() || MI.isInsertSubreg() || 245 MI.isExtractSubreg())); 246 } 247 248 /// Check whether \p MI is a copy like instruction that is 249 /// not recognized by the register coalescer. 250 bool isUncoalescableCopy(const MachineInstr &MI) { 251 return MI.isBitcast() || 252 (!DisableAdvCopyOpt && 253 (MI.isRegSequenceLike() || MI.isInsertSubregLike() || 254 MI.isExtractSubregLike())); 255 } 256 257 MachineInstr &rewriteSource(MachineInstr &CopyLike, 258 RegSubRegPair Def, RewriteMapTy &RewriteMap); 259 260 // Set of copies to virtual registers keyed by source register. Never 261 // holds any physreg which requires def tracking. 262 DenseMap<RegSubRegPair, MachineInstr *> CopySrcMIs; 263 264 // MachineFunction::Delegate implementation. Used to maintain CopySrcMIs. 265 void MF_HandleInsertion(MachineInstr &MI) override { 266 return; 267 } 268 269 bool getCopySrc(MachineInstr &MI, RegSubRegPair &SrcPair) { 270 if (!MI.isCopy()) 271 return false; 272 273 Register SrcReg = MI.getOperand(1).getReg(); 274 unsigned SrcSubReg = MI.getOperand(1).getSubReg(); 275 if (!SrcReg.isVirtual() && !MRI->isConstantPhysReg(SrcReg)) 276 return false; 277 278 SrcPair = RegSubRegPair(SrcReg, SrcSubReg); 279 return true; 280 } 281 282 // If a COPY instruction is to be deleted or changed, we should also remove 283 // it from CopySrcMIs. 284 void deleteChangedCopy(MachineInstr &MI) { 285 RegSubRegPair SrcPair; 286 if (!getCopySrc(MI, SrcPair)) 287 return; 288 289 auto It = CopySrcMIs.find(SrcPair); 290 if (It != CopySrcMIs.end() && It->second == &MI) 291 CopySrcMIs.erase(It); 292 } 293 294 void MF_HandleRemoval(MachineInstr &MI) override { 295 deleteChangedCopy(MI); 296 } 297 298 void MF_HandleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID) override 299 { 300 deleteChangedCopy(MI); 301 } 302 }; 303 304 /// Helper class to hold instructions that are inside recurrence cycles. 305 /// The recurrence cycle is formulated around 1) a def operand and its 306 /// tied use operand, or 2) a def operand and a use operand that is commutable 307 /// with another use operand which is tied to the def operand. In the latter 308 /// case, index of the tied use operand and the commutable use operand are 309 /// maintained with CommutePair. 310 class RecurrenceInstr { 311 public: 312 using IndexPair = std::pair<unsigned, unsigned>; 313 314 RecurrenceInstr(MachineInstr *MI) : MI(MI) {} 315 RecurrenceInstr(MachineInstr *MI, unsigned Idx1, unsigned Idx2) 316 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {} 317 318 MachineInstr *getMI() const { return MI; } 319 std::optional<IndexPair> getCommutePair() const { return CommutePair; } 320 321 private: 322 MachineInstr *MI; 323 std::optional<IndexPair> CommutePair; 324 }; 325 326 /// Helper class to hold a reply for ValueTracker queries. 327 /// Contains the returned sources for a given search and the instructions 328 /// where the sources were tracked from. 329 class ValueTrackerResult { 330 private: 331 /// Track all sources found by one ValueTracker query. 332 SmallVector<RegSubRegPair, 2> RegSrcs; 333 334 /// Instruction using the sources in 'RegSrcs'. 335 const MachineInstr *Inst = nullptr; 336 337 public: 338 ValueTrackerResult() = default; 339 340 ValueTrackerResult(Register Reg, unsigned SubReg) { 341 addSource(Reg, SubReg); 342 } 343 344 bool isValid() const { return getNumSources() > 0; } 345 346 void setInst(const MachineInstr *I) { Inst = I; } 347 const MachineInstr *getInst() const { return Inst; } 348 349 void clear() { 350 RegSrcs.clear(); 351 Inst = nullptr; 352 } 353 354 void addSource(Register SrcReg, unsigned SrcSubReg) { 355 RegSrcs.push_back(RegSubRegPair(SrcReg, SrcSubReg)); 356 } 357 358 void setSource(int Idx, Register SrcReg, unsigned SrcSubReg) { 359 assert(Idx < getNumSources() && "Reg pair source out of index"); 360 RegSrcs[Idx] = RegSubRegPair(SrcReg, SrcSubReg); 361 } 362 363 int getNumSources() const { return RegSrcs.size(); } 364 365 RegSubRegPair getSrc(int Idx) const { 366 return RegSrcs[Idx]; 367 } 368 369 Register getSrcReg(int Idx) const { 370 assert(Idx < getNumSources() && "Reg source out of index"); 371 return RegSrcs[Idx].Reg; 372 } 373 374 unsigned getSrcSubReg(int Idx) const { 375 assert(Idx < getNumSources() && "SubReg source out of index"); 376 return RegSrcs[Idx].SubReg; 377 } 378 379 bool operator==(const ValueTrackerResult &Other) const { 380 if (Other.getInst() != getInst()) 381 return false; 382 383 if (Other.getNumSources() != getNumSources()) 384 return false; 385 386 for (int i = 0, e = Other.getNumSources(); i != e; ++i) 387 if (Other.getSrcReg(i) != getSrcReg(i) || 388 Other.getSrcSubReg(i) != getSrcSubReg(i)) 389 return false; 390 return true; 391 } 392 }; 393 394 /// Helper class to track the possible sources of a value defined by 395 /// a (chain of) copy related instructions. 396 /// Given a definition (instruction and definition index), this class 397 /// follows the use-def chain to find successive suitable sources. 398 /// The given source can be used to rewrite the definition into 399 /// def = COPY src. 400 /// 401 /// For instance, let us consider the following snippet: 402 /// v0 = 403 /// v2 = INSERT_SUBREG v1, v0, sub0 404 /// def = COPY v2.sub0 405 /// 406 /// Using a ValueTracker for def = COPY v2.sub0 will give the following 407 /// suitable sources: 408 /// v2.sub0 and v0. 409 /// Then, def can be rewritten into def = COPY v0. 410 class ValueTracker { 411 private: 412 /// The current point into the use-def chain. 413 const MachineInstr *Def = nullptr; 414 415 /// The index of the definition in Def. 416 unsigned DefIdx = 0; 417 418 /// The sub register index of the definition. 419 unsigned DefSubReg; 420 421 /// The register where the value can be found. 422 Register Reg; 423 424 /// MachineRegisterInfo used to perform tracking. 425 const MachineRegisterInfo &MRI; 426 427 /// Optional TargetInstrInfo used to perform some complex tracking. 428 const TargetInstrInfo *TII; 429 430 /// Dispatcher to the right underlying implementation of getNextSource. 431 ValueTrackerResult getNextSourceImpl(); 432 433 /// Specialized version of getNextSource for Copy instructions. 434 ValueTrackerResult getNextSourceFromCopy(); 435 436 /// Specialized version of getNextSource for Bitcast instructions. 437 ValueTrackerResult getNextSourceFromBitcast(); 438 439 /// Specialized version of getNextSource for RegSequence instructions. 440 ValueTrackerResult getNextSourceFromRegSequence(); 441 442 /// Specialized version of getNextSource for InsertSubreg instructions. 443 ValueTrackerResult getNextSourceFromInsertSubreg(); 444 445 /// Specialized version of getNextSource for ExtractSubreg instructions. 446 ValueTrackerResult getNextSourceFromExtractSubreg(); 447 448 /// Specialized version of getNextSource for SubregToReg instructions. 449 ValueTrackerResult getNextSourceFromSubregToReg(); 450 451 /// Specialized version of getNextSource for PHI instructions. 452 ValueTrackerResult getNextSourceFromPHI(); 453 454 public: 455 /// Create a ValueTracker instance for the value defined by \p Reg. 456 /// \p DefSubReg represents the sub register index the value tracker will 457 /// track. It does not need to match the sub register index used in the 458 /// definition of \p Reg. 459 /// If \p Reg is a physical register, a value tracker constructed with 460 /// this constructor will not find any alternative source. 461 /// Indeed, when \p Reg is a physical register that constructor does not 462 /// know which definition of \p Reg it should track. 463 /// Use the next constructor to track a physical register. 464 ValueTracker(Register Reg, unsigned DefSubReg, 465 const MachineRegisterInfo &MRI, 466 const TargetInstrInfo *TII = nullptr) 467 : DefSubReg(DefSubReg), Reg(Reg), MRI(MRI), TII(TII) { 468 if (!Reg.isPhysical()) { 469 Def = MRI.getVRegDef(Reg); 470 DefIdx = MRI.def_begin(Reg).getOperandNo(); 471 } 472 } 473 474 /// Following the use-def chain, get the next available source 475 /// for the tracked value. 476 /// \return A ValueTrackerResult containing a set of registers 477 /// and sub registers with tracked values. A ValueTrackerResult with 478 /// an empty set of registers means no source was found. 479 ValueTrackerResult getNextSource(); 480 }; 481 482 } // end anonymous namespace 483 484 char PeepholeOptimizer::ID = 0; 485 486 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID; 487 488 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE, 489 "Peephole Optimizations", false, false) 490 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass) 491 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass) 492 INITIALIZE_PASS_END(PeepholeOptimizer, DEBUG_TYPE, 493 "Peephole Optimizations", false, false) 494 495 /// If instruction is a copy-like instruction, i.e. it reads a single register 496 /// and writes a single register and it does not modify the source, and if the 497 /// source value is preserved as a sub-register of the result, then replace all 498 /// reachable uses of the source with the subreg of the result. 499 /// 500 /// Do not generate an EXTRACT that is used only in a debug use, as this changes 501 /// the code. Since this code does not currently share EXTRACTs, just ignore all 502 /// debug uses. 503 bool PeepholeOptimizer:: 504 optimizeExtInstr(MachineInstr &MI, MachineBasicBlock &MBB, 505 SmallPtrSetImpl<MachineInstr*> &LocalMIs) { 506 Register SrcReg, DstReg; 507 unsigned SubIdx; 508 if (!TII->isCoalescableExtInstr(MI, SrcReg, DstReg, SubIdx)) 509 return false; 510 511 if (DstReg.isPhysical() || SrcReg.isPhysical()) 512 return false; 513 514 if (MRI->hasOneNonDBGUse(SrcReg)) 515 // No other uses. 516 return false; 517 518 // Ensure DstReg can get a register class that actually supports 519 // sub-registers. Don't change the class until we commit. 520 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg); 521 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx); 522 if (!DstRC) 523 return false; 524 525 // The ext instr may be operating on a sub-register of SrcReg as well. 526 // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit 527 // register. 528 // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of 529 // SrcReg:SubIdx should be replaced. 530 bool UseSrcSubIdx = 531 TRI->getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != nullptr; 532 533 // The source has other uses. See if we can replace the other uses with use of 534 // the result of the extension. 535 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs; 536 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg)) 537 ReachedBBs.insert(UI.getParent()); 538 539 // Uses that are in the same BB of uses of the result of the instruction. 540 SmallVector<MachineOperand*, 8> Uses; 541 542 // Uses that the result of the instruction can reach. 543 SmallVector<MachineOperand*, 8> ExtendedUses; 544 545 bool ExtendLife = true; 546 for (MachineOperand &UseMO : MRI->use_nodbg_operands(SrcReg)) { 547 MachineInstr *UseMI = UseMO.getParent(); 548 if (UseMI == &MI) 549 continue; 550 551 if (UseMI->isPHI()) { 552 ExtendLife = false; 553 continue; 554 } 555 556 // Only accept uses of SrcReg:SubIdx. 557 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx) 558 continue; 559 560 // It's an error to translate this: 561 // 562 // %reg1025 = <sext> %reg1024 563 // ... 564 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4 565 // 566 // into this: 567 // 568 // %reg1025 = <sext> %reg1024 569 // ... 570 // %reg1027 = COPY %reg1025:4 571 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4 572 // 573 // The problem here is that SUBREG_TO_REG is there to assert that an 574 // implicit zext occurs. It doesn't insert a zext instruction. If we allow 575 // the COPY here, it will give us the value after the <sext>, not the 576 // original value of %reg1024 before <sext>. 577 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG) 578 continue; 579 580 MachineBasicBlock *UseMBB = UseMI->getParent(); 581 if (UseMBB == &MBB) { 582 // Local uses that come after the extension. 583 if (!LocalMIs.count(UseMI)) 584 Uses.push_back(&UseMO); 585 } else if (ReachedBBs.count(UseMBB)) { 586 // Non-local uses where the result of the extension is used. Always 587 // replace these unless it's a PHI. 588 Uses.push_back(&UseMO); 589 } else if (Aggressive && DT->dominates(&MBB, UseMBB)) { 590 // We may want to extend the live range of the extension result in order 591 // to replace these uses. 592 ExtendedUses.push_back(&UseMO); 593 } else { 594 // Both will be live out of the def MBB anyway. Don't extend live range of 595 // the extension result. 596 ExtendLife = false; 597 break; 598 } 599 } 600 601 if (ExtendLife && !ExtendedUses.empty()) 602 // Extend the liveness of the extension result. 603 Uses.append(ExtendedUses.begin(), ExtendedUses.end()); 604 605 // Now replace all uses. 606 bool Changed = false; 607 if (!Uses.empty()) { 608 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs; 609 610 // Look for PHI uses of the extended result, we don't want to extend the 611 // liveness of a PHI input. It breaks all kinds of assumptions down 612 // stream. A PHI use is expected to be the kill of its source values. 613 for (MachineInstr &UI : MRI->use_nodbg_instructions(DstReg)) 614 if (UI.isPHI()) 615 PHIBBs.insert(UI.getParent()); 616 617 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 618 for (MachineOperand *UseMO : Uses) { 619 MachineInstr *UseMI = UseMO->getParent(); 620 MachineBasicBlock *UseMBB = UseMI->getParent(); 621 if (PHIBBs.count(UseMBB)) 622 continue; 623 624 // About to add uses of DstReg, clear DstReg's kill flags. 625 if (!Changed) { 626 MRI->clearKillFlags(DstReg); 627 MRI->constrainRegClass(DstReg, DstRC); 628 } 629 630 // SubReg defs are illegal in machine SSA phase, 631 // we should not generate SubReg defs. 632 // 633 // For example, for the instructions: 634 // 635 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc 636 // %3:gprc_and_gprc_nor0 = COPY %0.sub_32:g8rc 637 // 638 // We should generate: 639 // 640 // %1:g8rc_and_g8rc_nox0 = EXTSW %0:g8rc 641 // %6:gprc_and_gprc_nor0 = COPY %1.sub_32:g8rc_and_g8rc_nox0 642 // %3:gprc_and_gprc_nor0 = COPY %6:gprc_and_gprc_nor0 643 // 644 if (UseSrcSubIdx) 645 RC = MRI->getRegClass(UseMI->getOperand(0).getReg()); 646 647 Register NewVR = MRI->createVirtualRegister(RC); 648 BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(), 649 TII->get(TargetOpcode::COPY), NewVR) 650 .addReg(DstReg, 0, SubIdx); 651 if (UseSrcSubIdx) 652 UseMO->setSubReg(0); 653 654 UseMO->setReg(NewVR); 655 ++NumReuse; 656 Changed = true; 657 } 658 } 659 660 return Changed; 661 } 662 663 /// If the instruction is a compare and the previous instruction it's comparing 664 /// against already sets (or could be modified to set) the same flag as the 665 /// compare, then we can remove the comparison and use the flag from the 666 /// previous instruction. 667 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr &MI) { 668 // If this instruction is a comparison against zero and isn't comparing a 669 // physical register, we can try to optimize it. 670 Register SrcReg, SrcReg2; 671 int64_t CmpMask, CmpValue; 672 if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) || 673 SrcReg.isPhysical() || SrcReg2.isPhysical()) 674 return false; 675 676 // Attempt to optimize the comparison instruction. 677 LLVM_DEBUG(dbgs() << "Attempting to optimize compare: " << MI); 678 if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) { 679 LLVM_DEBUG(dbgs() << " -> Successfully optimized compare!\n"); 680 ++NumCmps; 681 return true; 682 } 683 684 return false; 685 } 686 687 /// Optimize a select instruction. 688 bool PeepholeOptimizer::optimizeSelect(MachineInstr &MI, 689 SmallPtrSetImpl<MachineInstr *> &LocalMIs) { 690 unsigned TrueOp = 0; 691 unsigned FalseOp = 0; 692 bool Optimizable = false; 693 SmallVector<MachineOperand, 4> Cond; 694 if (TII->analyzeSelect(MI, Cond, TrueOp, FalseOp, Optimizable)) 695 return false; 696 if (!Optimizable) 697 return false; 698 if (!TII->optimizeSelect(MI, LocalMIs)) 699 return false; 700 LLVM_DEBUG(dbgs() << "Deleting select: " << MI); 701 MI.eraseFromParent(); 702 ++NumSelects; 703 return true; 704 } 705 706 /// Check if a simpler conditional branch can be generated. 707 bool PeepholeOptimizer::optimizeCondBranch(MachineInstr &MI) { 708 return TII->optimizeCondBranch(MI); 709 } 710 711 /// Try to find the next source that share the same register file 712 /// for the value defined by \p Reg and \p SubReg. 713 /// When true is returned, the \p RewriteMap can be used by the client to 714 /// retrieve all Def -> Use along the way up to the next source. Any found 715 /// Use that is not itself a key for another entry, is the next source to 716 /// use. During the search for the next source, multiple sources can be found 717 /// given multiple incoming sources of a PHI instruction. In this case, we 718 /// look in each PHI source for the next source; all found next sources must 719 /// share the same register file as \p Reg and \p SubReg. The client should 720 /// then be capable to rewrite all intermediate PHIs to get the next source. 721 /// \return False if no alternative sources are available. True otherwise. 722 bool PeepholeOptimizer::findNextSource(RegSubRegPair RegSubReg, 723 RewriteMapTy &RewriteMap) { 724 // Do not try to find a new source for a physical register. 725 // So far we do not have any motivating example for doing that. 726 // Thus, instead of maintaining untested code, we will revisit that if 727 // that changes at some point. 728 Register Reg = RegSubReg.Reg; 729 if (Reg.isPhysical()) 730 return false; 731 const TargetRegisterClass *DefRC = MRI->getRegClass(Reg); 732 733 SmallVector<RegSubRegPair, 4> SrcToLook; 734 RegSubRegPair CurSrcPair = RegSubReg; 735 SrcToLook.push_back(CurSrcPair); 736 737 unsigned PHICount = 0; 738 do { 739 CurSrcPair = SrcToLook.pop_back_val(); 740 // As explained above, do not handle physical registers 741 if (CurSrcPair.Reg.isPhysical()) 742 return false; 743 744 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI, TII); 745 746 // Follow the chain of copies until we find a more suitable source, a phi 747 // or have to abort. 748 while (true) { 749 ValueTrackerResult Res = ValTracker.getNextSource(); 750 // Abort at the end of a chain (without finding a suitable source). 751 if (!Res.isValid()) 752 return false; 753 754 // Insert the Def -> Use entry for the recently found source. 755 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair); 756 if (CurSrcRes.isValid()) { 757 assert(CurSrcRes == Res && "ValueTrackerResult found must match"); 758 // An existent entry with multiple sources is a PHI cycle we must avoid. 759 // Otherwise it's an entry with a valid next source we already found. 760 if (CurSrcRes.getNumSources() > 1) { 761 LLVM_DEBUG(dbgs() 762 << "findNextSource: found PHI cycle, aborting...\n"); 763 return false; 764 } 765 break; 766 } 767 RewriteMap.insert(std::make_pair(CurSrcPair, Res)); 768 769 // ValueTrackerResult usually have one source unless it's the result from 770 // a PHI instruction. Add the found PHI edges to be looked up further. 771 unsigned NumSrcs = Res.getNumSources(); 772 if (NumSrcs > 1) { 773 PHICount++; 774 if (PHICount >= RewritePHILimit) { 775 LLVM_DEBUG(dbgs() << "findNextSource: PHI limit reached\n"); 776 return false; 777 } 778 779 for (unsigned i = 0; i < NumSrcs; ++i) 780 SrcToLook.push_back(Res.getSrc(i)); 781 break; 782 } 783 784 CurSrcPair = Res.getSrc(0); 785 // Do not extend the live-ranges of physical registers as they add 786 // constraints to the register allocator. Moreover, if we want to extend 787 // the live-range of a physical register, unlike SSA virtual register, 788 // we will have to check that they aren't redefine before the related use. 789 if (CurSrcPair.Reg.isPhysical()) 790 return false; 791 792 // Keep following the chain if the value isn't any better yet. 793 const TargetRegisterClass *SrcRC = MRI->getRegClass(CurSrcPair.Reg); 794 if (!TRI->shouldRewriteCopySrc(DefRC, RegSubReg.SubReg, SrcRC, 795 CurSrcPair.SubReg)) 796 continue; 797 798 // We currently cannot deal with subreg operands on PHI instructions 799 // (see insertPHI()). 800 if (PHICount > 0 && CurSrcPair.SubReg != 0) 801 continue; 802 803 // We found a suitable source, and are done with this chain. 804 break; 805 } 806 } while (!SrcToLook.empty()); 807 808 // If we did not find a more suitable source, there is nothing to optimize. 809 return CurSrcPair.Reg != Reg; 810 } 811 812 /// Insert a PHI instruction with incoming edges \p SrcRegs that are 813 /// guaranteed to have the same register class. This is necessary whenever we 814 /// successfully traverse a PHI instruction and find suitable sources coming 815 /// from its edges. By inserting a new PHI, we provide a rewritten PHI def 816 /// suitable to be used in a new COPY instruction. 817 static MachineInstr & 818 insertPHI(MachineRegisterInfo &MRI, const TargetInstrInfo &TII, 819 const SmallVectorImpl<RegSubRegPair> &SrcRegs, 820 MachineInstr &OrigPHI) { 821 assert(!SrcRegs.empty() && "No sources to create a PHI instruction?"); 822 823 const TargetRegisterClass *NewRC = MRI.getRegClass(SrcRegs[0].Reg); 824 // NewRC is only correct if no subregisters are involved. findNextSource() 825 // should have rejected those cases already. 826 assert(SrcRegs[0].SubReg == 0 && "should not have subreg operand"); 827 Register NewVR = MRI.createVirtualRegister(NewRC); 828 MachineBasicBlock *MBB = OrigPHI.getParent(); 829 MachineInstrBuilder MIB = BuildMI(*MBB, &OrigPHI, OrigPHI.getDebugLoc(), 830 TII.get(TargetOpcode::PHI), NewVR); 831 832 unsigned MBBOpIdx = 2; 833 for (const RegSubRegPair &RegPair : SrcRegs) { 834 MIB.addReg(RegPair.Reg, 0, RegPair.SubReg); 835 MIB.addMBB(OrigPHI.getOperand(MBBOpIdx).getMBB()); 836 // Since we're extended the lifetime of RegPair.Reg, clear the 837 // kill flags to account for that and make RegPair.Reg reaches 838 // the new PHI. 839 MRI.clearKillFlags(RegPair.Reg); 840 MBBOpIdx += 2; 841 } 842 843 return *MIB; 844 } 845 846 namespace { 847 848 /// Interface to query instructions amenable to copy rewriting. 849 class Rewriter { 850 protected: 851 MachineInstr &CopyLike; 852 unsigned CurrentSrcIdx = 0; ///< The index of the source being rewritten. 853 public: 854 Rewriter(MachineInstr &CopyLike) : CopyLike(CopyLike) {} 855 virtual ~Rewriter() = default; 856 857 /// Get the next rewritable source (SrcReg, SrcSubReg) and 858 /// the related value that it affects (DstReg, DstSubReg). 859 /// A source is considered rewritable if its register class and the 860 /// register class of the related DstReg may not be register 861 /// coalescer friendly. In other words, given a copy-like instruction 862 /// not all the arguments may be returned at rewritable source, since 863 /// some arguments are none to be register coalescer friendly. 864 /// 865 /// Each call of this method moves the current source to the next 866 /// rewritable source. 867 /// For instance, let CopyLike be the instruction to rewrite. 868 /// CopyLike has one definition and one source: 869 /// dst.dstSubIdx = CopyLike src.srcSubIdx. 870 /// 871 /// The first call will give the first rewritable source, i.e., 872 /// the only source this instruction has: 873 /// (SrcReg, SrcSubReg) = (src, srcSubIdx). 874 /// This source defines the whole definition, i.e., 875 /// (DstReg, DstSubReg) = (dst, dstSubIdx). 876 /// 877 /// The second and subsequent calls will return false, as there is only one 878 /// rewritable source. 879 /// 880 /// \return True if a rewritable source has been found, false otherwise. 881 /// The output arguments are valid if and only if true is returned. 882 virtual bool getNextRewritableSource(RegSubRegPair &Src, 883 RegSubRegPair &Dst) = 0; 884 885 /// Rewrite the current source with \p NewReg and \p NewSubReg if possible. 886 /// \return True if the rewriting was possible, false otherwise. 887 virtual bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) = 0; 888 }; 889 890 /// Rewriter for COPY instructions. 891 class CopyRewriter : public Rewriter { 892 public: 893 CopyRewriter(MachineInstr &MI) : Rewriter(MI) { 894 assert(MI.isCopy() && "Expected copy instruction"); 895 } 896 virtual ~CopyRewriter() = default; 897 898 bool getNextRewritableSource(RegSubRegPair &Src, 899 RegSubRegPair &Dst) override { 900 // CurrentSrcIdx > 0 means this function has already been called. 901 if (CurrentSrcIdx > 0) 902 return false; 903 // This is the first call to getNextRewritableSource. 904 // Move the CurrentSrcIdx to remember that we made that call. 905 CurrentSrcIdx = 1; 906 // The rewritable source is the argument. 907 const MachineOperand &MOSrc = CopyLike.getOperand(1); 908 Src = RegSubRegPair(MOSrc.getReg(), MOSrc.getSubReg()); 909 // What we track are the alternative sources of the definition. 910 const MachineOperand &MODef = CopyLike.getOperand(0); 911 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg()); 912 return true; 913 } 914 915 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override { 916 if (CurrentSrcIdx != 1) 917 return false; 918 MachineOperand &MOSrc = CopyLike.getOperand(CurrentSrcIdx); 919 MOSrc.setReg(NewReg); 920 MOSrc.setSubReg(NewSubReg); 921 return true; 922 } 923 }; 924 925 /// Helper class to rewrite uncoalescable copy like instructions 926 /// into new COPY (coalescable friendly) instructions. 927 class UncoalescableRewriter : public Rewriter { 928 unsigned NumDefs; ///< Number of defs in the bitcast. 929 930 public: 931 UncoalescableRewriter(MachineInstr &MI) : Rewriter(MI) { 932 NumDefs = MI.getDesc().getNumDefs(); 933 } 934 935 /// \see See Rewriter::getNextRewritableSource() 936 /// All such sources need to be considered rewritable in order to 937 /// rewrite a uncoalescable copy-like instruction. This method return 938 /// each definition that must be checked if rewritable. 939 bool getNextRewritableSource(RegSubRegPair &Src, 940 RegSubRegPair &Dst) override { 941 // Find the next non-dead definition and continue from there. 942 if (CurrentSrcIdx == NumDefs) 943 return false; 944 945 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) { 946 ++CurrentSrcIdx; 947 if (CurrentSrcIdx == NumDefs) 948 return false; 949 } 950 951 // What we track are the alternative sources of the definition. 952 Src = RegSubRegPair(0, 0); 953 const MachineOperand &MODef = CopyLike.getOperand(CurrentSrcIdx); 954 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg()); 955 956 CurrentSrcIdx++; 957 return true; 958 } 959 960 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override { 961 return false; 962 } 963 }; 964 965 /// Specialized rewriter for INSERT_SUBREG instruction. 966 class InsertSubregRewriter : public Rewriter { 967 public: 968 InsertSubregRewriter(MachineInstr &MI) : Rewriter(MI) { 969 assert(MI.isInsertSubreg() && "Invalid instruction"); 970 } 971 972 /// \see See Rewriter::getNextRewritableSource() 973 /// Here CopyLike has the following form: 974 /// dst = INSERT_SUBREG Src1, Src2.src2SubIdx, subIdx. 975 /// Src1 has the same register class has dst, hence, there is 976 /// nothing to rewrite. 977 /// Src2.src2SubIdx, may not be register coalescer friendly. 978 /// Therefore, the first call to this method returns: 979 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx). 980 /// (DstReg, DstSubReg) = (dst, subIdx). 981 /// 982 /// Subsequence calls will return false. 983 bool getNextRewritableSource(RegSubRegPair &Src, 984 RegSubRegPair &Dst) override { 985 // If we already get the only source we can rewrite, return false. 986 if (CurrentSrcIdx == 2) 987 return false; 988 // We are looking at v2 = INSERT_SUBREG v0, v1, sub0. 989 CurrentSrcIdx = 2; 990 const MachineOperand &MOInsertedReg = CopyLike.getOperand(2); 991 Src = RegSubRegPair(MOInsertedReg.getReg(), MOInsertedReg.getSubReg()); 992 const MachineOperand &MODef = CopyLike.getOperand(0); 993 994 // We want to track something that is compatible with the 995 // partial definition. 996 if (MODef.getSubReg()) 997 // Bail if we have to compose sub-register indices. 998 return false; 999 Dst = RegSubRegPair(MODef.getReg(), 1000 (unsigned)CopyLike.getOperand(3).getImm()); 1001 return true; 1002 } 1003 1004 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override { 1005 if (CurrentSrcIdx != 2) 1006 return false; 1007 // We are rewriting the inserted reg. 1008 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx); 1009 MO.setReg(NewReg); 1010 MO.setSubReg(NewSubReg); 1011 return true; 1012 } 1013 }; 1014 1015 /// Specialized rewriter for EXTRACT_SUBREG instruction. 1016 class ExtractSubregRewriter : public Rewriter { 1017 const TargetInstrInfo &TII; 1018 1019 public: 1020 ExtractSubregRewriter(MachineInstr &MI, const TargetInstrInfo &TII) 1021 : Rewriter(MI), TII(TII) { 1022 assert(MI.isExtractSubreg() && "Invalid instruction"); 1023 } 1024 1025 /// \see Rewriter::getNextRewritableSource() 1026 /// Here CopyLike has the following form: 1027 /// dst.dstSubIdx = EXTRACT_SUBREG Src, subIdx. 1028 /// There is only one rewritable source: Src.subIdx, 1029 /// which defines dst.dstSubIdx. 1030 bool getNextRewritableSource(RegSubRegPair &Src, 1031 RegSubRegPair &Dst) override { 1032 // If we already get the only source we can rewrite, return false. 1033 if (CurrentSrcIdx == 1) 1034 return false; 1035 // We are looking at v1 = EXTRACT_SUBREG v0, sub0. 1036 CurrentSrcIdx = 1; 1037 const MachineOperand &MOExtractedReg = CopyLike.getOperand(1); 1038 // If we have to compose sub-register indices, bail out. 1039 if (MOExtractedReg.getSubReg()) 1040 return false; 1041 1042 Src = RegSubRegPair(MOExtractedReg.getReg(), 1043 CopyLike.getOperand(2).getImm()); 1044 1045 // We want to track something that is compatible with the definition. 1046 const MachineOperand &MODef = CopyLike.getOperand(0); 1047 Dst = RegSubRegPair(MODef.getReg(), MODef.getSubReg()); 1048 return true; 1049 } 1050 1051 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override { 1052 // The only source we can rewrite is the input register. 1053 if (CurrentSrcIdx != 1) 1054 return false; 1055 1056 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg); 1057 1058 // If we find a source that does not require to extract something, 1059 // rewrite the operation with a copy. 1060 if (!NewSubReg) { 1061 // Move the current index to an invalid position. 1062 // We do not want another call to this method to be able 1063 // to do any change. 1064 CurrentSrcIdx = -1; 1065 // Rewrite the operation as a COPY. 1066 // Get rid of the sub-register index. 1067 CopyLike.removeOperand(2); 1068 // Morph the operation into a COPY. 1069 CopyLike.setDesc(TII.get(TargetOpcode::COPY)); 1070 return true; 1071 } 1072 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg); 1073 return true; 1074 } 1075 }; 1076 1077 /// Specialized rewriter for REG_SEQUENCE instruction. 1078 class RegSequenceRewriter : public Rewriter { 1079 public: 1080 RegSequenceRewriter(MachineInstr &MI) : Rewriter(MI) { 1081 assert(MI.isRegSequence() && "Invalid instruction"); 1082 } 1083 1084 /// \see Rewriter::getNextRewritableSource() 1085 /// Here CopyLike has the following form: 1086 /// dst = REG_SEQUENCE Src1.src1SubIdx, subIdx1, Src2.src2SubIdx, subIdx2. 1087 /// Each call will return a different source, walking all the available 1088 /// source. 1089 /// 1090 /// The first call returns: 1091 /// (SrcReg, SrcSubReg) = (Src1, src1SubIdx). 1092 /// (DstReg, DstSubReg) = (dst, subIdx1). 1093 /// 1094 /// The second call returns: 1095 /// (SrcReg, SrcSubReg) = (Src2, src2SubIdx). 1096 /// (DstReg, DstSubReg) = (dst, subIdx2). 1097 /// 1098 /// And so on, until all the sources have been traversed, then 1099 /// it returns false. 1100 bool getNextRewritableSource(RegSubRegPair &Src, 1101 RegSubRegPair &Dst) override { 1102 // We are looking at v0 = REG_SEQUENCE v1, sub1, v2, sub2, etc. 1103 1104 // If this is the first call, move to the first argument. 1105 if (CurrentSrcIdx == 0) { 1106 CurrentSrcIdx = 1; 1107 } else { 1108 // Otherwise, move to the next argument and check that it is valid. 1109 CurrentSrcIdx += 2; 1110 if (CurrentSrcIdx >= CopyLike.getNumOperands()) 1111 return false; 1112 } 1113 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx); 1114 Src.Reg = MOInsertedReg.getReg(); 1115 // If we have to compose sub-register indices, bail out. 1116 if ((Src.SubReg = MOInsertedReg.getSubReg())) 1117 return false; 1118 1119 // We want to track something that is compatible with the related 1120 // partial definition. 1121 Dst.SubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm(); 1122 1123 const MachineOperand &MODef = CopyLike.getOperand(0); 1124 Dst.Reg = MODef.getReg(); 1125 // If we have to compose sub-registers, bail. 1126 return MODef.getSubReg() == 0; 1127 } 1128 1129 bool RewriteCurrentSource(Register NewReg, unsigned NewSubReg) override { 1130 // We cannot rewrite out of bound operands. 1131 // Moreover, rewritable sources are at odd positions. 1132 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands()) 1133 return false; 1134 1135 MachineOperand &MO = CopyLike.getOperand(CurrentSrcIdx); 1136 MO.setReg(NewReg); 1137 MO.setSubReg(NewSubReg); 1138 return true; 1139 } 1140 }; 1141 1142 } // end anonymous namespace 1143 1144 /// Get the appropriated Rewriter for \p MI. 1145 /// \return A pointer to a dynamically allocated Rewriter or nullptr if no 1146 /// rewriter works for \p MI. 1147 static Rewriter *getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII) { 1148 // Handle uncoalescable copy-like instructions. 1149 if (MI.isBitcast() || MI.isRegSequenceLike() || MI.isInsertSubregLike() || 1150 MI.isExtractSubregLike()) 1151 return new UncoalescableRewriter(MI); 1152 1153 switch (MI.getOpcode()) { 1154 default: 1155 return nullptr; 1156 case TargetOpcode::COPY: 1157 return new CopyRewriter(MI); 1158 case TargetOpcode::INSERT_SUBREG: 1159 return new InsertSubregRewriter(MI); 1160 case TargetOpcode::EXTRACT_SUBREG: 1161 return new ExtractSubregRewriter(MI, TII); 1162 case TargetOpcode::REG_SEQUENCE: 1163 return new RegSequenceRewriter(MI); 1164 } 1165 } 1166 1167 /// Given a \p Def.Reg and Def.SubReg pair, use \p RewriteMap to find 1168 /// the new source to use for rewrite. If \p HandleMultipleSources is true and 1169 /// multiple sources for a given \p Def are found along the way, we found a 1170 /// PHI instructions that needs to be rewritten. 1171 /// TODO: HandleMultipleSources should be removed once we test PHI handling 1172 /// with coalescable copies. 1173 static RegSubRegPair 1174 getNewSource(MachineRegisterInfo *MRI, const TargetInstrInfo *TII, 1175 RegSubRegPair Def, 1176 const PeepholeOptimizer::RewriteMapTy &RewriteMap, 1177 bool HandleMultipleSources = true) { 1178 RegSubRegPair LookupSrc(Def.Reg, Def.SubReg); 1179 while (true) { 1180 ValueTrackerResult Res = RewriteMap.lookup(LookupSrc); 1181 // If there are no entries on the map, LookupSrc is the new source. 1182 if (!Res.isValid()) 1183 return LookupSrc; 1184 1185 // There's only one source for this definition, keep searching... 1186 unsigned NumSrcs = Res.getNumSources(); 1187 if (NumSrcs == 1) { 1188 LookupSrc.Reg = Res.getSrcReg(0); 1189 LookupSrc.SubReg = Res.getSrcSubReg(0); 1190 continue; 1191 } 1192 1193 // TODO: Remove once multiple srcs w/ coalescable copies are supported. 1194 if (!HandleMultipleSources) 1195 break; 1196 1197 // Multiple sources, recurse into each source to find a new source 1198 // for it. Then, rewrite the PHI accordingly to its new edges. 1199 SmallVector<RegSubRegPair, 4> NewPHISrcs; 1200 for (unsigned i = 0; i < NumSrcs; ++i) { 1201 RegSubRegPair PHISrc(Res.getSrcReg(i), Res.getSrcSubReg(i)); 1202 NewPHISrcs.push_back( 1203 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources)); 1204 } 1205 1206 // Build the new PHI node and return its def register as the new source. 1207 MachineInstr &OrigPHI = const_cast<MachineInstr &>(*Res.getInst()); 1208 MachineInstr &NewPHI = insertPHI(*MRI, *TII, NewPHISrcs, OrigPHI); 1209 LLVM_DEBUG(dbgs() << "-- getNewSource\n"); 1210 LLVM_DEBUG(dbgs() << " Replacing: " << OrigPHI); 1211 LLVM_DEBUG(dbgs() << " With: " << NewPHI); 1212 const MachineOperand &MODef = NewPHI.getOperand(0); 1213 return RegSubRegPair(MODef.getReg(), MODef.getSubReg()); 1214 } 1215 1216 return RegSubRegPair(0, 0); 1217 } 1218 1219 /// Optimize generic copy instructions to avoid cross register bank copy. 1220 /// The optimization looks through a chain of copies and tries to find a source 1221 /// that has a compatible register class. 1222 /// Two register classes are considered to be compatible if they share the same 1223 /// register bank. 1224 /// New copies issued by this optimization are register allocator 1225 /// friendly. This optimization does not remove any copy as it may 1226 /// overconstrain the register allocator, but replaces some operands 1227 /// when possible. 1228 /// \pre isCoalescableCopy(*MI) is true. 1229 /// \return True, when \p MI has been rewritten. False otherwise. 1230 bool PeepholeOptimizer::optimizeCoalescableCopy(MachineInstr &MI) { 1231 assert(isCoalescableCopy(MI) && "Invalid argument"); 1232 assert(MI.getDesc().getNumDefs() == 1 && 1233 "Coalescer can understand multiple defs?!"); 1234 const MachineOperand &MODef = MI.getOperand(0); 1235 // Do not rewrite physical definitions. 1236 if (MODef.getReg().isPhysical()) 1237 return false; 1238 1239 bool Changed = false; 1240 // Get the right rewriter for the current copy. 1241 std::unique_ptr<Rewriter> CpyRewriter(getCopyRewriter(MI, *TII)); 1242 // If none exists, bail out. 1243 if (!CpyRewriter) 1244 return false; 1245 // Rewrite each rewritable source. 1246 RegSubRegPair Src; 1247 RegSubRegPair TrackPair; 1248 while (CpyRewriter->getNextRewritableSource(Src, TrackPair)) { 1249 // Keep track of PHI nodes and its incoming edges when looking for sources. 1250 RewriteMapTy RewriteMap; 1251 // Try to find a more suitable source. If we failed to do so, or get the 1252 // actual source, move to the next source. 1253 if (!findNextSource(TrackPair, RewriteMap)) 1254 continue; 1255 1256 // Get the new source to rewrite. TODO: Only enable handling of multiple 1257 // sources (PHIs) once we have a motivating example and testcases for it. 1258 RegSubRegPair NewSrc = getNewSource(MRI, TII, TrackPair, RewriteMap, 1259 /*HandleMultipleSources=*/false); 1260 if (Src.Reg == NewSrc.Reg || NewSrc.Reg == 0) 1261 continue; 1262 1263 // Rewrite source. 1264 if (CpyRewriter->RewriteCurrentSource(NewSrc.Reg, NewSrc.SubReg)) { 1265 // We may have extended the live-range of NewSrc, account for that. 1266 MRI->clearKillFlags(NewSrc.Reg); 1267 Changed = true; 1268 } 1269 } 1270 // TODO: We could have a clean-up method to tidy the instruction. 1271 // E.g., v0 = INSERT_SUBREG v1, v1.sub0, sub0 1272 // => v0 = COPY v1 1273 // Currently we haven't seen motivating example for that and we 1274 // want to avoid untested code. 1275 NumRewrittenCopies += Changed; 1276 return Changed; 1277 } 1278 1279 /// Rewrite the source found through \p Def, by using the \p RewriteMap 1280 /// and create a new COPY instruction. More info about RewriteMap in 1281 /// PeepholeOptimizer::findNextSource. Right now this is only used to handle 1282 /// Uncoalescable copies, since they are copy like instructions that aren't 1283 /// recognized by the register allocator. 1284 MachineInstr & 1285 PeepholeOptimizer::rewriteSource(MachineInstr &CopyLike, 1286 RegSubRegPair Def, RewriteMapTy &RewriteMap) { 1287 assert(!Def.Reg.isPhysical() && "We do not rewrite physical registers"); 1288 1289 // Find the new source to use in the COPY rewrite. 1290 RegSubRegPair NewSrc = getNewSource(MRI, TII, Def, RewriteMap); 1291 1292 // Insert the COPY. 1293 const TargetRegisterClass *DefRC = MRI->getRegClass(Def.Reg); 1294 Register NewVReg = MRI->createVirtualRegister(DefRC); 1295 1296 MachineInstr *NewCopy = 1297 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(), 1298 TII->get(TargetOpcode::COPY), NewVReg) 1299 .addReg(NewSrc.Reg, 0, NewSrc.SubReg); 1300 1301 if (Def.SubReg) { 1302 NewCopy->getOperand(0).setSubReg(Def.SubReg); 1303 NewCopy->getOperand(0).setIsUndef(); 1304 } 1305 1306 LLVM_DEBUG(dbgs() << "-- RewriteSource\n"); 1307 LLVM_DEBUG(dbgs() << " Replacing: " << CopyLike); 1308 LLVM_DEBUG(dbgs() << " With: " << *NewCopy); 1309 MRI->replaceRegWith(Def.Reg, NewVReg); 1310 MRI->clearKillFlags(NewVReg); 1311 1312 // We extended the lifetime of NewSrc.Reg, clear the kill flags to 1313 // account for that. 1314 MRI->clearKillFlags(NewSrc.Reg); 1315 1316 return *NewCopy; 1317 } 1318 1319 /// Optimize copy-like instructions to create 1320 /// register coalescer friendly instruction. 1321 /// The optimization tries to kill-off the \p MI by looking 1322 /// through a chain of copies to find a source that has a compatible 1323 /// register class. 1324 /// If such a source is found, it replace \p MI by a generic COPY 1325 /// operation. 1326 /// \pre isUncoalescableCopy(*MI) is true. 1327 /// \return True, when \p MI has been optimized. In that case, \p MI has 1328 /// been removed from its parent. 1329 /// All COPY instructions created, are inserted in \p LocalMIs. 1330 bool PeepholeOptimizer::optimizeUncoalescableCopy( 1331 MachineInstr &MI, SmallPtrSetImpl<MachineInstr *> &LocalMIs) { 1332 assert(isUncoalescableCopy(MI) && "Invalid argument"); 1333 UncoalescableRewriter CpyRewriter(MI); 1334 1335 // Rewrite each rewritable source by generating new COPYs. This works 1336 // differently from optimizeCoalescableCopy since it first makes sure that all 1337 // definitions can be rewritten. 1338 RewriteMapTy RewriteMap; 1339 RegSubRegPair Src; 1340 RegSubRegPair Def; 1341 SmallVector<RegSubRegPair, 4> RewritePairs; 1342 while (CpyRewriter.getNextRewritableSource(Src, Def)) { 1343 // If a physical register is here, this is probably for a good reason. 1344 // Do not rewrite that. 1345 if (Def.Reg.isPhysical()) 1346 return false; 1347 1348 // If we do not know how to rewrite this definition, there is no point 1349 // in trying to kill this instruction. 1350 if (!findNextSource(Def, RewriteMap)) 1351 return false; 1352 1353 RewritePairs.push_back(Def); 1354 } 1355 1356 // The change is possible for all defs, do it. 1357 for (const RegSubRegPair &Def : RewritePairs) { 1358 // Rewrite the "copy" in a way the register coalescer understands. 1359 MachineInstr &NewCopy = rewriteSource(MI, Def, RewriteMap); 1360 LocalMIs.insert(&NewCopy); 1361 } 1362 1363 // MI is now dead. 1364 LLVM_DEBUG(dbgs() << "Deleting uncoalescable copy: " << MI); 1365 MI.eraseFromParent(); 1366 ++NumUncoalescableCopies; 1367 return true; 1368 } 1369 1370 /// Check whether MI is a candidate for folding into a later instruction. 1371 /// We only fold loads to virtual registers and the virtual register defined 1372 /// has a single user. 1373 bool PeepholeOptimizer::isLoadFoldable( 1374 MachineInstr &MI, SmallSet<Register, 16> &FoldAsLoadDefCandidates) { 1375 if (!MI.canFoldAsLoad() || !MI.mayLoad()) 1376 return false; 1377 const MCInstrDesc &MCID = MI.getDesc(); 1378 if (MCID.getNumDefs() != 1) 1379 return false; 1380 1381 Register Reg = MI.getOperand(0).getReg(); 1382 // To reduce compilation time, we check MRI->hasOneNonDBGUser when inserting 1383 // loads. It should be checked when processing uses of the load, since 1384 // uses can be removed during peephole. 1385 if (Reg.isVirtual() && !MI.getOperand(0).getSubReg() && 1386 MRI->hasOneNonDBGUser(Reg)) { 1387 FoldAsLoadDefCandidates.insert(Reg); 1388 return true; 1389 } 1390 return false; 1391 } 1392 1393 bool PeepholeOptimizer::isMoveImmediate( 1394 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs, 1395 DenseMap<Register, MachineInstr *> &ImmDefMIs) { 1396 const MCInstrDesc &MCID = MI.getDesc(); 1397 if (MCID.getNumDefs() != 1 || !MI.getOperand(0).isReg()) 1398 return false; 1399 Register Reg = MI.getOperand(0).getReg(); 1400 if (!Reg.isVirtual()) 1401 return false; 1402 1403 int64_t ImmVal; 1404 if (!MI.isMoveImmediate() && !TII->getConstValDefinedInReg(MI, Reg, ImmVal)) 1405 return false; 1406 1407 ImmDefMIs.insert(std::make_pair(Reg, &MI)); 1408 ImmDefRegs.insert(Reg); 1409 return true; 1410 } 1411 1412 /// Try folding register operands that are defined by move immediate 1413 /// instructions, i.e. a trivial constant folding optimization, if 1414 /// and only if the def and use are in the same BB. 1415 bool PeepholeOptimizer::foldImmediate( 1416 MachineInstr &MI, SmallSet<Register, 4> &ImmDefRegs, 1417 DenseMap<Register, MachineInstr *> &ImmDefMIs, bool &Deleted) { 1418 Deleted = false; 1419 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) { 1420 MachineOperand &MO = MI.getOperand(i); 1421 if (!MO.isReg() || MO.isDef()) 1422 continue; 1423 Register Reg = MO.getReg(); 1424 if (!Reg.isVirtual()) 1425 continue; 1426 if (ImmDefRegs.count(Reg) == 0) 1427 continue; 1428 DenseMap<Register, MachineInstr *>::iterator II = ImmDefMIs.find(Reg); 1429 assert(II != ImmDefMIs.end() && "couldn't find immediate definition"); 1430 if (TII->foldImmediate(MI, *II->second, Reg, MRI)) { 1431 ++NumImmFold; 1432 // foldImmediate can delete ImmDefMI if MI was its only user. If ImmDefMI 1433 // is not deleted, and we happened to get a same MI, we can delete MI and 1434 // replace its users. 1435 if (MRI->getVRegDef(Reg) && 1436 MI.isIdenticalTo(*II->second, MachineInstr::IgnoreVRegDefs)) { 1437 Register DstReg = MI.getOperand(0).getReg(); 1438 if (DstReg.isVirtual() && 1439 MRI->getRegClass(DstReg) == MRI->getRegClass(Reg)) { 1440 MRI->replaceRegWith(DstReg, Reg); 1441 MI.eraseFromParent(); 1442 Deleted = true; 1443 } 1444 } 1445 return true; 1446 } 1447 } 1448 return false; 1449 } 1450 1451 // FIXME: This is very simple and misses some cases which should be handled when 1452 // motivating examples are found. 1453 // 1454 // The copy rewriting logic should look at uses as well as defs and be able to 1455 // eliminate copies across blocks. 1456 // 1457 // Later copies that are subregister extracts will also not be eliminated since 1458 // only the first copy is considered. 1459 // 1460 // e.g. 1461 // %1 = COPY %0 1462 // %2 = COPY %0:sub1 1463 // 1464 // Should replace %2 uses with %1:sub1 1465 bool PeepholeOptimizer::foldRedundantCopy(MachineInstr &MI) { 1466 assert(MI.isCopy() && "expected a COPY machine instruction"); 1467 1468 RegSubRegPair SrcPair; 1469 if (!getCopySrc(MI, SrcPair)) 1470 return false; 1471 1472 Register DstReg = MI.getOperand(0).getReg(); 1473 if (!DstReg.isVirtual()) 1474 return false; 1475 1476 if (CopySrcMIs.insert(std::make_pair(SrcPair, &MI)).second) { 1477 // First copy of this reg seen. 1478 return false; 1479 } 1480 1481 MachineInstr *PrevCopy = CopySrcMIs.find(SrcPair)->second; 1482 1483 assert(SrcPair.SubReg == PrevCopy->getOperand(1).getSubReg() && 1484 "Unexpected mismatching subreg!"); 1485 1486 Register PrevDstReg = PrevCopy->getOperand(0).getReg(); 1487 1488 // Only replace if the copy register class is the same. 1489 // 1490 // TODO: If we have multiple copies to different register classes, we may want 1491 // to track multiple copies of the same source register. 1492 if (MRI->getRegClass(DstReg) != MRI->getRegClass(PrevDstReg)) 1493 return false; 1494 1495 MRI->replaceRegWith(DstReg, PrevDstReg); 1496 1497 // Lifetime of the previous copy has been extended. 1498 MRI->clearKillFlags(PrevDstReg); 1499 return true; 1500 } 1501 1502 bool PeepholeOptimizer::isNAPhysCopy(Register Reg) { 1503 return Reg.isPhysical() && !MRI->isAllocatable(Reg); 1504 } 1505 1506 bool PeepholeOptimizer::foldRedundantNAPhysCopy( 1507 MachineInstr &MI, DenseMap<Register, MachineInstr *> &NAPhysToVirtMIs) { 1508 assert(MI.isCopy() && "expected a COPY machine instruction"); 1509 1510 if (DisableNAPhysCopyOpt) 1511 return false; 1512 1513 Register DstReg = MI.getOperand(0).getReg(); 1514 Register SrcReg = MI.getOperand(1).getReg(); 1515 if (isNAPhysCopy(SrcReg) && DstReg.isVirtual()) { 1516 // %vreg = COPY $physreg 1517 // Avoid using a datastructure which can track multiple live non-allocatable 1518 // phys->virt copies since LLVM doesn't seem to do this. 1519 NAPhysToVirtMIs.insert({SrcReg, &MI}); 1520 return false; 1521 } 1522 1523 if (!(SrcReg.isVirtual() && isNAPhysCopy(DstReg))) 1524 return false; 1525 1526 // $physreg = COPY %vreg 1527 auto PrevCopy = NAPhysToVirtMIs.find(DstReg); 1528 if (PrevCopy == NAPhysToVirtMIs.end()) { 1529 // We can't remove the copy: there was an intervening clobber of the 1530 // non-allocatable physical register after the copy to virtual. 1531 LLVM_DEBUG(dbgs() << "NAPhysCopy: intervening clobber forbids erasing " 1532 << MI); 1533 return false; 1534 } 1535 1536 Register PrevDstReg = PrevCopy->second->getOperand(0).getReg(); 1537 if (PrevDstReg == SrcReg) { 1538 // Remove the virt->phys copy: we saw the virtual register definition, and 1539 // the non-allocatable physical register's state hasn't changed since then. 1540 LLVM_DEBUG(dbgs() << "NAPhysCopy: erasing " << MI); 1541 ++NumNAPhysCopies; 1542 return true; 1543 } 1544 1545 // Potential missed optimization opportunity: we saw a different virtual 1546 // register get a copy of the non-allocatable physical register, and we only 1547 // track one such copy. Avoid getting confused by this new non-allocatable 1548 // physical register definition, and remove it from the tracked copies. 1549 LLVM_DEBUG(dbgs() << "NAPhysCopy: missed opportunity " << MI); 1550 NAPhysToVirtMIs.erase(PrevCopy); 1551 return false; 1552 } 1553 1554 /// \bried Returns true if \p MO is a virtual register operand. 1555 static bool isVirtualRegisterOperand(MachineOperand &MO) { 1556 return MO.isReg() && MO.getReg().isVirtual(); 1557 } 1558 1559 bool PeepholeOptimizer::findTargetRecurrence( 1560 Register Reg, const SmallSet<Register, 2> &TargetRegs, 1561 RecurrenceCycle &RC) { 1562 // Recurrence found if Reg is in TargetRegs. 1563 if (TargetRegs.count(Reg)) 1564 return true; 1565 1566 // TODO: Curerntly, we only allow the last instruction of the recurrence 1567 // cycle (the instruction that feeds the PHI instruction) to have more than 1568 // one uses to guarantee that commuting operands does not tie registers 1569 // with overlapping live range. Once we have actual live range info of 1570 // each register, this constraint can be relaxed. 1571 if (!MRI->hasOneNonDBGUse(Reg)) 1572 return false; 1573 1574 // Give up if the reccurrence chain length is longer than the limit. 1575 if (RC.size() >= MaxRecurrenceChain) 1576 return false; 1577 1578 MachineInstr &MI = *(MRI->use_instr_nodbg_begin(Reg)); 1579 unsigned Idx = MI.findRegisterUseOperandIdx(Reg, /*TRI=*/nullptr); 1580 1581 // Only interested in recurrences whose instructions have only one def, which 1582 // is a virtual register. 1583 if (MI.getDesc().getNumDefs() != 1) 1584 return false; 1585 1586 MachineOperand &DefOp = MI.getOperand(0); 1587 if (!isVirtualRegisterOperand(DefOp)) 1588 return false; 1589 1590 // Check if def operand of MI is tied to any use operand. We are only 1591 // interested in the case that all the instructions in the recurrence chain 1592 // have there def operand tied with one of the use operand. 1593 unsigned TiedUseIdx; 1594 if (!MI.isRegTiedToUseOperand(0, &TiedUseIdx)) 1595 return false; 1596 1597 if (Idx == TiedUseIdx) { 1598 RC.push_back(RecurrenceInstr(&MI)); 1599 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC); 1600 } else { 1601 // If Idx is not TiedUseIdx, check if Idx is commutable with TiedUseIdx. 1602 unsigned CommIdx = TargetInstrInfo::CommuteAnyOperandIndex; 1603 if (TII->findCommutedOpIndices(MI, Idx, CommIdx) && CommIdx == TiedUseIdx) { 1604 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx)); 1605 return findTargetRecurrence(DefOp.getReg(), TargetRegs, RC); 1606 } 1607 } 1608 1609 return false; 1610 } 1611 1612 /// Phi instructions will eventually be lowered to copy instructions. 1613 /// If phi is in a loop header, a recurrence may formulated around the source 1614 /// and destination of the phi. For such case commuting operands of the 1615 /// instructions in the recurrence may enable coalescing of the copy instruction 1616 /// generated from the phi. For example, if there is a recurrence of 1617 /// 1618 /// LoopHeader: 1619 /// %1 = phi(%0, %100) 1620 /// LoopLatch: 1621 /// %0<def, tied1> = ADD %2<def, tied0>, %1 1622 /// 1623 /// , the fact that %0 and %2 are in the same tied operands set makes 1624 /// the coalescing of copy instruction generated from the phi in 1625 /// LoopHeader(i.e. %1 = COPY %0) impossible, because %1 and 1626 /// %2 have overlapping live range. This introduces additional move 1627 /// instruction to the final assembly. However, if we commute %2 and 1628 /// %1 of ADD instruction, the redundant move instruction can be 1629 /// avoided. 1630 bool PeepholeOptimizer::optimizeRecurrence(MachineInstr &PHI) { 1631 SmallSet<Register, 2> TargetRegs; 1632 for (unsigned Idx = 1; Idx < PHI.getNumOperands(); Idx += 2) { 1633 MachineOperand &MO = PHI.getOperand(Idx); 1634 assert(isVirtualRegisterOperand(MO) && "Invalid PHI instruction"); 1635 TargetRegs.insert(MO.getReg()); 1636 } 1637 1638 bool Changed = false; 1639 RecurrenceCycle RC; 1640 if (findTargetRecurrence(PHI.getOperand(0).getReg(), TargetRegs, RC)) { 1641 // Commutes operands of instructions in RC if necessary so that the copy to 1642 // be generated from PHI can be coalesced. 1643 LLVM_DEBUG(dbgs() << "Optimize recurrence chain from " << PHI); 1644 for (auto &RI : RC) { 1645 LLVM_DEBUG(dbgs() << "\tInst: " << *(RI.getMI())); 1646 auto CP = RI.getCommutePair(); 1647 if (CP) { 1648 Changed = true; 1649 TII->commuteInstruction(*(RI.getMI()), false, (*CP).first, 1650 (*CP).second); 1651 LLVM_DEBUG(dbgs() << "\t\tCommuted: " << *(RI.getMI())); 1652 } 1653 } 1654 } 1655 1656 return Changed; 1657 } 1658 1659 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) { 1660 if (skipFunction(MF.getFunction())) 1661 return false; 1662 1663 LLVM_DEBUG(dbgs() << "********** PEEPHOLE OPTIMIZER **********\n"); 1664 LLVM_DEBUG(dbgs() << "********** Function: " << MF.getName() << '\n'); 1665 1666 if (DisablePeephole) 1667 return false; 1668 1669 TII = MF.getSubtarget().getInstrInfo(); 1670 TRI = MF.getSubtarget().getRegisterInfo(); 1671 MRI = &MF.getRegInfo(); 1672 DT = Aggressive ? &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree() 1673 : nullptr; 1674 MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI(); 1675 MF.setDelegate(this); 1676 1677 bool Changed = false; 1678 1679 for (MachineBasicBlock &MBB : MF) { 1680 bool SeenMoveImm = false; 1681 1682 // During this forward scan, at some point it needs to answer the question 1683 // "given a pointer to an MI in the current BB, is it located before or 1684 // after the current instruction". 1685 // To perform this, the following set keeps track of the MIs already seen 1686 // during the scan, if a MI is not in the set, it is assumed to be located 1687 // after. Newly created MIs have to be inserted in the set as well. 1688 SmallPtrSet<MachineInstr*, 16> LocalMIs; 1689 SmallSet<Register, 4> ImmDefRegs; 1690 DenseMap<Register, MachineInstr *> ImmDefMIs; 1691 SmallSet<Register, 16> FoldAsLoadDefCandidates; 1692 1693 // Track when a non-allocatable physical register is copied to a virtual 1694 // register so that useless moves can be removed. 1695 // 1696 // $physreg is the map index; MI is the last valid `%vreg = COPY $physreg` 1697 // without any intervening re-definition of $physreg. 1698 DenseMap<Register, MachineInstr *> NAPhysToVirtMIs; 1699 1700 CopySrcMIs.clear(); 1701 1702 bool IsLoopHeader = MLI->isLoopHeader(&MBB); 1703 1704 for (MachineBasicBlock::iterator MII = MBB.begin(), MIE = MBB.end(); 1705 MII != MIE; ) { 1706 MachineInstr *MI = &*MII; 1707 // We may be erasing MI below, increment MII now. 1708 ++MII; 1709 LocalMIs.insert(MI); 1710 1711 // Skip debug instructions. They should not affect this peephole 1712 // optimization. 1713 if (MI->isDebugInstr()) 1714 continue; 1715 1716 if (MI->isPosition()) 1717 continue; 1718 1719 if (IsLoopHeader && MI->isPHI()) { 1720 if (optimizeRecurrence(*MI)) { 1721 Changed = true; 1722 continue; 1723 } 1724 } 1725 1726 if (!MI->isCopy()) { 1727 for (const MachineOperand &MO : MI->operands()) { 1728 // Visit all operands: definitions can be implicit or explicit. 1729 if (MO.isReg()) { 1730 Register Reg = MO.getReg(); 1731 if (MO.isDef() && isNAPhysCopy(Reg)) { 1732 const auto &Def = NAPhysToVirtMIs.find(Reg); 1733 if (Def != NAPhysToVirtMIs.end()) { 1734 // A new definition of the non-allocatable physical register 1735 // invalidates previous copies. 1736 LLVM_DEBUG(dbgs() 1737 << "NAPhysCopy: invalidating because of " << *MI); 1738 NAPhysToVirtMIs.erase(Def); 1739 } 1740 } 1741 } else if (MO.isRegMask()) { 1742 const uint32_t *RegMask = MO.getRegMask(); 1743 for (auto &RegMI : NAPhysToVirtMIs) { 1744 Register Def = RegMI.first; 1745 if (MachineOperand::clobbersPhysReg(RegMask, Def)) { 1746 LLVM_DEBUG(dbgs() 1747 << "NAPhysCopy: invalidating because of " << *MI); 1748 NAPhysToVirtMIs.erase(Def); 1749 } 1750 } 1751 } 1752 } 1753 } 1754 1755 if (MI->isImplicitDef() || MI->isKill()) 1756 continue; 1757 1758 if (MI->isInlineAsm() || MI->hasUnmodeledSideEffects()) { 1759 // Blow away all non-allocatable physical registers knowledge since we 1760 // don't know what's correct anymore. 1761 // 1762 // FIXME: handle explicit asm clobbers. 1763 LLVM_DEBUG(dbgs() << "NAPhysCopy: blowing away all info due to " 1764 << *MI); 1765 NAPhysToVirtMIs.clear(); 1766 } 1767 1768 if ((isUncoalescableCopy(*MI) && 1769 optimizeUncoalescableCopy(*MI, LocalMIs)) || 1770 (MI->isCompare() && optimizeCmpInstr(*MI)) || 1771 (MI->isSelect() && optimizeSelect(*MI, LocalMIs))) { 1772 // MI is deleted. 1773 LocalMIs.erase(MI); 1774 Changed = true; 1775 continue; 1776 } 1777 1778 if (MI->isConditionalBranch() && optimizeCondBranch(*MI)) { 1779 Changed = true; 1780 continue; 1781 } 1782 1783 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(*MI)) { 1784 // MI is just rewritten. 1785 Changed = true; 1786 continue; 1787 } 1788 1789 if (MI->isCopy() && (foldRedundantCopy(*MI) || 1790 foldRedundantNAPhysCopy(*MI, NAPhysToVirtMIs))) { 1791 LocalMIs.erase(MI); 1792 LLVM_DEBUG(dbgs() << "Deleting redundant copy: " << *MI << "\n"); 1793 MI->eraseFromParent(); 1794 Changed = true; 1795 continue; 1796 } 1797 1798 if (isMoveImmediate(*MI, ImmDefRegs, ImmDefMIs)) { 1799 SeenMoveImm = true; 1800 } else { 1801 Changed |= optimizeExtInstr(*MI, MBB, LocalMIs); 1802 // optimizeExtInstr might have created new instructions after MI 1803 // and before the already incremented MII. Adjust MII so that the 1804 // next iteration sees the new instructions. 1805 MII = MI; 1806 ++MII; 1807 if (SeenMoveImm) { 1808 bool Deleted; 1809 Changed |= foldImmediate(*MI, ImmDefRegs, ImmDefMIs, Deleted); 1810 if (Deleted) { 1811 LocalMIs.erase(MI); 1812 continue; 1813 } 1814 } 1815 } 1816 1817 // Check whether MI is a load candidate for folding into a later 1818 // instruction. If MI is not a candidate, check whether we can fold an 1819 // earlier load into MI. 1820 if (!isLoadFoldable(*MI, FoldAsLoadDefCandidates) && 1821 !FoldAsLoadDefCandidates.empty()) { 1822 1823 // We visit each operand even after successfully folding a previous 1824 // one. This allows us to fold multiple loads into a single 1825 // instruction. We do assume that optimizeLoadInstr doesn't insert 1826 // foldable uses earlier in the argument list. Since we don't restart 1827 // iteration, we'd miss such cases. 1828 const MCInstrDesc &MIDesc = MI->getDesc(); 1829 for (unsigned i = MIDesc.getNumDefs(); i != MI->getNumOperands(); 1830 ++i) { 1831 const MachineOperand &MOp = MI->getOperand(i); 1832 if (!MOp.isReg()) 1833 continue; 1834 Register FoldAsLoadDefReg = MOp.getReg(); 1835 if (FoldAsLoadDefCandidates.count(FoldAsLoadDefReg)) { 1836 // We need to fold load after optimizeCmpInstr, since 1837 // optimizeCmpInstr can enable folding by converting SUB to CMP. 1838 // Save FoldAsLoadDefReg because optimizeLoadInstr() resets it and 1839 // we need it for markUsesInDebugValueAsUndef(). 1840 Register FoldedReg = FoldAsLoadDefReg; 1841 MachineInstr *DefMI = nullptr; 1842 if (MachineInstr *FoldMI = 1843 TII->optimizeLoadInstr(*MI, MRI, FoldAsLoadDefReg, DefMI)) { 1844 // Update LocalMIs since we replaced MI with FoldMI and deleted 1845 // DefMI. 1846 LLVM_DEBUG(dbgs() << "Replacing: " << *MI); 1847 LLVM_DEBUG(dbgs() << " With: " << *FoldMI); 1848 LocalMIs.erase(MI); 1849 LocalMIs.erase(DefMI); 1850 LocalMIs.insert(FoldMI); 1851 // Update the call site info. 1852 if (MI->shouldUpdateCallSiteInfo()) 1853 MI->getMF()->moveCallSiteInfo(MI, FoldMI); 1854 MI->eraseFromParent(); 1855 DefMI->eraseFromParent(); 1856 MRI->markUsesInDebugValueAsUndef(FoldedReg); 1857 FoldAsLoadDefCandidates.erase(FoldedReg); 1858 ++NumLoadFold; 1859 1860 // MI is replaced with FoldMI so we can continue trying to fold 1861 Changed = true; 1862 MI = FoldMI; 1863 } 1864 } 1865 } 1866 } 1867 1868 // If we run into an instruction we can't fold across, discard 1869 // the load candidates. Note: We might be able to fold *into* this 1870 // instruction, so this needs to be after the folding logic. 1871 if (MI->isLoadFoldBarrier()) { 1872 LLVM_DEBUG(dbgs() << "Encountered load fold barrier on " << *MI); 1873 FoldAsLoadDefCandidates.clear(); 1874 } 1875 } 1876 } 1877 1878 MF.resetDelegate(this); 1879 return Changed; 1880 } 1881 1882 ValueTrackerResult ValueTracker::getNextSourceFromCopy() { 1883 assert(Def->isCopy() && "Invalid definition"); 1884 // Copy instruction are supposed to be: Def = Src. 1885 // If someone breaks this assumption, bad things will happen everywhere. 1886 // There may be implicit uses preventing the copy to be moved across 1887 // some target specific register definitions 1888 assert(Def->getNumOperands() - Def->getNumImplicitOperands() == 2 && 1889 "Invalid number of operands"); 1890 assert(!Def->hasImplicitDef() && "Only implicit uses are allowed"); 1891 1892 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg) 1893 // If we look for a different subreg, it means we want a subreg of src. 1894 // Bails as we do not support composing subregs yet. 1895 return ValueTrackerResult(); 1896 // Otherwise, we want the whole source. 1897 const MachineOperand &Src = Def->getOperand(1); 1898 if (Src.isUndef()) 1899 return ValueTrackerResult(); 1900 return ValueTrackerResult(Src.getReg(), Src.getSubReg()); 1901 } 1902 1903 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() { 1904 assert(Def->isBitcast() && "Invalid definition"); 1905 1906 // Bail if there are effects that a plain copy will not expose. 1907 if (Def->mayRaiseFPException() || Def->hasUnmodeledSideEffects()) 1908 return ValueTrackerResult(); 1909 1910 // Bitcasts with more than one def are not supported. 1911 if (Def->getDesc().getNumDefs() != 1) 1912 return ValueTrackerResult(); 1913 const MachineOperand DefOp = Def->getOperand(DefIdx); 1914 if (DefOp.getSubReg() != DefSubReg) 1915 // If we look for a different subreg, it means we want a subreg of the src. 1916 // Bails as we do not support composing subregs yet. 1917 return ValueTrackerResult(); 1918 1919 unsigned SrcIdx = Def->getNumOperands(); 1920 for (unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx; 1921 ++OpIdx) { 1922 const MachineOperand &MO = Def->getOperand(OpIdx); 1923 if (!MO.isReg() || !MO.getReg()) 1924 continue; 1925 // Ignore dead implicit defs. 1926 if (MO.isImplicit() && MO.isDead()) 1927 continue; 1928 assert(!MO.isDef() && "We should have skipped all the definitions by now"); 1929 if (SrcIdx != EndOpIdx) 1930 // Multiple sources? 1931 return ValueTrackerResult(); 1932 SrcIdx = OpIdx; 1933 } 1934 1935 // In some rare case, Def has no input, SrcIdx is out of bound, 1936 // getOperand(SrcIdx) will fail below. 1937 if (SrcIdx >= Def->getNumOperands()) 1938 return ValueTrackerResult(); 1939 1940 // Stop when any user of the bitcast is a SUBREG_TO_REG, replacing with a COPY 1941 // will break the assumed guarantees for the upper bits. 1942 for (const MachineInstr &UseMI : MRI.use_nodbg_instructions(DefOp.getReg())) { 1943 if (UseMI.isSubregToReg()) 1944 return ValueTrackerResult(); 1945 } 1946 1947 const MachineOperand &Src = Def->getOperand(SrcIdx); 1948 if (Src.isUndef()) 1949 return ValueTrackerResult(); 1950 return ValueTrackerResult(Src.getReg(), Src.getSubReg()); 1951 } 1952 1953 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() { 1954 assert((Def->isRegSequence() || Def->isRegSequenceLike()) && 1955 "Invalid definition"); 1956 1957 if (Def->getOperand(DefIdx).getSubReg()) 1958 // If we are composing subregs, bail out. 1959 // The case we are checking is Def.<subreg> = REG_SEQUENCE. 1960 // This should almost never happen as the SSA property is tracked at 1961 // the register level (as opposed to the subreg level). 1962 // I.e., 1963 // Def.sub0 = 1964 // Def.sub1 = 1965 // is a valid SSA representation for Def.sub0 and Def.sub1, but not for 1966 // Def. Thus, it must not be generated. 1967 // However, some code could theoretically generates a single 1968 // Def.sub0 (i.e, not defining the other subregs) and we would 1969 // have this case. 1970 // If we can ascertain (or force) that this never happens, we could 1971 // turn that into an assertion. 1972 return ValueTrackerResult(); 1973 1974 if (!TII) 1975 // We could handle the REG_SEQUENCE here, but we do not want to 1976 // duplicate the code from the generic TII. 1977 return ValueTrackerResult(); 1978 1979 SmallVector<RegSubRegPairAndIdx, 8> RegSeqInputRegs; 1980 if (!TII->getRegSequenceInputs(*Def, DefIdx, RegSeqInputRegs)) 1981 return ValueTrackerResult(); 1982 1983 // We are looking at: 1984 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ... 1985 // Check if one of the operand defines the subreg we are interested in. 1986 for (const RegSubRegPairAndIdx &RegSeqInput : RegSeqInputRegs) { 1987 if (RegSeqInput.SubIdx == DefSubReg) 1988 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg); 1989 } 1990 1991 // If the subreg we are tracking is super-defined by another subreg, 1992 // we could follow this value. However, this would require to compose 1993 // the subreg and we do not do that for now. 1994 return ValueTrackerResult(); 1995 } 1996 1997 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() { 1998 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) && 1999 "Invalid definition"); 2000 2001 if (Def->getOperand(DefIdx).getSubReg()) 2002 // If we are composing subreg, bail out. 2003 // Same remark as getNextSourceFromRegSequence. 2004 // I.e., this may be turned into an assert. 2005 return ValueTrackerResult(); 2006 2007 if (!TII) 2008 // We could handle the REG_SEQUENCE here, but we do not want to 2009 // duplicate the code from the generic TII. 2010 return ValueTrackerResult(); 2011 2012 RegSubRegPair BaseReg; 2013 RegSubRegPairAndIdx InsertedReg; 2014 if (!TII->getInsertSubregInputs(*Def, DefIdx, BaseReg, InsertedReg)) 2015 return ValueTrackerResult(); 2016 2017 // We are looking at: 2018 // Def = INSERT_SUBREG v0, v1, sub1 2019 // There are two cases: 2020 // 1. DefSubReg == sub1, get v1. 2021 // 2. DefSubReg != sub1, the value may be available through v0. 2022 2023 // #1 Check if the inserted register matches the required sub index. 2024 if (InsertedReg.SubIdx == DefSubReg) { 2025 return ValueTrackerResult(InsertedReg.Reg, InsertedReg.SubReg); 2026 } 2027 // #2 Otherwise, if the sub register we are looking for is not partial 2028 // defined by the inserted element, we can look through the main 2029 // register (v0). 2030 const MachineOperand &MODef = Def->getOperand(DefIdx); 2031 // If the result register (Def) and the base register (v0) do not 2032 // have the same register class or if we have to compose 2033 // subregisters, bail out. 2034 if (MRI.getRegClass(MODef.getReg()) != MRI.getRegClass(BaseReg.Reg) || 2035 BaseReg.SubReg) 2036 return ValueTrackerResult(); 2037 2038 // Get the TRI and check if the inserted sub-register overlaps with the 2039 // sub-register we are tracking. 2040 const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo(); 2041 if (!TRI || 2042 !(TRI->getSubRegIndexLaneMask(DefSubReg) & 2043 TRI->getSubRegIndexLaneMask(InsertedReg.SubIdx)).none()) 2044 return ValueTrackerResult(); 2045 // At this point, the value is available in v0 via the same subreg 2046 // we used for Def. 2047 return ValueTrackerResult(BaseReg.Reg, DefSubReg); 2048 } 2049 2050 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() { 2051 assert((Def->isExtractSubreg() || 2052 Def->isExtractSubregLike()) && "Invalid definition"); 2053 // We are looking at: 2054 // Def = EXTRACT_SUBREG v0, sub0 2055 2056 // Bail if we have to compose sub registers. 2057 // Indeed, if DefSubReg != 0, we would have to compose it with sub0. 2058 if (DefSubReg) 2059 return ValueTrackerResult(); 2060 2061 if (!TII) 2062 // We could handle the EXTRACT_SUBREG here, but we do not want to 2063 // duplicate the code from the generic TII. 2064 return ValueTrackerResult(); 2065 2066 RegSubRegPairAndIdx ExtractSubregInputReg; 2067 if (!TII->getExtractSubregInputs(*Def, DefIdx, ExtractSubregInputReg)) 2068 return ValueTrackerResult(); 2069 2070 // Bail if we have to compose sub registers. 2071 // Likewise, if v0.subreg != 0, we would have to compose v0.subreg with sub0. 2072 if (ExtractSubregInputReg.SubReg) 2073 return ValueTrackerResult(); 2074 // Otherwise, the value is available in the v0.sub0. 2075 return ValueTrackerResult(ExtractSubregInputReg.Reg, 2076 ExtractSubregInputReg.SubIdx); 2077 } 2078 2079 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() { 2080 assert(Def->isSubregToReg() && "Invalid definition"); 2081 // We are looking at: 2082 // Def = SUBREG_TO_REG Imm, v0, sub0 2083 2084 // Bail if we have to compose sub registers. 2085 // If DefSubReg != sub0, we would have to check that all the bits 2086 // we track are included in sub0 and if yes, we would have to 2087 // determine the right subreg in v0. 2088 if (DefSubReg != Def->getOperand(3).getImm()) 2089 return ValueTrackerResult(); 2090 // Bail if we have to compose sub registers. 2091 // Likewise, if v0.subreg != 0, we would have to compose it with sub0. 2092 if (Def->getOperand(2).getSubReg()) 2093 return ValueTrackerResult(); 2094 2095 return ValueTrackerResult(Def->getOperand(2).getReg(), 2096 Def->getOperand(3).getImm()); 2097 } 2098 2099 /// Explore each PHI incoming operand and return its sources. 2100 ValueTrackerResult ValueTracker::getNextSourceFromPHI() { 2101 assert(Def->isPHI() && "Invalid definition"); 2102 ValueTrackerResult Res; 2103 2104 // If we look for a different subreg, bail as we do not support composing 2105 // subregs yet. 2106 if (Def->getOperand(0).getSubReg() != DefSubReg) 2107 return ValueTrackerResult(); 2108 2109 // Return all register sources for PHI instructions. 2110 for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) { 2111 const MachineOperand &MO = Def->getOperand(i); 2112 assert(MO.isReg() && "Invalid PHI instruction"); 2113 // We have no code to deal with undef operands. They shouldn't happen in 2114 // normal programs anyway. 2115 if (MO.isUndef()) 2116 return ValueTrackerResult(); 2117 Res.addSource(MO.getReg(), MO.getSubReg()); 2118 } 2119 2120 return Res; 2121 } 2122 2123 ValueTrackerResult ValueTracker::getNextSourceImpl() { 2124 assert(Def && "This method needs a valid definition"); 2125 2126 assert(((Def->getOperand(DefIdx).isDef() && 2127 (DefIdx < Def->getDesc().getNumDefs() || 2128 Def->getDesc().isVariadic())) || 2129 Def->getOperand(DefIdx).isImplicit()) && 2130 "Invalid DefIdx"); 2131 if (Def->isCopy()) 2132 return getNextSourceFromCopy(); 2133 if (Def->isBitcast()) 2134 return getNextSourceFromBitcast(); 2135 // All the remaining cases involve "complex" instructions. 2136 // Bail if we did not ask for the advanced tracking. 2137 if (DisableAdvCopyOpt) 2138 return ValueTrackerResult(); 2139 if (Def->isRegSequence() || Def->isRegSequenceLike()) 2140 return getNextSourceFromRegSequence(); 2141 if (Def->isInsertSubreg() || Def->isInsertSubregLike()) 2142 return getNextSourceFromInsertSubreg(); 2143 if (Def->isExtractSubreg() || Def->isExtractSubregLike()) 2144 return getNextSourceFromExtractSubreg(); 2145 if (Def->isSubregToReg()) 2146 return getNextSourceFromSubregToReg(); 2147 if (Def->isPHI()) 2148 return getNextSourceFromPHI(); 2149 return ValueTrackerResult(); 2150 } 2151 2152 ValueTrackerResult ValueTracker::getNextSource() { 2153 // If we reach a point where we cannot move up in the use-def chain, 2154 // there is nothing we can get. 2155 if (!Def) 2156 return ValueTrackerResult(); 2157 2158 ValueTrackerResult Res = getNextSourceImpl(); 2159 if (Res.isValid()) { 2160 // Update definition, definition index, and subregister for the 2161 // next call of getNextSource. 2162 // Update the current register. 2163 bool OneRegSrc = Res.getNumSources() == 1; 2164 if (OneRegSrc) 2165 Reg = Res.getSrcReg(0); 2166 // Update the result before moving up in the use-def chain 2167 // with the instruction containing the last found sources. 2168 Res.setInst(Def); 2169 2170 // If we can still move up in the use-def chain, move to the next 2171 // definition. 2172 if (!Reg.isPhysical() && OneRegSrc) { 2173 MachineRegisterInfo::def_iterator DI = MRI.def_begin(Reg); 2174 if (DI != MRI.def_end()) { 2175 Def = DI->getParent(); 2176 DefIdx = DI.getOperandNo(); 2177 DefSubReg = Res.getSrcSubReg(0); 2178 } else { 2179 Def = nullptr; 2180 } 2181 return Res; 2182 } 2183 } 2184 // If we end up here, this means we will not be able to find another source 2185 // for the next iteration. Make sure any new call to getNextSource bails out 2186 // early by cutting the use-def chain. 2187 Def = nullptr; 2188 return Res; 2189 } 2190