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