1 //===----------- PPCVSXSwapRemoval.cpp - Remove VSX LE Swaps -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===---------------------------------------------------------------------===// 9 // 10 // This pass analyzes vector computations and removes unnecessary 11 // doubleword swaps (xxswapd instructions). This pass is performed 12 // only for little-endian VSX code generation. 13 // 14 // For this specific case, loads and stores of v4i32, v4f32, v2i64, 15 // and v2f64 vectors are inefficient. These are implemented using 16 // the lxvd2x and stxvd2x instructions, which invert the order of 17 // doublewords in a vector register. Thus code generation inserts 18 // an xxswapd after each such load, and prior to each such store. 19 // 20 // The extra xxswapd instructions reduce performance. The purpose 21 // of this pass is to reduce the number of xxswapd instructions 22 // required for correctness. 23 // 24 // The primary insight is that much code that operates on vectors 25 // does not care about the relative order of elements in a register, 26 // so long as the correct memory order is preserved. If we have a 27 // computation where all input values are provided by lxvd2x/xxswapd, 28 // all outputs are stored using xxswapd/lxvd2x, and all intermediate 29 // computations are lane-insensitive (independent of element order), 30 // then all the xxswapd instructions associated with the loads and 31 // stores may be removed without changing observable semantics. 32 // 33 // This pass uses standard equivalence class infrastructure to create 34 // maximal webs of computations fitting the above description. Each 35 // such web is then optimized by removing its unnecessary xxswapd 36 // instructions. 37 // 38 // There are some lane-sensitive operations for which we can still 39 // permit the optimization, provided we modify those operations 40 // accordingly. Such operations are identified as using "special 41 // handling" within this module. 42 // 43 //===---------------------------------------------------------------------===// 44 45 #include "PPC.h" 46 #include "PPCInstrBuilder.h" 47 #include "PPCInstrInfo.h" 48 #include "PPCTargetMachine.h" 49 #include "llvm/ADT/DenseMap.h" 50 #include "llvm/ADT/EquivalenceClasses.h" 51 #include "llvm/CodeGen/MachineFunctionPass.h" 52 #include "llvm/CodeGen/MachineInstrBuilder.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/Config/llvm-config.h" 55 #include "llvm/Support/Debug.h" 56 #include "llvm/Support/Format.h" 57 #include "llvm/Support/raw_ostream.h" 58 59 using namespace llvm; 60 61 #define DEBUG_TYPE "ppc-vsx-swaps" 62 63 namespace llvm { 64 void initializePPCVSXSwapRemovalPass(PassRegistry&); 65 } 66 67 namespace { 68 69 // A PPCVSXSwapEntry is created for each machine instruction that 70 // is relevant to a vector computation. 71 struct PPCVSXSwapEntry { 72 // Pointer to the instruction. 73 MachineInstr *VSEMI; 74 75 // Unique ID (position in the swap vector). 76 int VSEId; 77 78 // Attributes of this node. 79 unsigned int IsLoad : 1; 80 unsigned int IsStore : 1; 81 unsigned int IsSwap : 1; 82 unsigned int MentionsPhysVR : 1; 83 unsigned int IsSwappable : 1; 84 unsigned int MentionsPartialVR : 1; 85 unsigned int SpecialHandling : 3; 86 unsigned int WebRejected : 1; 87 unsigned int WillRemove : 1; 88 }; 89 90 enum SHValues { 91 SH_NONE = 0, 92 SH_EXTRACT, 93 SH_INSERT, 94 SH_NOSWAP_LD, 95 SH_NOSWAP_ST, 96 SH_SPLAT, 97 SH_XXPERMDI, 98 SH_COPYWIDEN 99 }; 100 101 struct PPCVSXSwapRemoval : public MachineFunctionPass { 102 103 static char ID; 104 const PPCInstrInfo *TII; 105 MachineFunction *MF; 106 MachineRegisterInfo *MRI; 107 108 // Swap entries are allocated in a vector for better performance. 109 std::vector<PPCVSXSwapEntry> SwapVector; 110 111 // A mapping is maintained between machine instructions and 112 // their swap entries. The key is the address of the MI. 113 DenseMap<MachineInstr*, int> SwapMap; 114 115 // Equivalence classes are used to gather webs of related computation. 116 // Swap entries are represented by their VSEId fields. 117 EquivalenceClasses<int> *EC; 118 119 PPCVSXSwapRemoval() : MachineFunctionPass(ID) { 120 initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry()); 121 } 122 123 private: 124 // Initialize data structures. 125 void initialize(MachineFunction &MFParm); 126 127 // Walk the machine instructions to gather vector usage information. 128 // Return true iff vector mentions are present. 129 bool gatherVectorInstructions(); 130 131 // Add an entry to the swap vector and swap map. 132 int addSwapEntry(MachineInstr *MI, PPCVSXSwapEntry &SwapEntry); 133 134 // Hunt backwards through COPY and SUBREG_TO_REG chains for a 135 // source register. VecIdx indicates the swap vector entry to 136 // mark as mentioning a physical register if the search leads 137 // to one. 138 unsigned lookThruCopyLike(unsigned SrcReg, unsigned VecIdx); 139 140 // Generate equivalence classes for related computations (webs). 141 void formWebs(); 142 143 // Analyze webs and determine those that cannot be optimized. 144 void recordUnoptimizableWebs(); 145 146 // Record which swap instructions can be safely removed. 147 void markSwapsForRemoval(); 148 149 // Remove swaps and update other instructions requiring special 150 // handling. Return true iff any changes are made. 151 bool removeSwaps(); 152 153 // Insert a swap instruction from SrcReg to DstReg at the given 154 // InsertPoint. 155 void insertSwap(MachineInstr *MI, MachineBasicBlock::iterator InsertPoint, 156 unsigned DstReg, unsigned SrcReg); 157 158 // Update instructions requiring special handling. 159 void handleSpecialSwappables(int EntryIdx); 160 161 // Dump a description of the entries in the swap vector. 162 void dumpSwapVector(); 163 164 // Return true iff the given register is in the given class. 165 bool isRegInClass(unsigned Reg, const TargetRegisterClass *RC) { 166 if (TargetRegisterInfo::isVirtualRegister(Reg)) 167 return RC->hasSubClassEq(MRI->getRegClass(Reg)); 168 return RC->contains(Reg); 169 } 170 171 // Return true iff the given register is a full vector register. 172 bool isVecReg(unsigned Reg) { 173 return (isRegInClass(Reg, &PPC::VSRCRegClass) || 174 isRegInClass(Reg, &PPC::VRRCRegClass)); 175 } 176 177 // Return true iff the given register is a partial vector register. 178 bool isScalarVecReg(unsigned Reg) { 179 return (isRegInClass(Reg, &PPC::VSFRCRegClass) || 180 isRegInClass(Reg, &PPC::VSSRCRegClass)); 181 } 182 183 // Return true iff the given register mentions all or part of a 184 // vector register. Also sets Partial to true if the mention 185 // is for just the floating-point register overlap of the register. 186 bool isAnyVecReg(unsigned Reg, bool &Partial) { 187 if (isScalarVecReg(Reg)) 188 Partial = true; 189 return isScalarVecReg(Reg) || isVecReg(Reg); 190 } 191 192 public: 193 // Main entry point for this pass. 194 bool runOnMachineFunction(MachineFunction &MF) override { 195 if (skipFunction(MF.getFunction())) 196 return false; 197 198 // If we don't have VSX on the subtarget, don't do anything. 199 // Also, on Power 9 the load and store ops preserve element order and so 200 // the swaps are not required. 201 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>(); 202 if (!STI.hasVSX() || !STI.needsSwapsForVSXMemOps()) 203 return false; 204 205 bool Changed = false; 206 initialize(MF); 207 208 if (gatherVectorInstructions()) { 209 formWebs(); 210 recordUnoptimizableWebs(); 211 markSwapsForRemoval(); 212 Changed = removeSwaps(); 213 } 214 215 // FIXME: See the allocation of EC in initialize(). 216 delete EC; 217 return Changed; 218 } 219 }; 220 221 // Initialize data structures for this pass. In particular, clear the 222 // swap vector and allocate the equivalence class mapping before 223 // processing each function. 224 void PPCVSXSwapRemoval::initialize(MachineFunction &MFParm) { 225 MF = &MFParm; 226 MRI = &MF->getRegInfo(); 227 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo(); 228 229 // An initial vector size of 256 appears to work well in practice. 230 // Small/medium functions with vector content tend not to incur a 231 // reallocation at this size. Three of the vector tests in 232 // projects/test-suite reallocate, which seems like a reasonable rate. 233 const int InitialVectorSize(256); 234 SwapVector.clear(); 235 SwapVector.reserve(InitialVectorSize); 236 237 // FIXME: Currently we allocate EC each time because we don't have 238 // access to the set representation on which to call clear(). Should 239 // consider adding a clear() method to the EquivalenceClasses class. 240 EC = new EquivalenceClasses<int>; 241 } 242 243 // Create an entry in the swap vector for each instruction that mentions 244 // a full vector register, recording various characteristics of the 245 // instructions there. 246 bool PPCVSXSwapRemoval::gatherVectorInstructions() { 247 bool RelevantFunction = false; 248 249 for (MachineBasicBlock &MBB : *MF) { 250 for (MachineInstr &MI : MBB) { 251 252 if (MI.isDebugInstr()) 253 continue; 254 255 bool RelevantInstr = false; 256 bool Partial = false; 257 258 for (const MachineOperand &MO : MI.operands()) { 259 if (!MO.isReg()) 260 continue; 261 unsigned Reg = MO.getReg(); 262 if (isAnyVecReg(Reg, Partial)) { 263 RelevantInstr = true; 264 break; 265 } 266 } 267 268 if (!RelevantInstr) 269 continue; 270 271 RelevantFunction = true; 272 273 // Create a SwapEntry initialized to zeros, then fill in the 274 // instruction and ID fields before pushing it to the back 275 // of the swap vector. 276 PPCVSXSwapEntry SwapEntry{}; 277 int VecIdx = addSwapEntry(&MI, SwapEntry); 278 279 switch(MI.getOpcode()) { 280 default: 281 // Unless noted otherwise, an instruction is considered 282 // safe for the optimization. There are a large number of 283 // such true-SIMD instructions (all vector math, logical, 284 // select, compare, etc.). However, if the instruction 285 // mentions a partial vector register and does not have 286 // special handling defined, it is not swappable. 287 if (Partial) 288 SwapVector[VecIdx].MentionsPartialVR = 1; 289 else 290 SwapVector[VecIdx].IsSwappable = 1; 291 break; 292 case PPC::XXPERMDI: { 293 // This is a swap if it is of the form XXPERMDI t, s, s, 2. 294 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we 295 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2, 296 // for example. We have to look through chains of COPY and 297 // SUBREG_TO_REG to find the real source value for comparison. 298 // If the real source value is a physical register, then mark the 299 // XXPERMDI as mentioning a physical register. 300 int immed = MI.getOperand(3).getImm(); 301 if (immed == 2) { 302 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(), 303 VecIdx); 304 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(), 305 VecIdx); 306 if (trueReg1 == trueReg2) 307 SwapVector[VecIdx].IsSwap = 1; 308 else { 309 // We can still handle these if the two registers are not 310 // identical, by adjusting the form of the XXPERMDI. 311 SwapVector[VecIdx].IsSwappable = 1; 312 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI; 313 } 314 // This is a doubleword splat if it is of the form 315 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we 316 // must look through chains of copy-likes to find the source 317 // register. We turn off the marking for mention of a physical 318 // register, because splatting it is safe; the optimization 319 // will not swap the value in the physical register. Whether 320 // or not the two input registers are identical, we can handle 321 // these by adjusting the form of the XXPERMDI. 322 } else if (immed == 0 || immed == 3) { 323 324 SwapVector[VecIdx].IsSwappable = 1; 325 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI; 326 327 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(), 328 VecIdx); 329 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(), 330 VecIdx); 331 if (trueReg1 == trueReg2) 332 SwapVector[VecIdx].MentionsPhysVR = 0; 333 334 } else { 335 // We can still handle these by adjusting the form of the XXPERMDI. 336 SwapVector[VecIdx].IsSwappable = 1; 337 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI; 338 } 339 break; 340 } 341 case PPC::LVX: 342 // Non-permuting loads are currently unsafe. We can use special 343 // handling for this in the future. By not marking these as 344 // IsSwap, we ensure computations containing them will be rejected 345 // for now. 346 SwapVector[VecIdx].IsLoad = 1; 347 break; 348 case PPC::LXVD2X: 349 case PPC::LXVW4X: 350 // Permuting loads are marked as both load and swap, and are 351 // safe for optimization. 352 SwapVector[VecIdx].IsLoad = 1; 353 SwapVector[VecIdx].IsSwap = 1; 354 break; 355 case PPC::LXSDX: 356 case PPC::LXSSPX: 357 case PPC::XFLOADf64: 358 case PPC::XFLOADf32: 359 // A load of a floating-point value into the high-order half of 360 // a vector register is safe, provided that we introduce a swap 361 // following the load, which will be done by the SUBREG_TO_REG 362 // support. So just mark these as safe. 363 SwapVector[VecIdx].IsLoad = 1; 364 SwapVector[VecIdx].IsSwappable = 1; 365 break; 366 case PPC::STVX: 367 // Non-permuting stores are currently unsafe. We can use special 368 // handling for this in the future. By not marking these as 369 // IsSwap, we ensure computations containing them will be rejected 370 // for now. 371 SwapVector[VecIdx].IsStore = 1; 372 break; 373 case PPC::STXVD2X: 374 case PPC::STXVW4X: 375 // Permuting stores are marked as both store and swap, and are 376 // safe for optimization. 377 SwapVector[VecIdx].IsStore = 1; 378 SwapVector[VecIdx].IsSwap = 1; 379 break; 380 case PPC::COPY: 381 // These are fine provided they are moving between full vector 382 // register classes. 383 if (isVecReg(MI.getOperand(0).getReg()) && 384 isVecReg(MI.getOperand(1).getReg())) 385 SwapVector[VecIdx].IsSwappable = 1; 386 // If we have a copy from one scalar floating-point register 387 // to another, we can accept this even if it is a physical 388 // register. The only way this gets involved is if it feeds 389 // a SUBREG_TO_REG, which is handled by introducing a swap. 390 else if (isScalarVecReg(MI.getOperand(0).getReg()) && 391 isScalarVecReg(MI.getOperand(1).getReg())) 392 SwapVector[VecIdx].IsSwappable = 1; 393 break; 394 case PPC::SUBREG_TO_REG: { 395 // These are fine provided they are moving between full vector 396 // register classes. If they are moving from a scalar 397 // floating-point class to a vector class, we can handle those 398 // as well, provided we introduce a swap. It is generally the 399 // case that we will introduce fewer swaps than we remove, but 400 // (FIXME) a cost model could be used. However, introduced 401 // swaps could potentially be CSEd, so this is not trivial. 402 if (isVecReg(MI.getOperand(0).getReg()) && 403 isVecReg(MI.getOperand(2).getReg())) 404 SwapVector[VecIdx].IsSwappable = 1; 405 else if (isVecReg(MI.getOperand(0).getReg()) && 406 isScalarVecReg(MI.getOperand(2).getReg())) { 407 SwapVector[VecIdx].IsSwappable = 1; 408 SwapVector[VecIdx].SpecialHandling = SHValues::SH_COPYWIDEN; 409 } 410 break; 411 } 412 case PPC::VSPLTB: 413 case PPC::VSPLTH: 414 case PPC::VSPLTW: 415 case PPC::XXSPLTW: 416 // Splats are lane-sensitive, but we can use special handling 417 // to adjust the source lane for the splat. 418 SwapVector[VecIdx].IsSwappable = 1; 419 SwapVector[VecIdx].SpecialHandling = SHValues::SH_SPLAT; 420 break; 421 // The presence of the following lane-sensitive operations in a 422 // web will kill the optimization, at least for now. For these 423 // we do nothing, causing the optimization to fail. 424 // FIXME: Some of these could be permitted with special handling, 425 // and will be phased in as time permits. 426 // FIXME: There is no simple and maintainable way to express a set 427 // of opcodes having a common attribute in TableGen. Should this 428 // change, this is a prime candidate to use such a mechanism. 429 case PPC::INLINEASM: 430 case PPC::EXTRACT_SUBREG: 431 case PPC::INSERT_SUBREG: 432 case PPC::COPY_TO_REGCLASS: 433 case PPC::LVEBX: 434 case PPC::LVEHX: 435 case PPC::LVEWX: 436 case PPC::LVSL: 437 case PPC::LVSR: 438 case PPC::LVXL: 439 case PPC::STVEBX: 440 case PPC::STVEHX: 441 case PPC::STVEWX: 442 case PPC::STVXL: 443 // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX, 444 // by adding special handling for narrowing copies as well as 445 // widening ones. However, I've experimented with this, and in 446 // practice we currently do not appear to use STXSDX fed by 447 // a narrowing copy from a full vector register. Since I can't 448 // generate any useful test cases, I've left this alone for now. 449 case PPC::STXSDX: 450 case PPC::STXSSPX: 451 case PPC::VCIPHER: 452 case PPC::VCIPHERLAST: 453 case PPC::VMRGHB: 454 case PPC::VMRGHH: 455 case PPC::VMRGHW: 456 case PPC::VMRGLB: 457 case PPC::VMRGLH: 458 case PPC::VMRGLW: 459 case PPC::VMULESB: 460 case PPC::VMULESH: 461 case PPC::VMULESW: 462 case PPC::VMULEUB: 463 case PPC::VMULEUH: 464 case PPC::VMULEUW: 465 case PPC::VMULOSB: 466 case PPC::VMULOSH: 467 case PPC::VMULOSW: 468 case PPC::VMULOUB: 469 case PPC::VMULOUH: 470 case PPC::VMULOUW: 471 case PPC::VNCIPHER: 472 case PPC::VNCIPHERLAST: 473 case PPC::VPERM: 474 case PPC::VPERMXOR: 475 case PPC::VPKPX: 476 case PPC::VPKSHSS: 477 case PPC::VPKSHUS: 478 case PPC::VPKSDSS: 479 case PPC::VPKSDUS: 480 case PPC::VPKSWSS: 481 case PPC::VPKSWUS: 482 case PPC::VPKUDUM: 483 case PPC::VPKUDUS: 484 case PPC::VPKUHUM: 485 case PPC::VPKUHUS: 486 case PPC::VPKUWUM: 487 case PPC::VPKUWUS: 488 case PPC::VPMSUMB: 489 case PPC::VPMSUMD: 490 case PPC::VPMSUMH: 491 case PPC::VPMSUMW: 492 case PPC::VRLB: 493 case PPC::VRLD: 494 case PPC::VRLH: 495 case PPC::VRLW: 496 case PPC::VSBOX: 497 case PPC::VSHASIGMAD: 498 case PPC::VSHASIGMAW: 499 case PPC::VSL: 500 case PPC::VSLDOI: 501 case PPC::VSLO: 502 case PPC::VSR: 503 case PPC::VSRO: 504 case PPC::VSUM2SWS: 505 case PPC::VSUM4SBS: 506 case PPC::VSUM4SHS: 507 case PPC::VSUM4UBS: 508 case PPC::VSUMSWS: 509 case PPC::VUPKHPX: 510 case PPC::VUPKHSB: 511 case PPC::VUPKHSH: 512 case PPC::VUPKHSW: 513 case PPC::VUPKLPX: 514 case PPC::VUPKLSB: 515 case PPC::VUPKLSH: 516 case PPC::VUPKLSW: 517 case PPC::XXMRGHW: 518 case PPC::XXMRGLW: 519 // XXSLDWI could be replaced by a general permute with one of three 520 // permute control vectors (for shift values 1, 2, 3). However, 521 // VPERM has a more restrictive register class. 522 case PPC::XXSLDWI: 523 case PPC::XSCVDPSPN: 524 case PPC::XSCVSPDPN: 525 break; 526 } 527 } 528 } 529 530 if (RelevantFunction) { 531 DEBUG(dbgs() << "Swap vector when first built\n\n"); 532 DEBUG(dumpSwapVector()); 533 } 534 535 return RelevantFunction; 536 } 537 538 // Add an entry to the swap vector and swap map, and make a 539 // singleton equivalence class for the entry. 540 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr *MI, 541 PPCVSXSwapEntry& SwapEntry) { 542 SwapEntry.VSEMI = MI; 543 SwapEntry.VSEId = SwapVector.size(); 544 SwapVector.push_back(SwapEntry); 545 EC->insert(SwapEntry.VSEId); 546 SwapMap[MI] = SwapEntry.VSEId; 547 return SwapEntry.VSEId; 548 } 549 550 // This is used to find the "true" source register for an 551 // XXPERMDI instruction, since MachineCSE does not handle the 552 // "copy-like" operations (Copy and SubregToReg). Returns 553 // the original SrcReg unless it is the target of a copy-like 554 // operation, in which case we chain backwards through all 555 // such operations to the ultimate source register. If a 556 // physical register is encountered, we stop the search and 557 // flag the swap entry indicated by VecIdx (the original 558 // XXPERMDI) as mentioning a physical register. 559 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg, 560 unsigned VecIdx) { 561 MachineInstr *MI = MRI->getVRegDef(SrcReg); 562 if (!MI->isCopyLike()) 563 return SrcReg; 564 565 unsigned CopySrcReg; 566 if (MI->isCopy()) 567 CopySrcReg = MI->getOperand(1).getReg(); 568 else { 569 assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike"); 570 CopySrcReg = MI->getOperand(2).getReg(); 571 } 572 573 if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg)) { 574 if (!isScalarVecReg(CopySrcReg)) 575 SwapVector[VecIdx].MentionsPhysVR = 1; 576 return CopySrcReg; 577 } 578 579 return lookThruCopyLike(CopySrcReg, VecIdx); 580 } 581 582 // Generate equivalence classes for related computations (webs) by 583 // def-use relationships of virtual registers. Mention of a physical 584 // register terminates the generation of equivalence classes as this 585 // indicates a use of a parameter, definition of a return value, use 586 // of a value returned from a call, or definition of a parameter to a 587 // call. Computations with physical register mentions are flagged 588 // as such so their containing webs will not be optimized. 589 void PPCVSXSwapRemoval::formWebs() { 590 591 DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n"); 592 593 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) { 594 595 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 596 597 DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " "); 598 DEBUG(MI->dump()); 599 600 // It's sufficient to walk vector uses and join them to their unique 601 // definitions. In addition, check full vector register operands 602 // for physical regs. We exclude partial-vector register operands 603 // because we can handle them if copied to a full vector. 604 for (const MachineOperand &MO : MI->operands()) { 605 if (!MO.isReg()) 606 continue; 607 608 unsigned Reg = MO.getReg(); 609 if (!isVecReg(Reg) && !isScalarVecReg(Reg)) 610 continue; 611 612 if (!TargetRegisterInfo::isVirtualRegister(Reg)) { 613 if (!(MI->isCopy() && isScalarVecReg(Reg))) 614 SwapVector[EntryIdx].MentionsPhysVR = 1; 615 continue; 616 } 617 618 if (!MO.isUse()) 619 continue; 620 621 MachineInstr* DefMI = MRI->getVRegDef(Reg); 622 assert(SwapMap.find(DefMI) != SwapMap.end() && 623 "Inconsistency: def of vector reg not found in swap map!"); 624 int DefIdx = SwapMap[DefMI]; 625 (void)EC->unionSets(SwapVector[DefIdx].VSEId, 626 SwapVector[EntryIdx].VSEId); 627 628 DEBUG(dbgs() << format("Unioning %d with %d\n", SwapVector[DefIdx].VSEId, 629 SwapVector[EntryIdx].VSEId)); 630 DEBUG(dbgs() << " Def: "); 631 DEBUG(DefMI->dump()); 632 } 633 } 634 } 635 636 // Walk the swap vector entries looking for conditions that prevent their 637 // containing computations from being optimized. When such conditions are 638 // found, mark the representative of the computation's equivalence class 639 // as rejected. 640 void PPCVSXSwapRemoval::recordUnoptimizableWebs() { 641 642 DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n"); 643 644 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) { 645 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId); 646 647 // If representative is already rejected, don't waste further time. 648 if (SwapVector[Repr].WebRejected) 649 continue; 650 651 // Reject webs containing mentions of physical or partial registers, or 652 // containing operations that we don't know how to handle in a lane- 653 // permuted region. 654 if (SwapVector[EntryIdx].MentionsPhysVR || 655 SwapVector[EntryIdx].MentionsPartialVR || 656 !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) { 657 658 SwapVector[Repr].WebRejected = 1; 659 660 DEBUG(dbgs() << 661 format("Web %d rejected for physreg, partial reg, or not " 662 "swap[pable]\n", Repr)); 663 DEBUG(dbgs() << " in " << EntryIdx << ": "); 664 DEBUG(SwapVector[EntryIdx].VSEMI->dump()); 665 DEBUG(dbgs() << "\n"); 666 } 667 668 // Reject webs than contain swapping loads that feed something other 669 // than a swap instruction. 670 else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) { 671 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 672 unsigned DefReg = MI->getOperand(0).getReg(); 673 674 // We skip debug instructions in the analysis. (Note that debug 675 // location information is still maintained by this optimization 676 // because it remains on the LXVD2X and STXVD2X instructions after 677 // the XXPERMDIs are removed.) 678 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) { 679 int UseIdx = SwapMap[&UseMI]; 680 681 if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad || 682 SwapVector[UseIdx].IsStore) { 683 684 SwapVector[Repr].WebRejected = 1; 685 686 DEBUG(dbgs() << 687 format("Web %d rejected for load not feeding swap\n", Repr)); 688 DEBUG(dbgs() << " def " << EntryIdx << ": "); 689 DEBUG(MI->dump()); 690 DEBUG(dbgs() << " use " << UseIdx << ": "); 691 DEBUG(UseMI.dump()); 692 DEBUG(dbgs() << "\n"); 693 } 694 } 695 696 // Reject webs that contain swapping stores that are fed by something 697 // other than a swap instruction. 698 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) { 699 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 700 unsigned UseReg = MI->getOperand(0).getReg(); 701 MachineInstr *DefMI = MRI->getVRegDef(UseReg); 702 unsigned DefReg = DefMI->getOperand(0).getReg(); 703 int DefIdx = SwapMap[DefMI]; 704 705 if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad || 706 SwapVector[DefIdx].IsStore) { 707 708 SwapVector[Repr].WebRejected = 1; 709 710 DEBUG(dbgs() << 711 format("Web %d rejected for store not fed by swap\n", Repr)); 712 DEBUG(dbgs() << " def " << DefIdx << ": "); 713 DEBUG(DefMI->dump()); 714 DEBUG(dbgs() << " use " << EntryIdx << ": "); 715 DEBUG(MI->dump()); 716 DEBUG(dbgs() << "\n"); 717 } 718 719 // Ensure all uses of the register defined by DefMI feed store 720 // instructions 721 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) { 722 int UseIdx = SwapMap[&UseMI]; 723 724 if (SwapVector[UseIdx].VSEMI->getOpcode() != MI->getOpcode()) { 725 SwapVector[Repr].WebRejected = 1; 726 727 DEBUG(dbgs() << 728 format("Web %d rejected for swap not feeding only stores\n", 729 Repr)); 730 DEBUG(dbgs() << " def " << " : "); 731 DEBUG(DefMI->dump()); 732 DEBUG(dbgs() << " use " << UseIdx << ": "); 733 DEBUG(SwapVector[UseIdx].VSEMI->dump()); 734 DEBUG(dbgs() << "\n"); 735 } 736 } 737 } 738 } 739 740 DEBUG(dbgs() << "Swap vector after web analysis:\n\n"); 741 DEBUG(dumpSwapVector()); 742 } 743 744 // Walk the swap vector entries looking for swaps fed by permuting loads 745 // and swaps that feed permuting stores. If the containing computation 746 // has not been marked rejected, mark each such swap for removal. 747 // (Removal is delayed in case optimization has disturbed the pattern, 748 // such that multiple loads feed the same swap, etc.) 749 void PPCVSXSwapRemoval::markSwapsForRemoval() { 750 751 DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n"); 752 753 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) { 754 755 if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) { 756 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId); 757 758 if (!SwapVector[Repr].WebRejected) { 759 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 760 unsigned DefReg = MI->getOperand(0).getReg(); 761 762 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) { 763 int UseIdx = SwapMap[&UseMI]; 764 SwapVector[UseIdx].WillRemove = 1; 765 766 DEBUG(dbgs() << "Marking swap fed by load for removal: "); 767 DEBUG(UseMI.dump()); 768 } 769 } 770 771 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) { 772 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId); 773 774 if (!SwapVector[Repr].WebRejected) { 775 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 776 unsigned UseReg = MI->getOperand(0).getReg(); 777 MachineInstr *DefMI = MRI->getVRegDef(UseReg); 778 int DefIdx = SwapMap[DefMI]; 779 SwapVector[DefIdx].WillRemove = 1; 780 781 DEBUG(dbgs() << "Marking swap feeding store for removal: "); 782 DEBUG(DefMI->dump()); 783 } 784 785 } else if (SwapVector[EntryIdx].IsSwappable && 786 SwapVector[EntryIdx].SpecialHandling != 0) { 787 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId); 788 789 if (!SwapVector[Repr].WebRejected) 790 handleSpecialSwappables(EntryIdx); 791 } 792 } 793 } 794 795 // Create an xxswapd instruction and insert it prior to the given point. 796 // MI is used to determine basic block and debug loc information. 797 // FIXME: When inserting a swap, we should check whether SrcReg is 798 // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so, 799 // then instead we should generate a copy from Reg to DstReg. 800 void PPCVSXSwapRemoval::insertSwap(MachineInstr *MI, 801 MachineBasicBlock::iterator InsertPoint, 802 unsigned DstReg, unsigned SrcReg) { 803 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(), 804 TII->get(PPC::XXPERMDI), DstReg) 805 .addReg(SrcReg) 806 .addReg(SrcReg) 807 .addImm(2); 808 } 809 810 // The identified swap entry requires special handling to allow its 811 // containing computation to be optimized. Perform that handling 812 // here. 813 // FIXME: Additional opportunities will be phased in with subsequent 814 // patches. 815 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) { 816 switch (SwapVector[EntryIdx].SpecialHandling) { 817 818 default: 819 llvm_unreachable("Unexpected special handling type"); 820 821 // For splats based on an index into a vector, add N/2 modulo N 822 // to the index, where N is the number of vector elements. 823 case SHValues::SH_SPLAT: { 824 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 825 unsigned NElts; 826 827 DEBUG(dbgs() << "Changing splat: "); 828 DEBUG(MI->dump()); 829 830 switch (MI->getOpcode()) { 831 default: 832 llvm_unreachable("Unexpected splat opcode"); 833 case PPC::VSPLTB: NElts = 16; break; 834 case PPC::VSPLTH: NElts = 8; break; 835 case PPC::VSPLTW: 836 case PPC::XXSPLTW: NElts = 4; break; 837 } 838 839 unsigned EltNo; 840 if (MI->getOpcode() == PPC::XXSPLTW) 841 EltNo = MI->getOperand(2).getImm(); 842 else 843 EltNo = MI->getOperand(1).getImm(); 844 845 EltNo = (EltNo + NElts / 2) % NElts; 846 if (MI->getOpcode() == PPC::XXSPLTW) 847 MI->getOperand(2).setImm(EltNo); 848 else 849 MI->getOperand(1).setImm(EltNo); 850 851 DEBUG(dbgs() << " Into: "); 852 DEBUG(MI->dump()); 853 break; 854 } 855 856 // For an XXPERMDI that isn't handled otherwise, we need to 857 // reverse the order of the operands. If the selector operand 858 // has a value of 0 or 3, we need to change it to 3 or 0, 859 // respectively. Otherwise we should leave it alone. (This 860 // is equivalent to reversing the two bits of the selector 861 // operand and complementing the result.) 862 case SHValues::SH_XXPERMDI: { 863 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 864 865 DEBUG(dbgs() << "Changing XXPERMDI: "); 866 DEBUG(MI->dump()); 867 868 unsigned Selector = MI->getOperand(3).getImm(); 869 if (Selector == 0 || Selector == 3) 870 Selector = 3 - Selector; 871 MI->getOperand(3).setImm(Selector); 872 873 unsigned Reg1 = MI->getOperand(1).getReg(); 874 unsigned Reg2 = MI->getOperand(2).getReg(); 875 MI->getOperand(1).setReg(Reg2); 876 MI->getOperand(2).setReg(Reg1); 877 878 DEBUG(dbgs() << " Into: "); 879 DEBUG(MI->dump()); 880 break; 881 } 882 883 // For a copy from a scalar floating-point register to a vector 884 // register, removing swaps will leave the copied value in the 885 // wrong lane. Insert a swap following the copy to fix this. 886 case SHValues::SH_COPYWIDEN: { 887 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 888 889 DEBUG(dbgs() << "Changing SUBREG_TO_REG: "); 890 DEBUG(MI->dump()); 891 892 unsigned DstReg = MI->getOperand(0).getReg(); 893 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg); 894 unsigned NewVReg = MRI->createVirtualRegister(DstRC); 895 896 MI->getOperand(0).setReg(NewVReg); 897 DEBUG(dbgs() << " Into: "); 898 DEBUG(MI->dump()); 899 900 auto InsertPoint = ++MachineBasicBlock::iterator(MI); 901 902 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG 903 // is copying to a VRRC, we need to be careful to avoid a register 904 // assignment problem. In this case we must copy from VRRC to VSRC 905 // prior to the swap, and from VSRC to VRRC following the swap. 906 // Coalescing will usually remove all this mess. 907 if (DstRC == &PPC::VRRCRegClass) { 908 unsigned VSRCTmp1 = MRI->createVirtualRegister(&PPC::VSRCRegClass); 909 unsigned VSRCTmp2 = MRI->createVirtualRegister(&PPC::VSRCRegClass); 910 911 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(), 912 TII->get(PPC::COPY), VSRCTmp1) 913 .addReg(NewVReg); 914 DEBUG(std::prev(InsertPoint)->dump()); 915 916 insertSwap(MI, InsertPoint, VSRCTmp2, VSRCTmp1); 917 DEBUG(std::prev(InsertPoint)->dump()); 918 919 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(), 920 TII->get(PPC::COPY), DstReg) 921 .addReg(VSRCTmp2); 922 DEBUG(std::prev(InsertPoint)->dump()); 923 924 } else { 925 insertSwap(MI, InsertPoint, DstReg, NewVReg); 926 DEBUG(std::prev(InsertPoint)->dump()); 927 } 928 break; 929 } 930 } 931 } 932 933 // Walk the swap vector and replace each entry marked for removal with 934 // a copy operation. 935 bool PPCVSXSwapRemoval::removeSwaps() { 936 937 DEBUG(dbgs() << "\n*** Removing swaps ***\n\n"); 938 939 bool Changed = false; 940 941 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) { 942 if (SwapVector[EntryIdx].WillRemove) { 943 Changed = true; 944 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 945 MachineBasicBlock *MBB = MI->getParent(); 946 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY), 947 MI->getOperand(0).getReg()) 948 .add(MI->getOperand(1)); 949 950 DEBUG(dbgs() << format("Replaced %d with copy: ", 951 SwapVector[EntryIdx].VSEId)); 952 DEBUG(MI->dump()); 953 954 MI->eraseFromParent(); 955 } 956 } 957 958 return Changed; 959 } 960 961 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 962 // For debug purposes, dump the contents of the swap vector. 963 LLVM_DUMP_METHOD void PPCVSXSwapRemoval::dumpSwapVector() { 964 965 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) { 966 967 MachineInstr *MI = SwapVector[EntryIdx].VSEMI; 968 int ID = SwapVector[EntryIdx].VSEId; 969 970 dbgs() << format("%6d", ID); 971 dbgs() << format("%6d", EC->getLeaderValue(ID)); 972 dbgs() << format(" %bb.%3d", MI->getParent()->getNumber()); 973 dbgs() << format(" %14s ", TII->getName(MI->getOpcode()).str().c_str()); 974 975 if (SwapVector[EntryIdx].IsLoad) 976 dbgs() << "load "; 977 if (SwapVector[EntryIdx].IsStore) 978 dbgs() << "store "; 979 if (SwapVector[EntryIdx].IsSwap) 980 dbgs() << "swap "; 981 if (SwapVector[EntryIdx].MentionsPhysVR) 982 dbgs() << "physreg "; 983 if (SwapVector[EntryIdx].MentionsPartialVR) 984 dbgs() << "partialreg "; 985 986 if (SwapVector[EntryIdx].IsSwappable) { 987 dbgs() << "swappable "; 988 switch(SwapVector[EntryIdx].SpecialHandling) { 989 default: 990 dbgs() << "special:**unknown**"; 991 break; 992 case SH_NONE: 993 break; 994 case SH_EXTRACT: 995 dbgs() << "special:extract "; 996 break; 997 case SH_INSERT: 998 dbgs() << "special:insert "; 999 break; 1000 case SH_NOSWAP_LD: 1001 dbgs() << "special:load "; 1002 break; 1003 case SH_NOSWAP_ST: 1004 dbgs() << "special:store "; 1005 break; 1006 case SH_SPLAT: 1007 dbgs() << "special:splat "; 1008 break; 1009 case SH_XXPERMDI: 1010 dbgs() << "special:xxpermdi "; 1011 break; 1012 case SH_COPYWIDEN: 1013 dbgs() << "special:copywiden "; 1014 break; 1015 } 1016 } 1017 1018 if (SwapVector[EntryIdx].WebRejected) 1019 dbgs() << "rejected "; 1020 if (SwapVector[EntryIdx].WillRemove) 1021 dbgs() << "remove "; 1022 1023 dbgs() << "\n"; 1024 1025 // For no-asserts builds. 1026 (void)MI; 1027 (void)ID; 1028 } 1029 1030 dbgs() << "\n"; 1031 } 1032 #endif 1033 1034 } // end default namespace 1035 1036 INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval, DEBUG_TYPE, 1037 "PowerPC VSX Swap Removal", false, false) 1038 INITIALIZE_PASS_END(PPCVSXSwapRemoval, DEBUG_TYPE, 1039 "PowerPC VSX Swap Removal", false, false) 1040 1041 char PPCVSXSwapRemoval::ID = 0; 1042 FunctionPass* 1043 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); } 1044