| 1 | //===- LoopUnrollAnalyzer.cpp - Unrolling Effect Estimation -----*- C++ -*-===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file implements UnrolledInstAnalyzer class. It's used for predicting |
| 10 | // potential effects that loop unrolling might have, such as enabling constant |
| 11 | // propagation and other optimizations. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "llvm/Analysis/LoopUnrollAnalyzer.h" |
| 16 | #include "llvm/Analysis/ConstantFolding.h" |
| 17 | #include "llvm/Analysis/InstructionSimplify.h" |
| 18 | #include "llvm/Analysis/LoopInfo.h" |
| 19 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
| 20 | #include "llvm/IR/IntrinsicInst.h" |
| 21 | #include "llvm/IR/Operator.h" |
| 22 | |
| 23 | using namespace llvm; |
| 24 | |
| 25 | /// Try to simplify instruction \param I using its SCEV expression. |
| 26 | /// |
| 27 | /// The idea is that some AddRec expressions become constants, which then |
| 28 | /// could trigger folding of other instructions. However, that only happens |
| 29 | /// for expressions whose start value is also constant, which isn't always the |
| 30 | /// case. In another common and important case the start value is just some |
| 31 | /// address (i.e. SCEVUnknown) - in this case we compute the offset and save |
| 32 | /// it along with the base address instead. |
| 33 | bool UnrolledInstAnalyzer::simplifyInstWithSCEV(Instruction *I) { |
| 34 | if (!SE.isSCEVable(Ty: I->getType())) |
| 35 | return false; |
| 36 | |
| 37 | const SCEV *S = SE.getSCEV(V: I); |
| 38 | if (auto *SC = dyn_cast<SCEVConstant>(Val: S)) { |
| 39 | SimplifiedValues[I] = SC->getValue(); |
| 40 | return true; |
| 41 | } |
| 42 | |
| 43 | // If we have a loop invariant computation, we only need to compute it once. |
| 44 | // Given that, all but the first occurance are free. |
| 45 | if (!IterationNumber->isZero() && SE.isLoopInvariant(S, L)) |
| 46 | return true; |
| 47 | |
| 48 | auto *AR = dyn_cast<SCEVAddRecExpr>(Val: S); |
| 49 | if (!AR || AR->getLoop() != L) |
| 50 | return false; |
| 51 | |
| 52 | const SCEV *ValueAtIteration = AR->evaluateAtIteration(It: IterationNumber, SE); |
| 53 | // Check if the AddRec expression becomes a constant. |
| 54 | if (auto *SC = dyn_cast<SCEVConstant>(Val: ValueAtIteration)) { |
| 55 | SimplifiedValues[I] = SC->getValue(); |
| 56 | return true; |
| 57 | } |
| 58 | |
| 59 | // Check if the offset from the base address becomes a constant. |
| 60 | auto *Base = dyn_cast<SCEVUnknown>(Val: SE.getPointerBase(V: S)); |
| 61 | if (!Base) |
| 62 | return false; |
| 63 | std::optional<APInt> Offset = |
| 64 | SE.computeConstantDifference(LHS: ValueAtIteration, RHS: Base); |
| 65 | if (!Offset) |
| 66 | return false; |
| 67 | SimplifiedAddress Address; |
| 68 | Address.Base = Base->getValue(); |
| 69 | Address.Offset = *Offset; |
| 70 | SimplifiedAddresses[I] = std::move(Address); |
| 71 | return false; |
| 72 | } |
| 73 | |
| 74 | /// Try to simplify binary operator I. |
| 75 | /// |
| 76 | /// TODO: Probably it's worth to hoist the code for estimating the |
| 77 | /// simplifications effects to a separate class, since we have a very similar |
| 78 | /// code in InlineCost already. |
| 79 | bool UnrolledInstAnalyzer::visitBinaryOperator(BinaryOperator &I) { |
| 80 | Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1); |
| 81 | if (!isa<Constant>(Val: LHS)) |
| 82 | if (Value *SimpleLHS = SimplifiedValues.lookup(Val: LHS)) |
| 83 | LHS = SimpleLHS; |
| 84 | if (!isa<Constant>(Val: RHS)) |
| 85 | if (Value *SimpleRHS = SimplifiedValues.lookup(Val: RHS)) |
| 86 | RHS = SimpleRHS; |
| 87 | |
| 88 | Value *SimpleV = nullptr; |
| 89 | const DataLayout &DL = I.getDataLayout(); |
| 90 | if (auto FI = dyn_cast<FPMathOperator>(Val: &I)) |
| 91 | SimpleV = |
| 92 | simplifyBinOp(Opcode: I.getOpcode(), LHS, RHS, FMF: FI->getFastMathFlags(), Q: DL); |
| 93 | else |
| 94 | SimpleV = simplifyBinOp(Opcode: I.getOpcode(), LHS, RHS, Q: DL); |
| 95 | |
| 96 | if (SimpleV) { |
| 97 | SimplifiedValues[&I] = SimpleV; |
| 98 | return true; |
| 99 | } |
| 100 | return Base::visitBinaryOperator(I); |
| 101 | } |
| 102 | |
| 103 | /// Try to fold load I. |
| 104 | bool UnrolledInstAnalyzer::visitLoad(LoadInst &I) { |
| 105 | Value *AddrOp = I.getPointerOperand(); |
| 106 | |
| 107 | auto AddressIt = SimplifiedAddresses.find(Val: AddrOp); |
| 108 | if (AddressIt == SimplifiedAddresses.end()) |
| 109 | return false; |
| 110 | |
| 111 | auto *GV = dyn_cast<GlobalVariable>(Val: AddressIt->second.Base); |
| 112 | // We're only interested in loads that can be completely folded to a |
| 113 | // constant. |
| 114 | if (!GV || !GV->hasDefinitiveInitializer() || !GV->isConstant()) |
| 115 | return false; |
| 116 | |
| 117 | Constant *Res = |
| 118 | ConstantFoldLoadFromConst(C: GV->getInitializer(), Ty: I.getType(), |
| 119 | Offset: AddressIt->second.Offset, DL: I.getDataLayout()); |
| 120 | if (!Res) |
| 121 | return false; |
| 122 | |
| 123 | SimplifiedValues[&I] = Res; |
| 124 | return true; |
| 125 | } |
| 126 | |
| 127 | /// Try to simplify cast instruction. |
| 128 | bool UnrolledInstAnalyzer::visitCastInst(CastInst &I) { |
| 129 | Value *Op = I.getOperand(i_nocapture: 0); |
| 130 | if (Value *Simplified = SimplifiedValues.lookup(Val: Op)) |
| 131 | Op = Simplified; |
| 132 | |
| 133 | // The cast can be invalid, because SimplifiedValues contains results of SCEV |
| 134 | // analysis, which operates on integers (and, e.g., might convert i8* null to |
| 135 | // i32 0). |
| 136 | if (CastInst::castIsValid(op: I.getOpcode(), S: Op, DstTy: I.getType())) { |
| 137 | const DataLayout &DL = I.getDataLayout(); |
| 138 | if (Value *V = simplifyCastInst(CastOpc: I.getOpcode(), Op, Ty: I.getType(), Q: DL)) { |
| 139 | SimplifiedValues[&I] = V; |
| 140 | return true; |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | return Base::visitCastInst(I); |
| 145 | } |
| 146 | |
| 147 | /// Try to simplify cmp instruction. |
| 148 | bool UnrolledInstAnalyzer::visitCmpInst(CmpInst &I) { |
| 149 | Value *LHS = I.getOperand(i_nocapture: 0), *RHS = I.getOperand(i_nocapture: 1); |
| 150 | |
| 151 | // First try to handle simplified comparisons. |
| 152 | if (!isa<Constant>(Val: LHS)) |
| 153 | if (Value *SimpleLHS = SimplifiedValues.lookup(Val: LHS)) |
| 154 | LHS = SimpleLHS; |
| 155 | if (!isa<Constant>(Val: RHS)) |
| 156 | if (Value *SimpleRHS = SimplifiedValues.lookup(Val: RHS)) |
| 157 | RHS = SimpleRHS; |
| 158 | |
| 159 | if (!isa<Constant>(Val: LHS) && !isa<Constant>(Val: RHS) && !I.isSigned()) { |
| 160 | auto SimplifiedLHS = SimplifiedAddresses.find(Val: LHS); |
| 161 | if (SimplifiedLHS != SimplifiedAddresses.end()) { |
| 162 | auto SimplifiedRHS = SimplifiedAddresses.find(Val: RHS); |
| 163 | if (SimplifiedRHS != SimplifiedAddresses.end()) { |
| 164 | SimplifiedAddress &LHSAddr = SimplifiedLHS->second; |
| 165 | SimplifiedAddress &RHSAddr = SimplifiedRHS->second; |
| 166 | if (LHSAddr.Base == RHSAddr.Base) { |
| 167 | // FIXME: This is only correct for equality predicates. For |
| 168 | // unsigned predicates, this only holds if we have nowrap flags, |
| 169 | // which we don't track (for nuw it's valid as-is, for nusw it |
| 170 | // requires converting the predicated to signed). As this is used only |
| 171 | // for cost modelling, this is not a correctness issue. |
| 172 | bool Res = ICmpInst::compare(LHS: LHSAddr.Offset, RHS: RHSAddr.Offset, |
| 173 | Pred: I.getPredicate()); |
| 174 | SimplifiedValues[&I] = ConstantInt::getBool(Ty: I.getType(), V: Res); |
| 175 | return true; |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | const DataLayout &DL = I.getDataLayout(); |
| 182 | if (Value *V = simplifyCmpInst(Predicate: I.getPredicate(), LHS, RHS, Q: DL)) { |
| 183 | SimplifiedValues[&I] = V; |
| 184 | return true; |
| 185 | } |
| 186 | |
| 187 | return Base::visitCmpInst(I); |
| 188 | } |
| 189 | |
| 190 | bool UnrolledInstAnalyzer::visitPHINode(PHINode &PN) { |
| 191 | // Run base visitor first. This way we can gather some useful for later |
| 192 | // analysis information. |
| 193 | if (Base::visitPHINode(I&: PN)) |
| 194 | return true; |
| 195 | |
| 196 | // The loop induction PHI nodes are definitionally free. |
| 197 | return PN.getParent() == L->getHeader(); |
| 198 | } |
| 199 | |
| 200 | /// Returns true if \p I computes the same value on every iteration of the |
| 201 | /// loop: it does not access memory, has no side effects, and all of its |
| 202 | /// operands are defined outside the loop or are themselves such computations. |
| 203 | /// Unlike SCEV-based invariance this works for any type, e.g. floating point. |
| 204 | bool UnrolledInstAnalyzer::isInvariantComputation(Instruction *I) { |
| 205 | if (!L->contains(Inst: I)) |
| 206 | return true; |
| 207 | if (auto It = InvariantInsts.find(Val: I); It != InvariantInsts.end()) |
| 208 | return It->second; |
| 209 | auto *II = dyn_cast<IntrinsicInst>(Val: I); |
| 210 | if (isa<PHINode, AllocaInst>(Val: I) || I->isTerminator() || |
| 211 | (II && II->isAssumeLikeIntrinsic()) || I->mayReadOrWriteMemory() || |
| 212 | I->mayHaveSideEffects()) { |
| 213 | InvariantInsts[I] = false; |
| 214 | return false; |
| 215 | } |
| 216 | bool Invariant = all_of(Range: I->operands(), P: [&](Value *Op) { |
| 217 | auto *OpI = dyn_cast<Instruction>(Val: Op); |
| 218 | return !OpI || isInvariantComputation(I: OpI); |
| 219 | }); |
| 220 | InvariantInsts[I] = Invariant; |
| 221 | return Invariant; |
| 222 | } |
| 223 | |
| 224 | bool UnrolledInstAnalyzer::visitInstruction(Instruction &I) { |
| 225 | if (simplifyInstWithSCEV(I: &I)) |
| 226 | return true; |
| 227 | |
| 228 | // Invariance of SCEVable values is decided by SCEV above. For other values, |
| 229 | // e.g. floating point, an invariant computation likewise only has to be |
| 230 | // performed once after unrolling; all but the first occurrence are free. |
| 231 | return !SE.isSCEVable(Ty: I.getType()) && !IterationNumber->isZero() && |
| 232 | isInvariantComputation(I: &I); |
| 233 | } |
| 234 | |