1 //===- TruncInstCombine.cpp -----------------------------------------------===// 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 // TruncInstCombine - looks for expression dags post-dominated by TruncInst and 11 // for each eligible dag, it will create a reduced bit-width expression, replace 12 // the old expression with this new one and remove the old expression. 13 // Eligible expression dag is such that: 14 // 1. Contains only supported instructions. 15 // 2. Supported leaves: ZExtInst, SExtInst, TruncInst and Constant value. 16 // 3. Can be evaluated into type with reduced legal bit-width. 17 // 4. All instructions in the dag must not have users outside the dag. 18 // The only exception is for {ZExt, SExt}Inst with operand type equal to 19 // the new reduced type evaluated in (3). 20 // 21 // The motivation for this optimization is that evaluating and expression using 22 // smaller bit-width is preferable, especially for vectorization where we can 23 // fit more values in one vectorized instruction. In addition, this optimization 24 // may decrease the number of cast instructions, but will not increase it. 25 // 26 //===----------------------------------------------------------------------===// 27 28 #include "AggressiveInstCombineInternal.h" 29 #include "llvm/ADT/MapVector.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/TargetLibraryInfo.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/IRBuilder.h" 36 using namespace llvm; 37 38 #define DEBUG_TYPE "aggressive-instcombine" 39 40 /// Given an instruction and a container, it fills all the relevant operands of 41 /// that instruction, with respect to the Trunc expression dag optimizaton. 42 static void getRelevantOperands(Instruction *I, SmallVectorImpl<Value *> &Ops) { 43 unsigned Opc = I->getOpcode(); 44 switch (Opc) { 45 case Instruction::Trunc: 46 case Instruction::ZExt: 47 case Instruction::SExt: 48 // These CastInst are considered leaves of the evaluated expression, thus, 49 // their operands are not relevent. 50 break; 51 case Instruction::Add: 52 case Instruction::Sub: 53 case Instruction::Mul: 54 case Instruction::And: 55 case Instruction::Or: 56 case Instruction::Xor: 57 Ops.push_back(I->getOperand(0)); 58 Ops.push_back(I->getOperand(1)); 59 break; 60 default: 61 llvm_unreachable("Unreachable!"); 62 } 63 } 64 65 bool TruncInstCombine::buildTruncExpressionDag() { 66 SmallVector<Value *, 8> Worklist; 67 SmallVector<Instruction *, 8> Stack; 68 // Clear old expression dag. 69 InstInfoMap.clear(); 70 71 Worklist.push_back(CurrentTruncInst->getOperand(0)); 72 73 while (!Worklist.empty()) { 74 Value *Curr = Worklist.back(); 75 76 if (isa<Constant>(Curr)) { 77 Worklist.pop_back(); 78 continue; 79 } 80 81 auto *I = dyn_cast<Instruction>(Curr); 82 if (!I) 83 return false; 84 85 if (!Stack.empty() && Stack.back() == I) { 86 // Already handled all instruction operands, can remove it from both the 87 // Worklist and the Stack, and add it to the instruction info map. 88 Worklist.pop_back(); 89 Stack.pop_back(); 90 // Insert I to the Info map. 91 InstInfoMap.insert(std::make_pair(I, Info())); 92 continue; 93 } 94 95 if (InstInfoMap.count(I)) { 96 Worklist.pop_back(); 97 continue; 98 } 99 100 // Add the instruction to the stack before start handling its operands. 101 Stack.push_back(I); 102 103 unsigned Opc = I->getOpcode(); 104 switch (Opc) { 105 case Instruction::Trunc: 106 case Instruction::ZExt: 107 case Instruction::SExt: 108 // trunc(trunc(x)) -> trunc(x) 109 // trunc(ext(x)) -> ext(x) if the source type is smaller than the new dest 110 // trunc(ext(x)) -> trunc(x) if the source type is larger than the new 111 // dest 112 break; 113 case Instruction::Add: 114 case Instruction::Sub: 115 case Instruction::Mul: 116 case Instruction::And: 117 case Instruction::Or: 118 case Instruction::Xor: { 119 SmallVector<Value *, 2> Operands; 120 getRelevantOperands(I, Operands); 121 for (Value *Operand : Operands) 122 Worklist.push_back(Operand); 123 break; 124 } 125 default: 126 // TODO: Can handle more cases here: 127 // 1. select, shufflevector, extractelement, insertelement 128 // 2. udiv, urem 129 // 3. shl, lshr, ashr 130 // 4. phi node(and loop handling) 131 // ... 132 return false; 133 } 134 } 135 return true; 136 } 137 138 unsigned TruncInstCombine::getMinBitWidth() { 139 SmallVector<Value *, 8> Worklist; 140 SmallVector<Instruction *, 8> Stack; 141 142 Value *Src = CurrentTruncInst->getOperand(0); 143 Type *DstTy = CurrentTruncInst->getType(); 144 unsigned TruncBitWidth = DstTy->getScalarSizeInBits(); 145 unsigned OrigBitWidth = 146 CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits(); 147 148 if (isa<Constant>(Src)) 149 return TruncBitWidth; 150 151 Worklist.push_back(Src); 152 InstInfoMap[cast<Instruction>(Src)].ValidBitWidth = TruncBitWidth; 153 154 while (!Worklist.empty()) { 155 Value *Curr = Worklist.back(); 156 157 if (isa<Constant>(Curr)) { 158 Worklist.pop_back(); 159 continue; 160 } 161 162 // Otherwise, it must be an instruction. 163 auto *I = cast<Instruction>(Curr); 164 165 auto &Info = InstInfoMap[I]; 166 167 SmallVector<Value *, 2> Operands; 168 getRelevantOperands(I, Operands); 169 170 if (!Stack.empty() && Stack.back() == I) { 171 // Already handled all instruction operands, can remove it from both, the 172 // Worklist and the Stack, and update MinBitWidth. 173 Worklist.pop_back(); 174 Stack.pop_back(); 175 for (auto *Operand : Operands) 176 if (auto *IOp = dyn_cast<Instruction>(Operand)) 177 Info.MinBitWidth = 178 std::max(Info.MinBitWidth, InstInfoMap[IOp].MinBitWidth); 179 continue; 180 } 181 182 // Add the instruction to the stack before start handling its operands. 183 Stack.push_back(I); 184 unsigned ValidBitWidth = Info.ValidBitWidth; 185 186 // Update minimum bit-width before handling its operands. This is required 187 // when the instruction is part of a loop. 188 Info.MinBitWidth = std::max(Info.MinBitWidth, Info.ValidBitWidth); 189 190 for (auto *Operand : Operands) 191 if (auto *IOp = dyn_cast<Instruction>(Operand)) { 192 // If we already calculated the minimum bit-width for this valid 193 // bit-width, or for a smaller valid bit-width, then just keep the 194 // answer we already calculated. 195 unsigned IOpBitwidth = InstInfoMap.lookup(IOp).ValidBitWidth; 196 if (IOpBitwidth >= ValidBitWidth) 197 continue; 198 InstInfoMap[IOp].ValidBitWidth = std::max(ValidBitWidth, IOpBitwidth); 199 Worklist.push_back(IOp); 200 } 201 } 202 unsigned MinBitWidth = InstInfoMap.lookup(cast<Instruction>(Src)).MinBitWidth; 203 assert(MinBitWidth >= TruncBitWidth); 204 205 if (MinBitWidth > TruncBitWidth) { 206 // In this case reducing expression with vector type might generate a new 207 // vector type, which is not preferable as it might result in generating 208 // sub-optimal code. 209 if (DstTy->isVectorTy()) 210 return OrigBitWidth; 211 // Use the smallest integer type in the range [MinBitWidth, OrigBitWidth). 212 Type *Ty = DL.getSmallestLegalIntType(DstTy->getContext(), MinBitWidth); 213 // Update minimum bit-width with the new destination type bit-width if 214 // succeeded to find such, otherwise, with original bit-width. 215 MinBitWidth = Ty ? Ty->getScalarSizeInBits() : OrigBitWidth; 216 } else { // MinBitWidth == TruncBitWidth 217 // In this case the expression can be evaluated with the trunc instruction 218 // destination type, and trunc instruction can be omitted. However, we 219 // should not perform the evaluation if the original type is a legal scalar 220 // type and the target type is illegal. 221 bool FromLegal = MinBitWidth == 1 || DL.isLegalInteger(OrigBitWidth); 222 bool ToLegal = MinBitWidth == 1 || DL.isLegalInteger(MinBitWidth); 223 if (!DstTy->isVectorTy() && FromLegal && !ToLegal) 224 return OrigBitWidth; 225 } 226 return MinBitWidth; 227 } 228 229 Type *TruncInstCombine::getBestTruncatedType() { 230 if (!buildTruncExpressionDag()) 231 return nullptr; 232 233 // We don't want to duplicate instructions, which isn't profitable. Thus, we 234 // can't shrink something that has multiple users, unless all users are 235 // post-dominated by the trunc instruction, i.e., were visited during the 236 // expression evaluation. 237 unsigned DesiredBitWidth = 0; 238 for (auto Itr : InstInfoMap) { 239 Instruction *I = Itr.first; 240 if (I->hasOneUse()) 241 continue; 242 bool IsExtInst = (isa<ZExtInst>(I) || isa<SExtInst>(I)); 243 for (auto *U : I->users()) 244 if (auto *UI = dyn_cast<Instruction>(U)) 245 if (UI != CurrentTruncInst && !InstInfoMap.count(UI)) { 246 if (!IsExtInst) 247 return nullptr; 248 // If this is an extension from the dest type, we can eliminate it, 249 // even if it has multiple users. Thus, update the DesiredBitWidth and 250 // validate all extension instructions agrees on same DesiredBitWidth. 251 unsigned ExtInstBitWidth = 252 I->getOperand(0)->getType()->getScalarSizeInBits(); 253 if (DesiredBitWidth && DesiredBitWidth != ExtInstBitWidth) 254 return nullptr; 255 DesiredBitWidth = ExtInstBitWidth; 256 } 257 } 258 259 unsigned OrigBitWidth = 260 CurrentTruncInst->getOperand(0)->getType()->getScalarSizeInBits(); 261 262 // Calculate minimum allowed bit-width allowed for shrinking the currently 263 // visited truncate's operand. 264 unsigned MinBitWidth = getMinBitWidth(); 265 266 // Check that we can shrink to smaller bit-width than original one and that 267 // it is similar to the DesiredBitWidth is such exists. 268 if (MinBitWidth >= OrigBitWidth || 269 (DesiredBitWidth && DesiredBitWidth != MinBitWidth)) 270 return nullptr; 271 272 return IntegerType::get(CurrentTruncInst->getContext(), MinBitWidth); 273 } 274 275 /// Given a reduced scalar type \p Ty and a \p V value, return a reduced type 276 /// for \p V, according to its type, if it vector type, return the vector 277 /// version of \p Ty, otherwise return \p Ty. 278 static Type *getReducedType(Value *V, Type *Ty) { 279 assert(Ty && !Ty->isVectorTy() && "Expect Scalar Type"); 280 if (auto *VTy = dyn_cast<VectorType>(V->getType())) 281 return VectorType::get(Ty, VTy->getNumElements()); 282 return Ty; 283 } 284 285 Value *TruncInstCombine::getReducedOperand(Value *V, Type *SclTy) { 286 Type *Ty = getReducedType(V, SclTy); 287 if (auto *C = dyn_cast<Constant>(V)) { 288 C = ConstantExpr::getIntegerCast(C, Ty, false); 289 // If we got a constantexpr back, try to simplify it with DL info. 290 if (Constant *FoldedC = ConstantFoldConstant(C, DL, &TLI)) 291 C = FoldedC; 292 return C; 293 } 294 295 auto *I = cast<Instruction>(V); 296 Info Entry = InstInfoMap.lookup(I); 297 assert(Entry.NewValue); 298 return Entry.NewValue; 299 } 300 301 void TruncInstCombine::ReduceExpressionDag(Type *SclTy) { 302 for (auto &Itr : InstInfoMap) { // Forward 303 Instruction *I = Itr.first; 304 TruncInstCombine::Info &NodeInfo = Itr.second; 305 306 assert(!NodeInfo.NewValue && "Instruction has been evaluated"); 307 308 IRBuilder<> Builder(I); 309 Value *Res = nullptr; 310 unsigned Opc = I->getOpcode(); 311 switch (Opc) { 312 case Instruction::Trunc: 313 case Instruction::ZExt: 314 case Instruction::SExt: { 315 Type *Ty = getReducedType(I, SclTy); 316 // If the source type of the cast is the type we're trying for then we can 317 // just return the source. There's no need to insert it because it is not 318 // new. 319 if (I->getOperand(0)->getType() == Ty) { 320 assert(!isa<TruncInst>(I) && "Cannot reach here with TruncInst"); 321 NodeInfo.NewValue = I->getOperand(0); 322 continue; 323 } 324 // Otherwise, must be the same type of cast, so just reinsert a new one. 325 // This also handles the case of zext(trunc(x)) -> zext(x). 326 Res = Builder.CreateIntCast(I->getOperand(0), Ty, 327 Opc == Instruction::SExt); 328 329 // Update Worklist entries with new value if needed. 330 // There are three possible changes to the Worklist: 331 // 1. Update Old-TruncInst -> New-TruncInst. 332 // 2. Remove Old-TruncInst (if New node is not TruncInst). 333 // 3. Add New-TruncInst (if Old node was not TruncInst). 334 auto Entry = find(Worklist, I); 335 if (Entry != Worklist.end()) { 336 if (auto *NewCI = dyn_cast<TruncInst>(Res)) 337 *Entry = NewCI; 338 else 339 Worklist.erase(Entry); 340 } else if (auto *NewCI = dyn_cast<TruncInst>(Res)) 341 Worklist.push_back(NewCI); 342 break; 343 } 344 case Instruction::Add: 345 case Instruction::Sub: 346 case Instruction::Mul: 347 case Instruction::And: 348 case Instruction::Or: 349 case Instruction::Xor: { 350 Value *LHS = getReducedOperand(I->getOperand(0), SclTy); 351 Value *RHS = getReducedOperand(I->getOperand(1), SclTy); 352 Res = Builder.CreateBinOp((Instruction::BinaryOps)Opc, LHS, RHS); 353 break; 354 } 355 default: 356 llvm_unreachable("Unhandled instruction"); 357 } 358 359 NodeInfo.NewValue = Res; 360 if (auto *ResI = dyn_cast<Instruction>(Res)) 361 ResI->takeName(I); 362 } 363 364 Value *Res = getReducedOperand(CurrentTruncInst->getOperand(0), SclTy); 365 Type *DstTy = CurrentTruncInst->getType(); 366 if (Res->getType() != DstTy) { 367 IRBuilder<> Builder(CurrentTruncInst); 368 Res = Builder.CreateIntCast(Res, DstTy, false); 369 if (auto *ResI = dyn_cast<Instruction>(Res)) 370 ResI->takeName(CurrentTruncInst); 371 } 372 CurrentTruncInst->replaceAllUsesWith(Res); 373 374 // Erase old expression dag, which was replaced by the reduced expression dag. 375 // We iterate backward, which means we visit the instruction before we visit 376 // any of its operands, this way, when we get to the operand, we already 377 // removed the instructions (from the expression dag) that uses it. 378 CurrentTruncInst->eraseFromParent(); 379 for (auto I = InstInfoMap.rbegin(), E = InstInfoMap.rend(); I != E; ++I) { 380 // We still need to check that the instruction has no users before we erase 381 // it, because {SExt, ZExt}Inst Instruction might have other users that was 382 // not reduced, in such case, we need to keep that instruction. 383 if (I->first->use_empty()) 384 I->first->eraseFromParent(); 385 } 386 } 387 388 bool TruncInstCombine::run(Function &F) { 389 bool MadeIRChange = false; 390 391 // Collect all TruncInst in the function into the Worklist for evaluating. 392 for (auto &BB : F) { 393 // Ignore unreachable basic block. 394 if (!DT.isReachableFromEntry(&BB)) 395 continue; 396 for (auto &I : BB) 397 if (auto *CI = dyn_cast<TruncInst>(&I)) 398 Worklist.push_back(CI); 399 } 400 401 // Process all TruncInst in the Worklist, for each instruction: 402 // 1. Check if it dominates an eligible expression dag to be reduced. 403 // 2. Create a reduced expression dag and replace the old one with it. 404 while (!Worklist.empty()) { 405 CurrentTruncInst = Worklist.pop_back_val(); 406 407 if (Type *NewDstSclTy = getBestTruncatedType()) { 408 LLVM_DEBUG( 409 dbgs() << "ICE: TruncInstCombine reducing type of expression dag " 410 "dominated by: " 411 << CurrentTruncInst << '\n'); 412 ReduceExpressionDag(NewDstSclTy); 413 MadeIRChange = true; 414 } 415 } 416 417 return MadeIRChange; 418 } 419