1 //===- NaryReassociate.cpp - Reassociate n-ary expressions ----------------===// 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 reassociates n-ary add expressions and eliminates the redundancy 11 // exposed by the reassociation. 12 // 13 // A motivating example: 14 // 15 // void foo(int a, int b) { 16 // bar(a + b); 17 // bar((a + 2) + b); 18 // } 19 // 20 // An ideal compiler should reassociate (a + 2) + b to (a + b) + 2 and simplify 21 // the above code to 22 // 23 // int t = a + b; 24 // bar(t); 25 // bar(t + 2); 26 // 27 // However, the Reassociate pass is unable to do that because it processes each 28 // instruction individually and believes (a + 2) + b is the best form according 29 // to its rank system. 30 // 31 // To address this limitation, NaryReassociate reassociates an expression in a 32 // form that reuses existing instructions. As a result, NaryReassociate can 33 // reassociate (a + 2) + b in the example to (a + b) + 2 because it detects that 34 // (a + b) is computed before. 35 // 36 // NaryReassociate works as follows. For every instruction in the form of (a + 37 // b) + c, it checks whether a + c or b + c is already computed by a dominating 38 // instruction. If so, it then reassociates (a + b) + c into (a + c) + b or (b + 39 // c) + a and removes the redundancy accordingly. To efficiently look up whether 40 // an expression is computed before, we store each instruction seen and its SCEV 41 // into an SCEV-to-instruction map. 42 // 43 // Although the algorithm pattern-matches only ternary additions, it 44 // automatically handles many >3-ary expressions by walking through the function 45 // in the depth-first order. For example, given 46 // 47 // (a + c) + d 48 // ((a + b) + c) + d 49 // 50 // NaryReassociate first rewrites (a + b) + c to (a + c) + b, and then rewrites 51 // ((a + c) + b) + d into ((a + c) + d) + b. 52 // 53 // Finally, the above dominator-based algorithm may need to be run multiple 54 // iterations before emitting optimal code. One source of this need is that we 55 // only split an operand when it is used only once. The above algorithm can 56 // eliminate an instruction and decrease the usage count of its operands. As a 57 // result, an instruction that previously had multiple uses may become a 58 // single-use instruction and thus eligible for split consideration. For 59 // example, 60 // 61 // ac = a + c 62 // ab = a + b 63 // abc = ab + c 64 // ab2 = ab + b 65 // ab2c = ab2 + c 66 // 67 // In the first iteration, we cannot reassociate abc to ac+b because ab is used 68 // twice. However, we can reassociate ab2c to abc+b in the first iteration. As a 69 // result, ab2 becomes dead and ab will be used only once in the second 70 // iteration. 71 // 72 // Limitations and TODO items: 73 // 74 // 1) We only considers n-ary adds for now. This should be extended and 75 // generalized. 76 // 77 // 2) Besides arithmetic operations, similar reassociation can be applied to 78 // GEPs. For example, if 79 // X = &arr[a] 80 // dominates 81 // Y = &arr[a + b] 82 // we may rewrite Y into X + b. 83 // 84 //===----------------------------------------------------------------------===// 85 86 #include "llvm/Analysis/ScalarEvolution.h" 87 #include "llvm/Analysis/TargetLibraryInfo.h" 88 #include "llvm/Analysis/TargetTransformInfo.h" 89 #include "llvm/IR/Dominators.h" 90 #include "llvm/IR/Module.h" 91 #include "llvm/IR/PatternMatch.h" 92 #include "llvm/Transforms/Scalar.h" 93 #include "llvm/Transforms/Utils/Local.h" 94 using namespace llvm; 95 using namespace PatternMatch; 96 97 #define DEBUG_TYPE "nary-reassociate" 98 99 namespace { 100 class NaryReassociate : public FunctionPass { 101 public: 102 static char ID; 103 104 NaryReassociate(): FunctionPass(ID) { 105 initializeNaryReassociatePass(*PassRegistry::getPassRegistry()); 106 } 107 108 bool doInitialization(Module &M) override { 109 DL = &M.getDataLayout(); 110 return false; 111 } 112 bool runOnFunction(Function &F) override; 113 114 void getAnalysisUsage(AnalysisUsage &AU) const override { 115 AU.addPreserved<DominatorTreeWrapperPass>(); 116 AU.addPreserved<ScalarEvolution>(); 117 AU.addPreserved<TargetLibraryInfoWrapperPass>(); 118 AU.addRequired<DominatorTreeWrapperPass>(); 119 AU.addRequired<ScalarEvolution>(); 120 AU.addRequired<TargetLibraryInfoWrapperPass>(); 121 AU.addRequired<TargetTransformInfoWrapperPass>(); 122 AU.setPreservesCFG(); 123 } 124 125 private: 126 // Runs only one iteration of the dominator-based algorithm. See the header 127 // comments for why we need multiple iterations. 128 bool doOneIteration(Function &F); 129 130 // Reassociates I for better CSE. 131 Instruction *tryReassociate(Instruction *I); 132 133 // Reassociate GEP for better CSE. 134 Instruction *tryReassociateGEP(GetElementPtrInst *GEP); 135 // Try splitting GEP at the I-th index and see whether either part can be 136 // CSE'ed. This is a helper function for tryReassociateGEP. 137 // 138 // \p IndexedType The element type indexed by GEP's I-th index. This is 139 // equivalent to 140 // GEP->getIndexedType(GEP->getPointerOperand(), 0-th index, 141 // ..., i-th index). 142 GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP, 143 unsigned I, Type *IndexedType); 144 // Given GEP's I-th index = LHS + RHS, see whether &Base[..][LHS][..] or 145 // &Base[..][RHS][..] can be CSE'ed and rewrite GEP accordingly. 146 GetElementPtrInst *tryReassociateGEPAtIndex(GetElementPtrInst *GEP, 147 unsigned I, Value *LHS, 148 Value *RHS, Type *IndexedType); 149 150 // Reassociate Add for better CSE. 151 Instruction *tryReassociateAdd(BinaryOperator *I); 152 // A helper function for tryReassociateAdd. LHS and RHS are explicitly passed. 153 Instruction *tryReassociateAdd(Value *LHS, Value *RHS, Instruction *I); 154 // Rewrites I to LHS + RHS if LHS is computed already. 155 Instruction *tryReassociatedAdd(const SCEV *LHS, Value *RHS, Instruction *I); 156 157 // Returns the closest dominator of \c Dominatee that computes 158 // \c CandidateExpr. Returns null if not found. 159 Instruction *findClosestMatchingDominator(const SCEV *CandidateExpr, 160 Instruction *Dominatee); 161 // GetElementPtrInst implicitly sign-extends an index if the index is shorter 162 // than the pointer size. This function returns whether Index is shorter than 163 // GEP's pointer size, i.e., whether Index needs to be sign-extended in order 164 // to be an index of GEP. 165 bool requiresSignExtension(Value *Index, GetElementPtrInst *GEP); 166 167 DominatorTree *DT; 168 ScalarEvolution *SE; 169 TargetLibraryInfo *TLI; 170 TargetTransformInfo *TTI; 171 const DataLayout *DL; 172 // A lookup table quickly telling which instructions compute the given SCEV. 173 // Note that there can be multiple instructions at different locations 174 // computing to the same SCEV, so we map a SCEV to an instruction list. For 175 // example, 176 // 177 // if (p1) 178 // foo(a + b); 179 // if (p2) 180 // bar(a + b); 181 DenseMap<const SCEV *, SmallVector<Instruction *, 2>> SeenExprs; 182 }; 183 } // anonymous namespace 184 185 char NaryReassociate::ID = 0; 186 INITIALIZE_PASS_BEGIN(NaryReassociate, "nary-reassociate", "Nary reassociation", 187 false, false) 188 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 189 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 190 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 191 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 192 INITIALIZE_PASS_END(NaryReassociate, "nary-reassociate", "Nary reassociation", 193 false, false) 194 195 FunctionPass *llvm::createNaryReassociatePass() { 196 return new NaryReassociate(); 197 } 198 199 bool NaryReassociate::runOnFunction(Function &F) { 200 if (skipOptnoneFunction(F)) 201 return false; 202 203 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 204 SE = &getAnalysis<ScalarEvolution>(); 205 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 206 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 207 208 bool Changed = false, ChangedInThisIteration; 209 do { 210 ChangedInThisIteration = doOneIteration(F); 211 Changed |= ChangedInThisIteration; 212 } while (ChangedInThisIteration); 213 return Changed; 214 } 215 216 // Whitelist the instruction types NaryReassociate handles for now. 217 static bool isPotentiallyNaryReassociable(Instruction *I) { 218 switch (I->getOpcode()) { 219 case Instruction::Add: 220 case Instruction::GetElementPtr: 221 return true; 222 default: 223 return false; 224 } 225 } 226 227 bool NaryReassociate::doOneIteration(Function &F) { 228 bool Changed = false; 229 SeenExprs.clear(); 230 // Process the basic blocks in pre-order of the dominator tree. This order 231 // ensures that all bases of a candidate are in Candidates when we process it. 232 for (auto Node = GraphTraits<DominatorTree *>::nodes_begin(DT); 233 Node != GraphTraits<DominatorTree *>::nodes_end(DT); ++Node) { 234 BasicBlock *BB = Node->getBlock(); 235 for (auto I = BB->begin(); I != BB->end(); ++I) { 236 if (SE->isSCEVable(I->getType()) && isPotentiallyNaryReassociable(I)) { 237 const SCEV *OldSCEV = SE->getSCEV(I); 238 if (Instruction *NewI = tryReassociate(I)) { 239 Changed = true; 240 SE->forgetValue(I); 241 I->replaceAllUsesWith(NewI); 242 RecursivelyDeleteTriviallyDeadInstructions(I, TLI); 243 I = NewI; 244 } 245 // Add the rewritten instruction to SeenExprs; the original instruction 246 // is deleted. 247 const SCEV *NewSCEV = SE->getSCEV(I); 248 SeenExprs[NewSCEV].push_back(I); 249 // Ideally, NewSCEV should equal OldSCEV because tryReassociate(I) 250 // is equivalent to I. However, ScalarEvolution::getSCEV may 251 // weaken nsw causing NewSCEV not to equal OldSCEV. For example, suppose 252 // we reassociate 253 // I = &a[sext(i +nsw j)] // assuming sizeof(a[0]) = 4 254 // to 255 // NewI = &a[sext(i)] + sext(j). 256 // 257 // ScalarEvolution computes 258 // getSCEV(I) = a + 4 * sext(i + j) 259 // getSCEV(newI) = a + 4 * sext(i) + 4 * sext(j) 260 // which are different SCEVs. 261 // 262 // To alleviate this issue of ScalarEvolution not always capturing 263 // equivalence, we add I to SeenExprs[OldSCEV] as well so that we can 264 // map both SCEV before and after tryReassociate(I) to I. 265 // 266 // This improvement is exercised in @reassociate_gep_nsw in nary-gep.ll. 267 if (NewSCEV != OldSCEV) 268 SeenExprs[OldSCEV].push_back(I); 269 } 270 } 271 } 272 return Changed; 273 } 274 275 Instruction *NaryReassociate::tryReassociate(Instruction *I) { 276 switch (I->getOpcode()) { 277 case Instruction::Add: 278 return tryReassociateAdd(cast<BinaryOperator>(I)); 279 case Instruction::GetElementPtr: 280 return tryReassociateGEP(cast<GetElementPtrInst>(I)); 281 default: 282 llvm_unreachable("should be filtered out by isPotentiallyNaryReassociable"); 283 } 284 } 285 286 // FIXME: extract this method into TTI->getGEPCost. 287 static bool isGEPFoldable(GetElementPtrInst *GEP, 288 const TargetTransformInfo *TTI, 289 const DataLayout *DL) { 290 GlobalVariable *BaseGV = nullptr; 291 int64_t BaseOffset = 0; 292 bool HasBaseReg = false; 293 int64_t Scale = 0; 294 295 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand())) 296 BaseGV = GV; 297 else 298 HasBaseReg = true; 299 300 gep_type_iterator GTI = gep_type_begin(GEP); 301 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I, ++GTI) { 302 if (isa<SequentialType>(*GTI)) { 303 int64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 304 if (ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) { 305 BaseOffset += ConstIdx->getSExtValue() * ElementSize; 306 } else { 307 // Needs scale register. 308 if (Scale != 0) { 309 // No addressing mode takes two scale registers. 310 return false; 311 } 312 Scale = ElementSize; 313 } 314 } else { 315 StructType *STy = cast<StructType>(*GTI); 316 uint64_t Field = cast<ConstantInt>(*I)->getZExtValue(); 317 BaseOffset += DL->getStructLayout(STy)->getElementOffset(Field); 318 } 319 } 320 321 unsigned AddrSpace = GEP->getPointerAddressSpace(); 322 return TTI->isLegalAddressingMode(GEP->getType()->getElementType(), BaseGV, 323 BaseOffset, HasBaseReg, Scale, AddrSpace); 324 } 325 326 Instruction *NaryReassociate::tryReassociateGEP(GetElementPtrInst *GEP) { 327 // Not worth reassociating GEP if it is foldable. 328 if (isGEPFoldable(GEP, TTI, DL)) 329 return nullptr; 330 331 gep_type_iterator GTI = gep_type_begin(*GEP); 332 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) { 333 if (isa<SequentialType>(*GTI++)) { 334 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I - 1, *GTI)) { 335 return NewGEP; 336 } 337 } 338 } 339 return nullptr; 340 } 341 342 bool NaryReassociate::requiresSignExtension(Value *Index, 343 GetElementPtrInst *GEP) { 344 unsigned PointerSizeInBits = 345 DL->getPointerSizeInBits(GEP->getType()->getPointerAddressSpace()); 346 return cast<IntegerType>(Index->getType())->getBitWidth() < PointerSizeInBits; 347 } 348 349 GetElementPtrInst * 350 NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I, 351 Type *IndexedType) { 352 Value *IndexToSplit = GEP->getOperand(I + 1); 353 if (SExtInst *SExt = dyn_cast<SExtInst>(IndexToSplit)) 354 IndexToSplit = SExt->getOperand(0); 355 356 if (AddOperator *AO = dyn_cast<AddOperator>(IndexToSplit)) { 357 // If the I-th index needs sext and the underlying add is not equipped with 358 // nsw, we cannot split the add because 359 // sext(LHS + RHS) != sext(LHS) + sext(RHS). 360 if (requiresSignExtension(IndexToSplit, GEP) && !AO->hasNoSignedWrap()) 361 return nullptr; 362 Value *LHS = AO->getOperand(0), *RHS = AO->getOperand(1); 363 // IndexToSplit = LHS + RHS. 364 if (auto *NewGEP = tryReassociateGEPAtIndex(GEP, I, LHS, RHS, IndexedType)) 365 return NewGEP; 366 // Symmetrically, try IndexToSplit = RHS + LHS. 367 if (LHS != RHS) { 368 if (auto *NewGEP = 369 tryReassociateGEPAtIndex(GEP, I, RHS, LHS, IndexedType)) 370 return NewGEP; 371 } 372 } 373 return nullptr; 374 } 375 376 GetElementPtrInst * 377 NaryReassociate::tryReassociateGEPAtIndex(GetElementPtrInst *GEP, unsigned I, 378 Value *LHS, Value *RHS, 379 Type *IndexedType) { 380 // Look for GEP's closest dominator that has the same SCEV as GEP except that 381 // the I-th index is replaced with LHS. 382 SmallVector<const SCEV *, 4> IndexExprs; 383 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 384 IndexExprs.push_back(SE->getSCEV(*Index)); 385 // Replace the I-th index with LHS. 386 IndexExprs[I] = SE->getSCEV(LHS); 387 const SCEV *CandidateExpr = SE->getGEPExpr( 388 GEP->getSourceElementType(), SE->getSCEV(GEP->getPointerOperand()), 389 IndexExprs, GEP->isInBounds()); 390 391 auto *Candidate = findClosestMatchingDominator(CandidateExpr, GEP); 392 if (Candidate == nullptr) 393 return nullptr; 394 395 PointerType *TypeOfCandidate = dyn_cast<PointerType>(Candidate->getType()); 396 // Pretty rare but theoretically possible when a numeric value happens to 397 // share CandidateExpr. 398 if (TypeOfCandidate == nullptr) 399 return nullptr; 400 401 // NewGEP = (char *)Candidate + RHS * sizeof(IndexedType) 402 uint64_t IndexedSize = DL->getTypeAllocSize(IndexedType); 403 Type *ElementType = TypeOfCandidate->getElementType(); 404 uint64_t ElementSize = DL->getTypeAllocSize(ElementType); 405 // Another less rare case: because I is not necessarily the last index of the 406 // GEP, the size of the type at the I-th index (IndexedSize) is not 407 // necessarily divisible by ElementSize. For example, 408 // 409 // #pragma pack(1) 410 // struct S { 411 // int a[3]; 412 // int64 b[8]; 413 // }; 414 // #pragma pack() 415 // 416 // sizeof(S) = 100 is indivisible by sizeof(int64) = 8. 417 // 418 // TODO: bail out on this case for now. We could emit uglygep. 419 if (IndexedSize % ElementSize != 0) 420 return nullptr; 421 422 // NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0]))); 423 IRBuilder<> Builder(GEP); 424 Type *IntPtrTy = DL->getIntPtrType(TypeOfCandidate); 425 if (RHS->getType() != IntPtrTy) 426 RHS = Builder.CreateSExtOrTrunc(RHS, IntPtrTy); 427 if (IndexedSize != ElementSize) { 428 RHS = Builder.CreateMul( 429 RHS, ConstantInt::get(IntPtrTy, IndexedSize / ElementSize)); 430 } 431 GetElementPtrInst *NewGEP = 432 cast<GetElementPtrInst>(Builder.CreateGEP(Candidate, RHS)); 433 NewGEP->setIsInBounds(GEP->isInBounds()); 434 NewGEP->takeName(GEP); 435 return NewGEP; 436 } 437 438 Instruction *NaryReassociate::tryReassociateAdd(BinaryOperator *I) { 439 Value *LHS = I->getOperand(0), *RHS = I->getOperand(1); 440 if (auto *NewI = tryReassociateAdd(LHS, RHS, I)) 441 return NewI; 442 if (auto *NewI = tryReassociateAdd(RHS, LHS, I)) 443 return NewI; 444 return nullptr; 445 } 446 447 Instruction *NaryReassociate::tryReassociateAdd(Value *LHS, Value *RHS, 448 Instruction *I) { 449 Value *A = nullptr, *B = nullptr; 450 // To be conservative, we reassociate I only when it is the only user of A+B. 451 if (LHS->hasOneUse() && match(LHS, m_Add(m_Value(A), m_Value(B)))) { 452 // I = (A + B) + RHS 453 // = (A + RHS) + B or (B + RHS) + A 454 const SCEV *AExpr = SE->getSCEV(A), *BExpr = SE->getSCEV(B); 455 const SCEV *RHSExpr = SE->getSCEV(RHS); 456 if (BExpr != RHSExpr) { 457 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(AExpr, RHSExpr), B, I)) 458 return NewI; 459 } 460 if (AExpr != RHSExpr) { 461 if (auto *NewI = tryReassociatedAdd(SE->getAddExpr(BExpr, RHSExpr), A, I)) 462 return NewI; 463 } 464 } 465 return nullptr; 466 } 467 468 Instruction *NaryReassociate::tryReassociatedAdd(const SCEV *LHSExpr, 469 Value *RHS, Instruction *I) { 470 auto Pos = SeenExprs.find(LHSExpr); 471 // Bail out if LHSExpr is not previously seen. 472 if (Pos == SeenExprs.end()) 473 return nullptr; 474 475 // Look for the closest dominator LHS of I that computes LHSExpr, and replace 476 // I with LHS + RHS. 477 auto *LHS = findClosestMatchingDominator(LHSExpr, I); 478 if (LHS == nullptr) 479 return nullptr; 480 481 Instruction *NewI = BinaryOperator::CreateAdd(LHS, RHS, "", I); 482 NewI->takeName(I); 483 return NewI; 484 } 485 486 Instruction * 487 NaryReassociate::findClosestMatchingDominator(const SCEV *CandidateExpr, 488 Instruction *Dominatee) { 489 auto Pos = SeenExprs.find(CandidateExpr); 490 if (Pos == SeenExprs.end()) 491 return nullptr; 492 493 auto &Candidates = Pos->second; 494 // Because we process the basic blocks in pre-order of the dominator tree, a 495 // candidate that doesn't dominate the current instruction won't dominate any 496 // future instruction either. Therefore, we pop it out of the stack. This 497 // optimization makes the algorithm O(n). 498 while (!Candidates.empty()) { 499 Instruction *Candidate = Candidates.back(); 500 if (DT->dominates(Candidate, Dominatee)) 501 return Candidate; 502 Candidates.pop_back(); 503 } 504 return nullptr; 505 } 506