1 //===-- WebAssemblyRegStackify.cpp - Register Stackification --------------===// 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 /// \file 11 /// This file implements a register stacking pass. 12 /// 13 /// This pass reorders instructions to put register uses and defs in an order 14 /// such that they form single-use expression trees. Registers fitting this form 15 /// are then marked as "stackified", meaning references to them are replaced by 16 /// "push" and "pop" from the value stack. 17 /// 18 /// This is primarily a code size optimization, since temporary values on the 19 /// value stack don't need to be named. 20 /// 21 //===----------------------------------------------------------------------===// 22 23 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_* 24 #include "WebAssembly.h" 25 #include "WebAssemblyMachineFunctionInfo.h" 26 #include "WebAssemblySubtarget.h" 27 #include "WebAssemblyUtilities.h" 28 #include "llvm/Analysis/AliasAnalysis.h" 29 #include "llvm/CodeGen/LiveIntervals.h" 30 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 31 #include "llvm/CodeGen/MachineDominators.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/Passes.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/raw_ostream.h" 38 using namespace llvm; 39 40 #define DEBUG_TYPE "wasm-reg-stackify" 41 42 namespace { 43 class WebAssemblyRegStackify final : public MachineFunctionPass { 44 StringRef getPassName() const override { 45 return "WebAssembly Register Stackify"; 46 } 47 48 void getAnalysisUsage(AnalysisUsage &AU) const override { 49 AU.setPreservesCFG(); 50 AU.addRequired<AAResultsWrapperPass>(); 51 AU.addRequired<MachineDominatorTree>(); 52 AU.addRequired<LiveIntervals>(); 53 AU.addPreserved<MachineBlockFrequencyInfo>(); 54 AU.addPreserved<SlotIndexes>(); 55 AU.addPreserved<LiveIntervals>(); 56 AU.addPreservedID(LiveVariablesID); 57 AU.addPreserved<MachineDominatorTree>(); 58 MachineFunctionPass::getAnalysisUsage(AU); 59 } 60 61 bool runOnMachineFunction(MachineFunction &MF) override; 62 63 public: 64 static char ID; // Pass identification, replacement for typeid 65 WebAssemblyRegStackify() : MachineFunctionPass(ID) {} 66 }; 67 } // end anonymous namespace 68 69 char WebAssemblyRegStackify::ID = 0; 70 INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE, 71 "Reorder instructions to use the WebAssembly value stack", 72 false, false) 73 74 FunctionPass *llvm::createWebAssemblyRegStackify() { 75 return new WebAssemblyRegStackify(); 76 } 77 78 // Decorate the given instruction with implicit operands that enforce the 79 // expression stack ordering constraints for an instruction which is on 80 // the expression stack. 81 static void ImposeStackOrdering(MachineInstr *MI) { 82 // Write the opaque VALUE_STACK register. 83 if (!MI->definesRegister(WebAssembly::VALUE_STACK)) 84 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK, 85 /*isDef=*/true, 86 /*isImp=*/true)); 87 88 // Also read the opaque VALUE_STACK register. 89 if (!MI->readsRegister(WebAssembly::VALUE_STACK)) 90 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK, 91 /*isDef=*/false, 92 /*isImp=*/true)); 93 } 94 95 // Convert an IMPLICIT_DEF instruction into an instruction which defines 96 // a constant zero value. 97 static void ConvertImplicitDefToConstZero(MachineInstr *MI, 98 MachineRegisterInfo &MRI, 99 const TargetInstrInfo *TII, 100 MachineFunction &MF) { 101 assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF); 102 103 const auto *RegClass = 104 MRI.getRegClass(MI->getOperand(0).getReg()); 105 if (RegClass == &WebAssembly::I32RegClass) { 106 MI->setDesc(TII->get(WebAssembly::CONST_I32)); 107 MI->addOperand(MachineOperand::CreateImm(0)); 108 } else if (RegClass == &WebAssembly::I64RegClass) { 109 MI->setDesc(TII->get(WebAssembly::CONST_I64)); 110 MI->addOperand(MachineOperand::CreateImm(0)); 111 } else if (RegClass == &WebAssembly::F32RegClass) { 112 MI->setDesc(TII->get(WebAssembly::CONST_F32)); 113 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue( 114 Type::getFloatTy(MF.getFunction().getContext()))); 115 MI->addOperand(MachineOperand::CreateFPImm(Val)); 116 } else if (RegClass == &WebAssembly::F64RegClass) { 117 MI->setDesc(TII->get(WebAssembly::CONST_F64)); 118 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue( 119 Type::getDoubleTy(MF.getFunction().getContext()))); 120 MI->addOperand(MachineOperand::CreateFPImm(Val)); 121 } else { 122 llvm_unreachable("Unexpected reg class"); 123 } 124 } 125 126 // Determine whether a call to the callee referenced by 127 // MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side 128 // effects. 129 static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read, 130 bool &Write, bool &Effects, bool &StackPointer) { 131 // All calls can use the stack pointer. 132 StackPointer = true; 133 134 const MachineOperand &MO = MI.getOperand(CalleeOpNo); 135 if (MO.isGlobal()) { 136 const Constant *GV = MO.getGlobal(); 137 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 138 if (!GA->isInterposable()) 139 GV = GA->getAliasee(); 140 141 if (const Function *F = dyn_cast<Function>(GV)) { 142 if (!F->doesNotThrow()) 143 Effects = true; 144 if (F->doesNotAccessMemory()) 145 return; 146 if (F->onlyReadsMemory()) { 147 Read = true; 148 return; 149 } 150 } 151 } 152 153 // Assume the worst. 154 Write = true; 155 Read = true; 156 Effects = true; 157 } 158 159 // Determine whether MI reads memory, writes memory, has side effects, 160 // and/or uses the stack pointer value. 161 static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read, 162 bool &Write, bool &Effects, bool &StackPointer) { 163 assert(!MI.isPosition()); 164 assert(!MI.isTerminator()); 165 166 if (MI.isDebugInstr()) 167 return; 168 169 // Check for loads. 170 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA)) 171 Read = true; 172 173 // Check for stores. 174 if (MI.mayStore()) { 175 Write = true; 176 177 // Check for stores to __stack_pointer. 178 for (auto MMO : MI.memoperands()) { 179 const MachinePointerInfo &MPI = MMO->getPointerInfo(); 180 if (MPI.V.is<const PseudoSourceValue *>()) { 181 auto PSV = MPI.V.get<const PseudoSourceValue *>(); 182 if (const ExternalSymbolPseudoSourceValue *EPSV = 183 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV)) 184 if (StringRef(EPSV->getSymbol()) == "__stack_pointer") { 185 StackPointer = true; 186 } 187 } 188 } 189 } else if (MI.hasOrderedMemoryRef()) { 190 switch (MI.getOpcode()) { 191 case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64: 192 case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64: 193 case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64: 194 case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64: 195 case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32: 196 case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64: 197 case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32: 198 case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64: 199 // These instruction have hasUnmodeledSideEffects() returning true 200 // because they trap on overflow and invalid so they can't be arbitrarily 201 // moved, however hasOrderedMemoryRef() interprets this plus their lack 202 // of memoperands as having a potential unknown memory reference. 203 break; 204 default: 205 // Record volatile accesses, unless it's a call, as calls are handled 206 // specially below. 207 if (!MI.isCall()) { 208 Write = true; 209 Effects = true; 210 } 211 break; 212 } 213 } 214 215 // Check for side effects. 216 if (MI.hasUnmodeledSideEffects()) { 217 switch (MI.getOpcode()) { 218 case WebAssembly::DIV_S_I32: case WebAssembly::DIV_S_I64: 219 case WebAssembly::REM_S_I32: case WebAssembly::REM_S_I64: 220 case WebAssembly::DIV_U_I32: case WebAssembly::DIV_U_I64: 221 case WebAssembly::REM_U_I32: case WebAssembly::REM_U_I64: 222 case WebAssembly::I32_TRUNC_S_F32: case WebAssembly::I64_TRUNC_S_F32: 223 case WebAssembly::I32_TRUNC_S_F64: case WebAssembly::I64_TRUNC_S_F64: 224 case WebAssembly::I32_TRUNC_U_F32: case WebAssembly::I64_TRUNC_U_F32: 225 case WebAssembly::I32_TRUNC_U_F64: case WebAssembly::I64_TRUNC_U_F64: 226 // These instructions have hasUnmodeledSideEffects() returning true 227 // because they trap on overflow and invalid so they can't be arbitrarily 228 // moved, however in the specific case of register stackifying, it is safe 229 // to move them because overflow and invalid are Undefined Behavior. 230 break; 231 default: 232 Effects = true; 233 break; 234 } 235 } 236 237 // Analyze calls. 238 if (MI.isCall()) { 239 switch (MI.getOpcode()) { 240 case WebAssembly::CALL_VOID: 241 case WebAssembly::CALL_INDIRECT_VOID: 242 QueryCallee(MI, 0, Read, Write, Effects, StackPointer); 243 break; 244 case WebAssembly::CALL_I32: case WebAssembly::CALL_I64: 245 case WebAssembly::CALL_F32: case WebAssembly::CALL_F64: 246 case WebAssembly::CALL_INDIRECT_I32: case WebAssembly::CALL_INDIRECT_I64: 247 case WebAssembly::CALL_INDIRECT_F32: case WebAssembly::CALL_INDIRECT_F64: 248 QueryCallee(MI, 1, Read, Write, Effects, StackPointer); 249 break; 250 default: 251 llvm_unreachable("unexpected call opcode"); 252 } 253 } 254 } 255 256 // Test whether Def is safe and profitable to rematerialize. 257 static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA, 258 const WebAssemblyInstrInfo *TII) { 259 return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA); 260 } 261 262 // Identify the definition for this register at this point. This is a 263 // generalization of MachineRegisterInfo::getUniqueVRegDef that uses 264 // LiveIntervals to handle complex cases. 265 static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert, 266 const MachineRegisterInfo &MRI, 267 const LiveIntervals &LIS) 268 { 269 // Most registers are in SSA form here so we try a quick MRI query first. 270 if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg)) 271 return Def; 272 273 // MRI doesn't know what the Def is. Try asking LIS. 274 if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore( 275 LIS.getInstructionIndex(*Insert))) 276 return LIS.getInstructionFromIndex(ValNo->def); 277 278 return nullptr; 279 } 280 281 // Test whether Reg, as defined at Def, has exactly one use. This is a 282 // generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals 283 // to handle complex cases. 284 static bool HasOneUse(unsigned Reg, MachineInstr *Def, 285 MachineRegisterInfo &MRI, MachineDominatorTree &MDT, 286 LiveIntervals &LIS) { 287 // Most registers are in SSA form here so we try a quick MRI query first. 288 if (MRI.hasOneUse(Reg)) 289 return true; 290 291 bool HasOne = false; 292 const LiveInterval &LI = LIS.getInterval(Reg); 293 const VNInfo *DefVNI = LI.getVNInfoAt( 294 LIS.getInstructionIndex(*Def).getRegSlot()); 295 assert(DefVNI); 296 for (auto &I : MRI.use_nodbg_operands(Reg)) { 297 const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent())); 298 if (Result.valueIn() == DefVNI) { 299 if (!Result.isKill()) 300 return false; 301 if (HasOne) 302 return false; 303 HasOne = true; 304 } 305 } 306 return HasOne; 307 } 308 309 // Test whether it's safe to move Def to just before Insert. 310 // TODO: Compute memory dependencies in a way that doesn't require always 311 // walking the block. 312 // TODO: Compute memory dependencies in a way that uses AliasAnalysis to be 313 // more precise. 314 static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert, 315 AliasAnalysis &AA, const MachineRegisterInfo &MRI) { 316 assert(Def->getParent() == Insert->getParent()); 317 318 // Check for register dependencies. 319 SmallVector<unsigned, 4> MutableRegisters; 320 for (const MachineOperand &MO : Def->operands()) { 321 if (!MO.isReg() || MO.isUndef()) 322 continue; 323 unsigned Reg = MO.getReg(); 324 325 // If the register is dead here and at Insert, ignore it. 326 if (MO.isDead() && Insert->definesRegister(Reg) && 327 !Insert->readsRegister(Reg)) 328 continue; 329 330 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 331 // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions 332 // from moving down, and we've already checked for that. 333 if (Reg == WebAssembly::ARGUMENTS) 334 continue; 335 // If the physical register is never modified, ignore it. 336 if (!MRI.isPhysRegModified(Reg)) 337 continue; 338 // Otherwise, it's a physical register with unknown liveness. 339 return false; 340 } 341 342 // If one of the operands isn't in SSA form, it has different values at 343 // different times, and we need to make sure we don't move our use across 344 // a different def. 345 if (!MO.isDef() && !MRI.hasOneDef(Reg)) 346 MutableRegisters.push_back(Reg); 347 } 348 349 bool Read = false, Write = false, Effects = false, StackPointer = false; 350 Query(*Def, AA, Read, Write, Effects, StackPointer); 351 352 // If the instruction does not access memory and has no side effects, it has 353 // no additional dependencies. 354 bool HasMutableRegisters = !MutableRegisters.empty(); 355 if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters) 356 return true; 357 358 // Scan through the intervening instructions between Def and Insert. 359 MachineBasicBlock::const_iterator D(Def), I(Insert); 360 for (--I; I != D; --I) { 361 bool InterveningRead = false; 362 bool InterveningWrite = false; 363 bool InterveningEffects = false; 364 bool InterveningStackPointer = false; 365 Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects, 366 InterveningStackPointer); 367 if (Effects && InterveningEffects) 368 return false; 369 if (Read && InterveningWrite) 370 return false; 371 if (Write && (InterveningRead || InterveningWrite)) 372 return false; 373 if (StackPointer && InterveningStackPointer) 374 return false; 375 376 for (unsigned Reg : MutableRegisters) 377 for (const MachineOperand &MO : I->operands()) 378 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) 379 return false; 380 } 381 382 return true; 383 } 384 385 /// Test whether OneUse, a use of Reg, dominates all of Reg's other uses. 386 static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse, 387 const MachineBasicBlock &MBB, 388 const MachineRegisterInfo &MRI, 389 const MachineDominatorTree &MDT, 390 LiveIntervals &LIS, 391 WebAssemblyFunctionInfo &MFI) { 392 const LiveInterval &LI = LIS.getInterval(Reg); 393 394 const MachineInstr *OneUseInst = OneUse.getParent(); 395 VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst)); 396 397 for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) { 398 if (&Use == &OneUse) 399 continue; 400 401 const MachineInstr *UseInst = Use.getParent(); 402 VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst)); 403 404 if (UseVNI != OneUseVNI) 405 continue; 406 407 const MachineInstr *OneUseInst = OneUse.getParent(); 408 if (UseInst == OneUseInst) { 409 // Another use in the same instruction. We need to ensure that the one 410 // selected use happens "before" it. 411 if (&OneUse > &Use) 412 return false; 413 } else { 414 // Test that the use is dominated by the one selected use. 415 while (!MDT.dominates(OneUseInst, UseInst)) { 416 // Actually, dominating is over-conservative. Test that the use would 417 // happen after the one selected use in the stack evaluation order. 418 // 419 // This is needed as a consequence of using implicit get_locals for 420 // uses and implicit set_locals for defs. 421 if (UseInst->getDesc().getNumDefs() == 0) 422 return false; 423 const MachineOperand &MO = UseInst->getOperand(0); 424 if (!MO.isReg()) 425 return false; 426 unsigned DefReg = MO.getReg(); 427 if (!TargetRegisterInfo::isVirtualRegister(DefReg) || 428 !MFI.isVRegStackified(DefReg)) 429 return false; 430 assert(MRI.hasOneUse(DefReg)); 431 const MachineOperand &NewUse = *MRI.use_begin(DefReg); 432 const MachineInstr *NewUseInst = NewUse.getParent(); 433 if (NewUseInst == OneUseInst) { 434 if (&OneUse > &NewUse) 435 return false; 436 break; 437 } 438 UseInst = NewUseInst; 439 } 440 } 441 } 442 return true; 443 } 444 445 /// Get the appropriate tee opcode for the given register class. 446 static unsigned GetTeeOpcode(const TargetRegisterClass *RC) { 447 if (RC == &WebAssembly::I32RegClass) 448 return WebAssembly::TEE_I32; 449 if (RC == &WebAssembly::I64RegClass) 450 return WebAssembly::TEE_I64; 451 if (RC == &WebAssembly::F32RegClass) 452 return WebAssembly::TEE_F32; 453 if (RC == &WebAssembly::F64RegClass) 454 return WebAssembly::TEE_F64; 455 if (RC == &WebAssembly::V128RegClass) 456 return WebAssembly::TEE_V128; 457 llvm_unreachable("Unexpected register class"); 458 } 459 460 // Shrink LI to its uses, cleaning up LI. 461 static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) { 462 if (LIS.shrinkToUses(&LI)) { 463 SmallVector<LiveInterval*, 4> SplitLIs; 464 LIS.splitSeparateComponents(LI, SplitLIs); 465 } 466 } 467 468 /// A single-use def in the same block with no intervening memory or register 469 /// dependencies; move the def down and nest it with the current instruction. 470 static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand& Op, 471 MachineInstr *Def, 472 MachineBasicBlock &MBB, 473 MachineInstr *Insert, LiveIntervals &LIS, 474 WebAssemblyFunctionInfo &MFI, 475 MachineRegisterInfo &MRI) { 476 LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump()); 477 478 MBB.splice(Insert, &MBB, Def); 479 LIS.handleMove(*Def); 480 481 if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) { 482 // No one else is using this register for anything so we can just stackify 483 // it in place. 484 MFI.stackifyVReg(Reg); 485 } else { 486 // The register may have unrelated uses or defs; create a new register for 487 // just our one def and use so that we can stackify it. 488 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg)); 489 Def->getOperand(0).setReg(NewReg); 490 Op.setReg(NewReg); 491 492 // Tell LiveIntervals about the new register. 493 LIS.createAndComputeVirtRegInterval(NewReg); 494 495 // Tell LiveIntervals about the changes to the old register. 496 LiveInterval &LI = LIS.getInterval(Reg); 497 LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(), 498 LIS.getInstructionIndex(*Op.getParent()).getRegSlot(), 499 /*RemoveDeadValNo=*/true); 500 501 MFI.stackifyVReg(NewReg); 502 503 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump()); 504 } 505 506 ImposeStackOrdering(Def); 507 return Def; 508 } 509 510 /// A trivially cloneable instruction; clone it and nest the new copy with the 511 /// current instruction. 512 static MachineInstr *RematerializeCheapDef( 513 unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB, 514 MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS, 515 WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI, 516 const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) { 517 LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump()); 518 LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump()); 519 520 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg)); 521 TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI); 522 Op.setReg(NewReg); 523 MachineInstr *Clone = &*std::prev(Insert); 524 LIS.InsertMachineInstrInMaps(*Clone); 525 LIS.createAndComputeVirtRegInterval(NewReg); 526 MFI.stackifyVReg(NewReg); 527 ImposeStackOrdering(Clone); 528 529 LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump()); 530 531 // Shrink the interval. 532 bool IsDead = MRI.use_empty(Reg); 533 if (!IsDead) { 534 LiveInterval &LI = LIS.getInterval(Reg); 535 ShrinkToUses(LI, LIS); 536 IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot()); 537 } 538 539 // If that was the last use of the original, delete the original. 540 if (IsDead) { 541 LLVM_DEBUG(dbgs() << " - Deleting original\n"); 542 SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot(); 543 LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx); 544 LIS.removeInterval(Reg); 545 LIS.RemoveMachineInstrFromMaps(Def); 546 Def.eraseFromParent(); 547 } 548 549 return Clone; 550 } 551 552 /// A multiple-use def in the same block with no intervening memory or register 553 /// dependencies; move the def down, nest it with the current instruction, and 554 /// insert a tee to satisfy the rest of the uses. As an illustration, rewrite 555 /// this: 556 /// 557 /// Reg = INST ... // Def 558 /// INST ..., Reg, ... // Insert 559 /// INST ..., Reg, ... 560 /// INST ..., Reg, ... 561 /// 562 /// to this: 563 /// 564 /// DefReg = INST ... // Def (to become the new Insert) 565 /// TeeReg, Reg = TEE_... DefReg 566 /// INST ..., TeeReg, ... // Insert 567 /// INST ..., Reg, ... 568 /// INST ..., Reg, ... 569 /// 570 /// with DefReg and TeeReg stackified. This eliminates a get_local from the 571 /// resulting code. 572 static MachineInstr *MoveAndTeeForMultiUse( 573 unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB, 574 MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI, 575 MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) { 576 LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump()); 577 578 // Move Def into place. 579 MBB.splice(Insert, &MBB, Def); 580 LIS.handleMove(*Def); 581 582 // Create the Tee and attach the registers. 583 const auto *RegClass = MRI.getRegClass(Reg); 584 unsigned TeeReg = MRI.createVirtualRegister(RegClass); 585 unsigned DefReg = MRI.createVirtualRegister(RegClass); 586 MachineOperand &DefMO = Def->getOperand(0); 587 MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(), 588 TII->get(GetTeeOpcode(RegClass)), TeeReg) 589 .addReg(Reg, RegState::Define) 590 .addReg(DefReg, getUndefRegState(DefMO.isDead())); 591 Op.setReg(TeeReg); 592 DefMO.setReg(DefReg); 593 SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot(); 594 SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot(); 595 596 // Tell LiveIntervals we moved the original vreg def from Def to Tee. 597 LiveInterval &LI = LIS.getInterval(Reg); 598 LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx); 599 VNInfo *ValNo = LI.getVNInfoAt(DefIdx); 600 I->start = TeeIdx; 601 ValNo->def = TeeIdx; 602 ShrinkToUses(LI, LIS); 603 604 // Finish stackifying the new regs. 605 LIS.createAndComputeVirtRegInterval(TeeReg); 606 LIS.createAndComputeVirtRegInterval(DefReg); 607 MFI.stackifyVReg(DefReg); 608 MFI.stackifyVReg(TeeReg); 609 ImposeStackOrdering(Def); 610 ImposeStackOrdering(Tee); 611 612 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump()); 613 LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump()); 614 return Def; 615 } 616 617 namespace { 618 /// A stack for walking the tree of instructions being built, visiting the 619 /// MachineOperands in DFS order. 620 class TreeWalkerState { 621 typedef MachineInstr::mop_iterator mop_iterator; 622 typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator; 623 typedef iterator_range<mop_reverse_iterator> RangeTy; 624 SmallVector<RangeTy, 4> Worklist; 625 626 public: 627 explicit TreeWalkerState(MachineInstr *Insert) { 628 const iterator_range<mop_iterator> &Range = Insert->explicit_uses(); 629 if (Range.begin() != Range.end()) 630 Worklist.push_back(reverse(Range)); 631 } 632 633 bool Done() const { return Worklist.empty(); } 634 635 MachineOperand &Pop() { 636 RangeTy &Range = Worklist.back(); 637 MachineOperand &Op = *Range.begin(); 638 Range = drop_begin(Range, 1); 639 if (Range.begin() == Range.end()) 640 Worklist.pop_back(); 641 assert((Worklist.empty() || 642 Worklist.back().begin() != Worklist.back().end()) && 643 "Empty ranges shouldn't remain in the worklist"); 644 return Op; 645 } 646 647 /// Push Instr's operands onto the stack to be visited. 648 void PushOperands(MachineInstr *Instr) { 649 const iterator_range<mop_iterator> &Range(Instr->explicit_uses()); 650 if (Range.begin() != Range.end()) 651 Worklist.push_back(reverse(Range)); 652 } 653 654 /// Some of Instr's operands are on the top of the stack; remove them and 655 /// re-insert them starting from the beginning (because we've commuted them). 656 void ResetTopOperands(MachineInstr *Instr) { 657 assert(HasRemainingOperands(Instr) && 658 "Reseting operands should only be done when the instruction has " 659 "an operand still on the stack"); 660 Worklist.back() = reverse(Instr->explicit_uses()); 661 } 662 663 /// Test whether Instr has operands remaining to be visited at the top of 664 /// the stack. 665 bool HasRemainingOperands(const MachineInstr *Instr) const { 666 if (Worklist.empty()) 667 return false; 668 const RangeTy &Range = Worklist.back(); 669 return Range.begin() != Range.end() && Range.begin()->getParent() == Instr; 670 } 671 672 /// Test whether the given register is present on the stack, indicating an 673 /// operand in the tree that we haven't visited yet. Moving a definition of 674 /// Reg to a point in the tree after that would change its value. 675 /// 676 /// This is needed as a consequence of using implicit get_locals for 677 /// uses and implicit set_locals for defs. 678 bool IsOnStack(unsigned Reg) const { 679 for (const RangeTy &Range : Worklist) 680 for (const MachineOperand &MO : Range) 681 if (MO.isReg() && MO.getReg() == Reg) 682 return true; 683 return false; 684 } 685 }; 686 687 /// State to keep track of whether commuting is in flight or whether it's been 688 /// tried for the current instruction and didn't work. 689 class CommutingState { 690 /// There are effectively three states: the initial state where we haven't 691 /// started commuting anything and we don't know anything yet, the tenative 692 /// state where we've commuted the operands of the current instruction and are 693 /// revisting it, and the declined state where we've reverted the operands 694 /// back to their original order and will no longer commute it further. 695 bool TentativelyCommuting; 696 bool Declined; 697 698 /// During the tentative state, these hold the operand indices of the commuted 699 /// operands. 700 unsigned Operand0, Operand1; 701 702 public: 703 CommutingState() : TentativelyCommuting(false), Declined(false) {} 704 705 /// Stackification for an operand was not successful due to ordering 706 /// constraints. If possible, and if we haven't already tried it and declined 707 /// it, commute Insert's operands and prepare to revisit it. 708 void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker, 709 const WebAssemblyInstrInfo *TII) { 710 if (TentativelyCommuting) { 711 assert(!Declined && 712 "Don't decline commuting until you've finished trying it"); 713 // Commuting didn't help. Revert it. 714 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1); 715 TentativelyCommuting = false; 716 Declined = true; 717 } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) { 718 Operand0 = TargetInstrInfo::CommuteAnyOperandIndex; 719 Operand1 = TargetInstrInfo::CommuteAnyOperandIndex; 720 if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) { 721 // Tentatively commute the operands and try again. 722 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1); 723 TreeWalker.ResetTopOperands(Insert); 724 TentativelyCommuting = true; 725 Declined = false; 726 } 727 } 728 } 729 730 /// Stackification for some operand was successful. Reset to the default 731 /// state. 732 void Reset() { 733 TentativelyCommuting = false; 734 Declined = false; 735 } 736 }; 737 } // end anonymous namespace 738 739 bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) { 740 LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n" 741 "********** Function: " 742 << MF.getName() << '\n'); 743 744 bool Changed = false; 745 MachineRegisterInfo &MRI = MF.getRegInfo(); 746 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 747 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 748 const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo(); 749 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 750 MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>(); 751 LiveIntervals &LIS = getAnalysis<LiveIntervals>(); 752 753 // Disable the TEE optimization if we aren't doing direct wasm object 754 // emission, because lowering TEE to TEE_LOCAL is done in the ExplicitLocals 755 // pass, which is also disabled. 756 bool UseTee = true; 757 if (MF.getSubtarget<WebAssemblySubtarget>() 758 .getTargetTriple().isOSBinFormatELF()) 759 UseTee = false; 760 761 // Walk the instructions from the bottom up. Currently we don't look past 762 // block boundaries, and the blocks aren't ordered so the block visitation 763 // order isn't significant, but we may want to change this in the future. 764 for (MachineBasicBlock &MBB : MF) { 765 // Don't use a range-based for loop, because we modify the list as we're 766 // iterating over it and the end iterator may change. 767 for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) { 768 MachineInstr *Insert = &*MII; 769 // Don't nest anything inside an inline asm, because we don't have 770 // constraints for $push inputs. 771 if (Insert->getOpcode() == TargetOpcode::INLINEASM) 772 continue; 773 774 // Ignore debugging intrinsics. 775 if (Insert->getOpcode() == TargetOpcode::DBG_VALUE) 776 continue; 777 778 // Iterate through the inputs in reverse order, since we'll be pulling 779 // operands off the stack in LIFO order. 780 CommutingState Commuting; 781 TreeWalkerState TreeWalker(Insert); 782 while (!TreeWalker.Done()) { 783 MachineOperand &Op = TreeWalker.Pop(); 784 785 // We're only interested in explicit virtual register operands. 786 if (!Op.isReg()) 787 continue; 788 789 unsigned Reg = Op.getReg(); 790 assert(Op.isUse() && "explicit_uses() should only iterate over uses"); 791 assert(!Op.isImplicit() && 792 "explicit_uses() should only iterate over explicit operands"); 793 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 794 continue; 795 796 // Identify the definition for this register at this point. 797 MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS); 798 if (!Def) 799 continue; 800 801 // Don't nest an INLINE_ASM def into anything, because we don't have 802 // constraints for $pop outputs. 803 if (Def->getOpcode() == TargetOpcode::INLINEASM) 804 continue; 805 806 // Argument instructions represent live-in registers and not real 807 // instructions. 808 if (WebAssembly::isArgument(*Def)) 809 continue; 810 811 // Decide which strategy to take. Prefer to move a single-use value 812 // over cloning it, and prefer cloning over introducing a tee. 813 // For moving, we require the def to be in the same block as the use; 814 // this makes things simpler (LiveIntervals' handleMove function only 815 // supports intra-block moves) and it's MachineSink's job to catch all 816 // the sinking opportunities anyway. 817 bool SameBlock = Def->getParent() == &MBB; 818 bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) && 819 !TreeWalker.IsOnStack(Reg); 820 if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) { 821 Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI); 822 } else if (ShouldRematerialize(*Def, AA, TII)) { 823 Insert = 824 RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(), 825 LIS, MFI, MRI, TII, TRI); 826 } else if (UseTee && CanMove && 827 OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) { 828 Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI, 829 MRI, TII); 830 } else { 831 // We failed to stackify the operand. If the problem was ordering 832 // constraints, Commuting may be able to help. 833 if (!CanMove && SameBlock) 834 Commuting.MaybeCommute(Insert, TreeWalker, TII); 835 // Proceed to the next operand. 836 continue; 837 } 838 839 // If the instruction we just stackified is an IMPLICIT_DEF, convert it 840 // to a constant 0 so that the def is explicit, and the push/pop 841 // correspondence is maintained. 842 if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF) 843 ConvertImplicitDefToConstZero(Insert, MRI, TII, MF); 844 845 // We stackified an operand. Add the defining instruction's operands to 846 // the worklist stack now to continue to build an ever deeper tree. 847 Commuting.Reset(); 848 TreeWalker.PushOperands(Insert); 849 } 850 851 // If we stackified any operands, skip over the tree to start looking for 852 // the next instruction we can build a tree on. 853 if (Insert != &*MII) { 854 ImposeStackOrdering(&*MII); 855 MII = MachineBasicBlock::iterator(Insert).getReverse(); 856 Changed = true; 857 } 858 } 859 } 860 861 // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so 862 // that it never looks like a use-before-def. 863 if (Changed) { 864 MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK); 865 for (MachineBasicBlock &MBB : MF) 866 MBB.addLiveIn(WebAssembly::VALUE_STACK); 867 } 868 869 #ifndef NDEBUG 870 // Verify that pushes and pops are performed in LIFO order. 871 SmallVector<unsigned, 0> Stack; 872 for (MachineBasicBlock &MBB : MF) { 873 for (MachineInstr &MI : MBB) { 874 if (MI.isDebugInstr()) 875 continue; 876 for (MachineOperand &MO : reverse(MI.explicit_operands())) { 877 if (!MO.isReg()) 878 continue; 879 unsigned Reg = MO.getReg(); 880 881 if (MFI.isVRegStackified(Reg)) { 882 if (MO.isDef()) 883 Stack.push_back(Reg); 884 else 885 assert(Stack.pop_back_val() == Reg && 886 "Register stack pop should be paired with a push"); 887 } 888 } 889 } 890 // TODO: Generalize this code to support keeping values on the stack across 891 // basic block boundaries. 892 assert(Stack.empty() && 893 "Register stack pushes and pops should be balanced"); 894 } 895 #endif 896 897 return Changed; 898 } 899