1 //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===// 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 file implements the PredicateInfo class. 11 // 12 //===----------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Utils/PredicateInfo.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/DepthFirstIterator.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/AssumptionCache.h" 21 #include "llvm/Analysis/CFG.h" 22 #include "llvm/Analysis/OrderedBasicBlock.h" 23 #include "llvm/IR/AssemblyAnnotationWriter.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/GlobalVariable.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/Metadata.h" 31 #include "llvm/IR/Module.h" 32 #include "llvm/IR/PatternMatch.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/DebugCounter.h" 35 #include "llvm/Support/FormattedStream.h" 36 #include "llvm/Transforms/Scalar.h" 37 #include <algorithm> 38 #define DEBUG_TYPE "predicateinfo" 39 using namespace llvm; 40 using namespace PatternMatch; 41 using namespace llvm::PredicateInfoClasses; 42 43 INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo", 44 "PredicateInfo Printer", false, false) 45 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 46 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 47 INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo", 48 "PredicateInfo Printer", false, false) 49 static cl::opt<bool> VerifyPredicateInfo( 50 "verify-predicateinfo", cl::init(false), cl::Hidden, 51 cl::desc("Verify PredicateInfo in legacy printer pass.")); 52 namespace { 53 DEBUG_COUNTER(RenameCounter, "predicateinfo-rename", 54 "Controls which variables are renamed with predicateinfo") 55 // Given a predicate info that is a type of branching terminator, get the 56 // branching block. 57 const BasicBlock *getBranchBlock(const PredicateBase *PB) { 58 assert(isa<PredicateWithEdge>(PB) && 59 "Only branches and switches should have PHIOnly defs that " 60 "require branch blocks."); 61 return cast<PredicateWithEdge>(PB)->From; 62 } 63 64 // Given a predicate info that is a type of branching terminator, get the 65 // branching terminator. 66 static Instruction *getBranchTerminator(const PredicateBase *PB) { 67 assert(isa<PredicateWithEdge>(PB) && 68 "Not a predicate info type we know how to get a terminator from."); 69 return cast<PredicateWithEdge>(PB)->From->getTerminator(); 70 } 71 72 // Given a predicate info that is a type of branching terminator, get the 73 // edge this predicate info represents 74 const std::pair<BasicBlock *, BasicBlock *> 75 getBlockEdge(const PredicateBase *PB) { 76 assert(isa<PredicateWithEdge>(PB) && 77 "Not a predicate info type we know how to get an edge from."); 78 const auto *PEdge = cast<PredicateWithEdge>(PB); 79 return std::make_pair(PEdge->From, PEdge->To); 80 } 81 } 82 83 namespace llvm { 84 namespace PredicateInfoClasses { 85 enum LocalNum { 86 // Operations that must appear first in the block. 87 LN_First, 88 // Operations that are somewhere in the middle of the block, and are sorted on 89 // demand. 90 LN_Middle, 91 // Operations that must appear last in a block, like successor phi node uses. 92 LN_Last 93 }; 94 95 // Associate global and local DFS info with defs and uses, so we can sort them 96 // into a global domination ordering. 97 struct ValueDFS { 98 int DFSIn = 0; 99 int DFSOut = 0; 100 unsigned int LocalNum = LN_Middle; 101 // Only one of Def or Use will be set. 102 Value *Def = nullptr; 103 Use *U = nullptr; 104 // Neither PInfo nor EdgeOnly participate in the ordering 105 PredicateBase *PInfo = nullptr; 106 bool EdgeOnly = false; 107 }; 108 109 // This compares ValueDFS structures, creating OrderedBasicBlocks where 110 // necessary to compare uses/defs in the same block. Doing so allows us to walk 111 // the minimum number of instructions necessary to compute our def/use ordering. 112 struct ValueDFS_Compare { 113 DenseMap<const BasicBlock *, std::unique_ptr<OrderedBasicBlock>> &OBBMap; 114 ValueDFS_Compare( 115 DenseMap<const BasicBlock *, std::unique_ptr<OrderedBasicBlock>> &OBBMap) 116 : OBBMap(OBBMap) {} 117 bool operator()(const ValueDFS &A, const ValueDFS &B) const { 118 if (&A == &B) 119 return false; 120 // The only case we can't directly compare them is when they in the same 121 // block, and both have localnum == middle. In that case, we have to use 122 // comesbefore to see what the real ordering is, because they are in the 123 // same basic block. 124 125 bool SameBlock = std::tie(A.DFSIn, A.DFSOut) == std::tie(B.DFSIn, B.DFSOut); 126 127 // We want to put the def that will get used for a given set of phi uses, 128 // before those phi uses. 129 // So we sort by edge, then by def. 130 // Note that only phi nodes uses and defs can come last. 131 if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last) 132 return comparePHIRelated(A, B); 133 134 if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle) 135 return std::tie(A.DFSIn, A.DFSOut, A.LocalNum, A.Def, A.U) < 136 std::tie(B.DFSIn, B.DFSOut, B.LocalNum, B.Def, B.U); 137 return localComesBefore(A, B); 138 } 139 140 // For a phi use, or a non-materialized def, return the edge it represents. 141 const std::pair<BasicBlock *, BasicBlock *> 142 getBlockEdge(const ValueDFS &VD) const { 143 if (!VD.Def && VD.U) { 144 auto *PHI = cast<PHINode>(VD.U->getUser()); 145 return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent()); 146 } 147 // This is really a non-materialized def. 148 return ::getBlockEdge(VD.PInfo); 149 } 150 151 // For two phi related values, return the ordering. 152 bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const { 153 auto &ABlockEdge = getBlockEdge(A); 154 auto &BBlockEdge = getBlockEdge(B); 155 // Now sort by block edge and then defs before uses. 156 return std::tie(ABlockEdge, A.Def, A.U) < std::tie(BBlockEdge, B.Def, B.U); 157 } 158 159 // Get the definition of an instruction that occurs in the middle of a block. 160 Value *getMiddleDef(const ValueDFS &VD) const { 161 if (VD.Def) 162 return VD.Def; 163 // It's possible for the defs and uses to be null. For branches, the local 164 // numbering will say the placed predicaeinfos should go first (IE 165 // LN_beginning), so we won't be in this function. For assumes, we will end 166 // up here, beause we need to order the def we will place relative to the 167 // assume. So for the purpose of ordering, we pretend the def is the assume 168 // because that is where we will insert the info. 169 if (!VD.U) { 170 assert(VD.PInfo && 171 "No def, no use, and no predicateinfo should not occur"); 172 assert(isa<PredicateAssume>(VD.PInfo) && 173 "Middle of block should only occur for assumes"); 174 return cast<PredicateAssume>(VD.PInfo)->AssumeInst; 175 } 176 return nullptr; 177 } 178 179 // Return either the Def, if it's not null, or the user of the Use, if the def 180 // is null. 181 const Instruction *getDefOrUser(const Value *Def, const Use *U) const { 182 if (Def) 183 return cast<Instruction>(Def); 184 return cast<Instruction>(U->getUser()); 185 } 186 187 // This performs the necessary local basic block ordering checks to tell 188 // whether A comes before B, where both are in the same basic block. 189 bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const { 190 auto *ADef = getMiddleDef(A); 191 auto *BDef = getMiddleDef(B); 192 193 // See if we have real values or uses. If we have real values, we are 194 // guaranteed they are instructions or arguments. No matter what, we are 195 // guaranteed they are in the same block if they are instructions. 196 auto *ArgA = dyn_cast_or_null<Argument>(ADef); 197 auto *ArgB = dyn_cast_or_null<Argument>(BDef); 198 199 if (ArgA && !ArgB) 200 return true; 201 if (ArgB && !ArgA) 202 return false; 203 if (ArgA && ArgB) 204 return ArgA->getArgNo() < ArgB->getArgNo(); 205 206 auto *AInst = getDefOrUser(ADef, A.U); 207 auto *BInst = getDefOrUser(BDef, B.U); 208 209 auto *BB = AInst->getParent(); 210 auto LookupResult = OBBMap.find(BB); 211 if (LookupResult != OBBMap.end()) 212 return LookupResult->second->dominates(AInst, BInst); 213 214 auto Result = OBBMap.insert({BB, make_unique<OrderedBasicBlock>(BB)}); 215 return Result.first->second->dominates(AInst, BInst); 216 } 217 }; 218 219 } // namespace PredicateInfoClasses 220 221 bool PredicateInfo::stackIsInScope(const ValueDFSStack &Stack, 222 const ValueDFS &VDUse) const { 223 if (Stack.empty()) 224 return false; 225 // If it's a phi only use, make sure it's for this phi node edge, and that the 226 // use is in a phi node. If it's anything else, and the top of the stack is 227 // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to 228 // the defs they must go with so that we can know it's time to pop the stack 229 // when we hit the end of the phi uses for a given def. 230 if (Stack.back().EdgeOnly) { 231 if (!VDUse.U) 232 return false; 233 auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser()); 234 if (!PHI) 235 return false; 236 // Check edge 237 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U); 238 if (EdgePred != getBranchBlock(Stack.back().PInfo)) 239 return false; 240 241 // Use dominates, which knows how to handle edge dominance. 242 return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U); 243 } 244 245 return (VDUse.DFSIn >= Stack.back().DFSIn && 246 VDUse.DFSOut <= Stack.back().DFSOut); 247 } 248 249 void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack, 250 const ValueDFS &VD) { 251 while (!Stack.empty() && !stackIsInScope(Stack, VD)) 252 Stack.pop_back(); 253 } 254 255 // Convert the uses of Op into a vector of uses, associating global and local 256 // DFS info with each one. 257 void PredicateInfo::convertUsesToDFSOrdered( 258 Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) { 259 for (auto &U : Op->uses()) { 260 if (auto *I = dyn_cast<Instruction>(U.getUser())) { 261 ValueDFS VD; 262 // Put the phi node uses in the incoming block. 263 BasicBlock *IBlock; 264 if (auto *PN = dyn_cast<PHINode>(I)) { 265 IBlock = PN->getIncomingBlock(U); 266 // Make phi node users appear last in the incoming block 267 // they are from. 268 VD.LocalNum = LN_Last; 269 } else { 270 // If it's not a phi node use, it is somewhere in the middle of the 271 // block. 272 IBlock = I->getParent(); 273 VD.LocalNum = LN_Middle; 274 } 275 DomTreeNode *DomNode = DT.getNode(IBlock); 276 // It's possible our use is in an unreachable block. Skip it if so. 277 if (!DomNode) 278 continue; 279 VD.DFSIn = DomNode->getDFSNumIn(); 280 VD.DFSOut = DomNode->getDFSNumOut(); 281 VD.U = &U; 282 DFSOrderedSet.push_back(VD); 283 } 284 } 285 } 286 287 // Collect relevant operations from Comparison that we may want to insert copies 288 // for. 289 void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) { 290 auto *Op0 = Comparison->getOperand(0); 291 auto *Op1 = Comparison->getOperand(1); 292 if (Op0 == Op1) 293 return; 294 CmpOperands.push_back(Comparison); 295 // Only want real values, not constants. Additionally, operands with one use 296 // are only being used in the comparison, which means they will not be useful 297 // for us to consider for predicateinfo. 298 // 299 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse()) 300 CmpOperands.push_back(Op0); 301 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse()) 302 CmpOperands.push_back(Op1); 303 } 304 305 // Add Op, PB to the list of value infos for Op, and mark Op to be renamed. 306 void PredicateInfo::addInfoFor(SmallPtrSetImpl<Value *> &OpsToRename, Value *Op, 307 PredicateBase *PB) { 308 OpsToRename.insert(Op); 309 auto &OperandInfo = getOrCreateValueInfo(Op); 310 AllInfos.push_back(PB); 311 OperandInfo.Infos.push_back(PB); 312 } 313 314 // Process an assume instruction and place relevant operations we want to rename 315 // into OpsToRename. 316 void PredicateInfo::processAssume(IntrinsicInst *II, BasicBlock *AssumeBB, 317 SmallPtrSetImpl<Value *> &OpsToRename) { 318 // See if we have a comparison we support 319 SmallVector<Value *, 8> CmpOperands; 320 SmallVector<Value *, 2> ConditionsToProcess; 321 CmpInst::Predicate Pred; 322 Value *Operand = II->getOperand(0); 323 if (m_c_And(m_Cmp(Pred, m_Value(), m_Value()), 324 m_Cmp(Pred, m_Value(), m_Value())) 325 .match(II->getOperand(0))) { 326 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(0)); 327 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(1)); 328 ConditionsToProcess.push_back(Operand); 329 } else if (isa<CmpInst>(Operand)) { 330 331 ConditionsToProcess.push_back(Operand); 332 } 333 for (auto Cond : ConditionsToProcess) { 334 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) { 335 collectCmpOps(Cmp, CmpOperands); 336 // Now add our copy infos for our operands 337 for (auto *Op : CmpOperands) { 338 auto *PA = new PredicateAssume(Op, II, Cmp); 339 addInfoFor(OpsToRename, Op, PA); 340 } 341 CmpOperands.clear(); 342 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) { 343 // Otherwise, it should be an AND. 344 assert(BinOp->getOpcode() == Instruction::And && 345 "Should have been an AND"); 346 auto *PA = new PredicateAssume(BinOp, II, BinOp); 347 addInfoFor(OpsToRename, BinOp, PA); 348 } else { 349 llvm_unreachable("Unknown type of condition"); 350 } 351 } 352 } 353 354 // Process a block terminating branch, and place relevant operations to be 355 // renamed into OpsToRename. 356 void PredicateInfo::processBranch(BranchInst *BI, BasicBlock *BranchBB, 357 SmallPtrSetImpl<Value *> &OpsToRename) { 358 BasicBlock *FirstBB = BI->getSuccessor(0); 359 BasicBlock *SecondBB = BI->getSuccessor(1); 360 SmallVector<BasicBlock *, 2> SuccsToProcess; 361 SuccsToProcess.push_back(FirstBB); 362 SuccsToProcess.push_back(SecondBB); 363 SmallVector<Value *, 2> ConditionsToProcess; 364 365 auto InsertHelper = [&](Value *Op, bool isAnd, bool isOr, Value *Cond) { 366 for (auto *Succ : SuccsToProcess) { 367 // Don't try to insert on a self-edge. This is mainly because we will 368 // eliminate during renaming anyway. 369 if (Succ == BranchBB) 370 continue; 371 bool TakenEdge = (Succ == FirstBB); 372 // For and, only insert on the true edge 373 // For or, only insert on the false edge 374 if ((isAnd && !TakenEdge) || (isOr && TakenEdge)) 375 continue; 376 PredicateBase *PB = 377 new PredicateBranch(Op, BranchBB, Succ, Cond, TakenEdge); 378 addInfoFor(OpsToRename, Op, PB); 379 if (!Succ->getSinglePredecessor()) 380 EdgeUsesOnly.insert({BranchBB, Succ}); 381 } 382 }; 383 384 // Match combinations of conditions. 385 CmpInst::Predicate Pred; 386 bool isAnd = false; 387 bool isOr = false; 388 SmallVector<Value *, 8> CmpOperands; 389 if (match(BI->getCondition(), m_And(m_Cmp(Pred, m_Value(), m_Value()), 390 m_Cmp(Pred, m_Value(), m_Value()))) || 391 match(BI->getCondition(), m_Or(m_Cmp(Pred, m_Value(), m_Value()), 392 m_Cmp(Pred, m_Value(), m_Value())))) { 393 auto *BinOp = cast<BinaryOperator>(BI->getCondition()); 394 if (BinOp->getOpcode() == Instruction::And) 395 isAnd = true; 396 else if (BinOp->getOpcode() == Instruction::Or) 397 isOr = true; 398 ConditionsToProcess.push_back(BinOp->getOperand(0)); 399 ConditionsToProcess.push_back(BinOp->getOperand(1)); 400 ConditionsToProcess.push_back(BI->getCondition()); 401 } else if (isa<CmpInst>(BI->getCondition())) { 402 ConditionsToProcess.push_back(BI->getCondition()); 403 } 404 for (auto Cond : ConditionsToProcess) { 405 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) { 406 collectCmpOps(Cmp, CmpOperands); 407 // Now add our copy infos for our operands 408 for (auto *Op : CmpOperands) 409 InsertHelper(Op, isAnd, isOr, Cmp); 410 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) { 411 // This must be an AND or an OR. 412 assert((BinOp->getOpcode() == Instruction::And || 413 BinOp->getOpcode() == Instruction::Or) && 414 "Should have been an AND or an OR"); 415 // The actual value of the binop is not subject to the same restrictions 416 // as the comparison. It's either true or false on the true/false branch. 417 InsertHelper(BinOp, false, false, BinOp); 418 } else { 419 llvm_unreachable("Unknown type of condition"); 420 } 421 CmpOperands.clear(); 422 } 423 } 424 // Process a block terminating switch, and place relevant operations to be 425 // renamed into OpsToRename. 426 void PredicateInfo::processSwitch(SwitchInst *SI, BasicBlock *BranchBB, 427 SmallPtrSetImpl<Value *> &OpsToRename) { 428 Value *Op = SI->getCondition(); 429 if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse()) 430 return; 431 432 // Remember how many outgoing edges there are to every successor. 433 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges; 434 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { 435 BasicBlock *TargetBlock = SI->getSuccessor(i); 436 ++SwitchEdges[TargetBlock]; 437 } 438 439 // Now propagate info for each case value 440 for (auto C : SI->cases()) { 441 BasicBlock *TargetBlock = C.getCaseSuccessor(); 442 if (SwitchEdges.lookup(TargetBlock) == 1) { 443 PredicateSwitch *PS = new PredicateSwitch( 444 Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI); 445 addInfoFor(OpsToRename, Op, PS); 446 if (!TargetBlock->getSinglePredecessor()) 447 EdgeUsesOnly.insert({BranchBB, TargetBlock}); 448 } 449 } 450 } 451 452 // Build predicate info for our function 453 void PredicateInfo::buildPredicateInfo() { 454 DT.updateDFSNumbers(); 455 // Collect operands to rename from all conditional branch terminators, as well 456 // as assume statements. 457 SmallPtrSet<Value *, 8> OpsToRename; 458 for (auto DTN : depth_first(DT.getRootNode())) { 459 BasicBlock *BranchBB = DTN->getBlock(); 460 if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) { 461 if (!BI->isConditional()) 462 continue; 463 // Can't insert conditional information if they all go to the same place. 464 if (BI->getSuccessor(0) == BI->getSuccessor(1)) 465 continue; 466 processBranch(BI, BranchBB, OpsToRename); 467 } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) { 468 processSwitch(SI, BranchBB, OpsToRename); 469 } 470 } 471 for (auto &Assume : AC.assumptions()) { 472 if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume)) 473 processAssume(II, II->getParent(), OpsToRename); 474 } 475 // Now rename all our operations. 476 renameUses(OpsToRename); 477 } 478 479 // Given the renaming stack, make all the operands currently on the stack real 480 // by inserting them into the IR. Return the last operation's value. 481 Value *PredicateInfo::materializeStack(unsigned int &Counter, 482 ValueDFSStack &RenameStack, 483 Value *OrigOp) { 484 // Find the first thing we have to materialize 485 auto RevIter = RenameStack.rbegin(); 486 for (; RevIter != RenameStack.rend(); ++RevIter) 487 if (RevIter->Def) 488 break; 489 490 size_t Start = RevIter - RenameStack.rbegin(); 491 // The maximum number of things we should be trying to materialize at once 492 // right now is 4, depending on if we had an assume, a branch, and both used 493 // and of conditions. 494 for (auto RenameIter = RenameStack.end() - Start; 495 RenameIter != RenameStack.end(); ++RenameIter) { 496 auto *Op = 497 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def; 498 ValueDFS &Result = *RenameIter; 499 auto *ValInfo = Result.PInfo; 500 // For edge predicates, we can just place the operand in the block before 501 // the terminator. For assume, we have to place it right before the assume 502 // to ensure we dominate all of our uses. Always insert right before the 503 // relevant instruction (terminator, assume), so that we insert in proper 504 // order in the case of multiple predicateinfo in the same block. 505 if (isa<PredicateWithEdge>(ValInfo)) { 506 IRBuilder<> B(getBranchTerminator(ValInfo)); 507 Function *IF = Intrinsic::getDeclaration( 508 F.getParent(), Intrinsic::ssa_copy, Op->getType()); 509 CallInst *PIC = 510 B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++)); 511 PredicateMap.insert({PIC, ValInfo}); 512 Result.Def = PIC; 513 } else { 514 auto *PAssume = dyn_cast<PredicateAssume>(ValInfo); 515 assert(PAssume && 516 "Should not have gotten here without it being an assume"); 517 IRBuilder<> B(PAssume->AssumeInst); 518 Function *IF = Intrinsic::getDeclaration( 519 F.getParent(), Intrinsic::ssa_copy, Op->getType()); 520 CallInst *PIC = B.CreateCall(IF, Op); 521 PredicateMap.insert({PIC, ValInfo}); 522 Result.Def = PIC; 523 } 524 } 525 return RenameStack.back().Def; 526 } 527 528 // Instead of the standard SSA renaming algorithm, which is O(Number of 529 // instructions), and walks the entire dominator tree, we walk only the defs + 530 // uses. The standard SSA renaming algorithm does not really rely on the 531 // dominator tree except to order the stack push/pops of the renaming stacks, so 532 // that defs end up getting pushed before hitting the correct uses. This does 533 // not require the dominator tree, only the *order* of the dominator tree. The 534 // complete and correct ordering of the defs and uses, in dominator tree is 535 // contained in the DFS numbering of the dominator tree. So we sort the defs and 536 // uses into the DFS ordering, and then just use the renaming stack as per 537 // normal, pushing when we hit a def (which is a predicateinfo instruction), 538 // popping when we are out of the dfs scope for that def, and replacing any uses 539 // with top of stack if it exists. In order to handle liveness without 540 // propagating liveness info, we don't actually insert the predicateinfo 541 // instruction def until we see a use that it would dominate. Once we see such 542 // a use, we materialize the predicateinfo instruction in the right place and 543 // use it. 544 // 545 // TODO: Use this algorithm to perform fast single-variable renaming in 546 // promotememtoreg and memoryssa. 547 void PredicateInfo::renameUses(SmallPtrSetImpl<Value *> &OpSet) { 548 // Sort OpsToRename since we are going to iterate it. 549 SmallVector<Value *, 8> OpsToRename(OpSet.begin(), OpSet.end()); 550 std::sort(OpsToRename.begin(), OpsToRename.end(), [&](const Value *A, 551 const Value *B) { 552 auto *ArgA = dyn_cast_or_null<Argument>(A); 553 auto *ArgB = dyn_cast_or_null<Argument>(B); 554 555 // If A and B are args, order them based on their arg no. 556 if (ArgA && !ArgB) 557 return true; 558 if (ArgB && !ArgA) 559 return false; 560 if (ArgA && ArgB) 561 return ArgA->getArgNo() < ArgB->getArgNo(); 562 563 // Else, A are B are instructions. 564 // If they belong to different BBs, order them by the dominance of BBs. 565 auto *AInst = cast<Instruction>(A); 566 auto *BInst = cast<Instruction>(B); 567 if (AInst->getParent() != BInst->getParent()) 568 return DT.dominates(AInst->getParent(), BInst->getParent()); 569 570 // Else, A and B belong to the same BB. 571 // Order A and B by their dominance. 572 auto *BB = AInst->getParent(); 573 auto LookupResult = OBBMap.find(BB); 574 if (LookupResult != OBBMap.end()) 575 return LookupResult->second->dominates(AInst, BInst); 576 577 auto Result = OBBMap.insert({BB, make_unique<OrderedBasicBlock>(BB)}); 578 return Result.first->second->dominates(AInst, BInst); 579 }); 580 581 ValueDFS_Compare Compare(OBBMap); 582 // Compute liveness, and rename in O(uses) per Op. 583 for (auto *Op : OpsToRename) { 584 unsigned Counter = 0; 585 SmallVector<ValueDFS, 16> OrderedUses; 586 const auto &ValueInfo = getValueInfo(Op); 587 // Insert the possible copies into the def/use list. 588 // They will become real copies if we find a real use for them, and never 589 // created otherwise. 590 for (auto &PossibleCopy : ValueInfo.Infos) { 591 ValueDFS VD; 592 // Determine where we are going to place the copy by the copy type. 593 // The predicate info for branches always come first, they will get 594 // materialized in the split block at the top of the block. 595 // The predicate info for assumes will be somewhere in the middle, 596 // it will get materialized in front of the assume. 597 if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) { 598 VD.LocalNum = LN_Middle; 599 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent()); 600 if (!DomNode) 601 continue; 602 VD.DFSIn = DomNode->getDFSNumIn(); 603 VD.DFSOut = DomNode->getDFSNumOut(); 604 VD.PInfo = PossibleCopy; 605 OrderedUses.push_back(VD); 606 } else if (isa<PredicateWithEdge>(PossibleCopy)) { 607 // If we can only do phi uses, we treat it like it's in the branch 608 // block, and handle it specially. We know that it goes last, and only 609 // dominate phi uses. 610 auto BlockEdge = getBlockEdge(PossibleCopy); 611 if (EdgeUsesOnly.count(BlockEdge)) { 612 VD.LocalNum = LN_Last; 613 auto *DomNode = DT.getNode(BlockEdge.first); 614 if (DomNode) { 615 VD.DFSIn = DomNode->getDFSNumIn(); 616 VD.DFSOut = DomNode->getDFSNumOut(); 617 VD.PInfo = PossibleCopy; 618 VD.EdgeOnly = true; 619 OrderedUses.push_back(VD); 620 } 621 } else { 622 // Otherwise, we are in the split block (even though we perform 623 // insertion in the branch block). 624 // Insert a possible copy at the split block and before the branch. 625 VD.LocalNum = LN_First; 626 auto *DomNode = DT.getNode(BlockEdge.second); 627 if (DomNode) { 628 VD.DFSIn = DomNode->getDFSNumIn(); 629 VD.DFSOut = DomNode->getDFSNumOut(); 630 VD.PInfo = PossibleCopy; 631 OrderedUses.push_back(VD); 632 } 633 } 634 } 635 } 636 637 convertUsesToDFSOrdered(Op, OrderedUses); 638 std::sort(OrderedUses.begin(), OrderedUses.end(), Compare); 639 SmallVector<ValueDFS, 8> RenameStack; 640 // For each use, sorted into dfs order, push values and replaces uses with 641 // top of stack, which will represent the reaching def. 642 for (auto &VD : OrderedUses) { 643 // We currently do not materialize copy over copy, but we should decide if 644 // we want to. 645 bool PossibleCopy = VD.PInfo != nullptr; 646 if (RenameStack.empty()) { 647 DEBUG(dbgs() << "Rename Stack is empty\n"); 648 } else { 649 DEBUG(dbgs() << "Rename Stack Top DFS numbers are (" 650 << RenameStack.back().DFSIn << "," 651 << RenameStack.back().DFSOut << ")\n"); 652 } 653 654 DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << "," 655 << VD.DFSOut << ")\n"); 656 657 bool ShouldPush = (VD.Def || PossibleCopy); 658 bool OutOfScope = !stackIsInScope(RenameStack, VD); 659 if (OutOfScope || ShouldPush) { 660 // Sync to our current scope. 661 popStackUntilDFSScope(RenameStack, VD); 662 if (ShouldPush) { 663 RenameStack.push_back(VD); 664 } 665 } 666 // If we get to this point, and the stack is empty we must have a use 667 // with no renaming needed, just skip it. 668 if (RenameStack.empty()) 669 continue; 670 // Skip values, only want to rename the uses 671 if (VD.Def || PossibleCopy) 672 continue; 673 if (!DebugCounter::shouldExecute(RenameCounter)) { 674 DEBUG(dbgs() << "Skipping execution due to debug counter\n"); 675 continue; 676 } 677 ValueDFS &Result = RenameStack.back(); 678 679 // If the possible copy dominates something, materialize our stack up to 680 // this point. This ensures every comparison that affects our operation 681 // ends up with predicateinfo. 682 if (!Result.Def) 683 Result.Def = materializeStack(Counter, RenameStack, Op); 684 685 DEBUG(dbgs() << "Found replacement " << *Result.Def << " for " 686 << *VD.U->get() << " in " << *(VD.U->getUser()) << "\n"); 687 assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) && 688 "Predicateinfo def should have dominated this use"); 689 VD.U->set(Result.Def); 690 } 691 } 692 } 693 694 PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(Value *Operand) { 695 auto OIN = ValueInfoNums.find(Operand); 696 if (OIN == ValueInfoNums.end()) { 697 // This will grow it 698 ValueInfos.resize(ValueInfos.size() + 1); 699 // This will use the new size and give us a 0 based number of the info 700 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1}); 701 assert(InsertResult.second && "Value info number already existed?"); 702 return ValueInfos[InsertResult.first->second]; 703 } 704 return ValueInfos[OIN->second]; 705 } 706 707 const PredicateInfo::ValueInfo & 708 PredicateInfo::getValueInfo(Value *Operand) const { 709 auto OINI = ValueInfoNums.lookup(Operand); 710 assert(OINI != 0 && "Operand was not really in the Value Info Numbers"); 711 assert(OINI < ValueInfos.size() && 712 "Value Info Number greater than size of Value Info Table"); 713 return ValueInfos[OINI]; 714 } 715 716 PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT, 717 AssumptionCache &AC) 718 : F(F), DT(DT), AC(AC) { 719 // Push an empty operand info so that we can detect 0 as not finding one 720 ValueInfos.resize(1); 721 buildPredicateInfo(); 722 } 723 724 PredicateInfo::~PredicateInfo() {} 725 726 void PredicateInfo::verifyPredicateInfo() const {} 727 728 char PredicateInfoPrinterLegacyPass::ID = 0; 729 730 PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass() 731 : FunctionPass(ID) { 732 initializePredicateInfoPrinterLegacyPassPass( 733 *PassRegistry::getPassRegistry()); 734 } 735 736 void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const { 737 AU.setPreservesAll(); 738 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 739 AU.addRequired<AssumptionCacheTracker>(); 740 } 741 742 bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) { 743 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 744 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 745 auto PredInfo = make_unique<PredicateInfo>(F, DT, AC); 746 PredInfo->print(dbgs()); 747 if (VerifyPredicateInfo) 748 PredInfo->verifyPredicateInfo(); 749 return false; 750 } 751 752 PreservedAnalyses PredicateInfoPrinterPass::run(Function &F, 753 FunctionAnalysisManager &AM) { 754 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 755 auto &AC = AM.getResult<AssumptionAnalysis>(F); 756 OS << "PredicateInfo for function: " << F.getName() << "\n"; 757 make_unique<PredicateInfo>(F, DT, AC)->print(OS); 758 759 return PreservedAnalyses::all(); 760 } 761 762 /// \brief An assembly annotator class to print PredicateInfo information in 763 /// comments. 764 class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter { 765 friend class PredicateInfo; 766 const PredicateInfo *PredInfo; 767 768 public: 769 PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {} 770 771 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, 772 formatted_raw_ostream &OS) {} 773 774 virtual void emitInstructionAnnot(const Instruction *I, 775 formatted_raw_ostream &OS) { 776 if (const auto *PI = PredInfo->getPredicateInfoFor(I)) { 777 OS << "; Has predicate info\n"; 778 if (const auto *PB = dyn_cast<PredicateBranch>(PI)) { 779 OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge 780 << " Comparison:" << *PB->Condition << " Edge: ["; 781 PB->From->printAsOperand(OS); 782 OS << ","; 783 PB->To->printAsOperand(OS); 784 OS << "] }\n"; 785 } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) { 786 OS << "; switch predicate info { CaseValue: " << *PS->CaseValue 787 << " Switch:" << *PS->Switch << " Edge: ["; 788 PS->From->printAsOperand(OS); 789 OS << ","; 790 PS->To->printAsOperand(OS); 791 OS << "] }\n"; 792 } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) { 793 OS << "; assume predicate info {" 794 << " Comparison:" << *PA->Condition << " }\n"; 795 } 796 } 797 } 798 }; 799 800 void PredicateInfo::print(raw_ostream &OS) const { 801 PredicateInfoAnnotatedWriter Writer(this); 802 F.print(OS, &Writer); 803 } 804 805 void PredicateInfo::dump() const { 806 PredicateInfoAnnotatedWriter Writer(this); 807 F.print(dbgs(), &Writer); 808 } 809 810 PreservedAnalyses PredicateInfoVerifierPass::run(Function &F, 811 FunctionAnalysisManager &AM) { 812 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 813 auto &AC = AM.getResult<AssumptionAnalysis>(F); 814 make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo(); 815 816 return PreservedAnalyses::all(); 817 } 818 } 819