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     // FIXME: should this handle scalable vectors?
286     return FixedVectorType::get(Ty, VTy->getNumElements());
287   }
288   return Ty;
289 }
290 
291 Value *TruncInstCombine::getReducedOperand(Value *V, Type *SclTy) {
292   Type *Ty = getReducedType(V, SclTy);
293   if (auto *C = dyn_cast<Constant>(V)) {
294     C = ConstantExpr::getIntegerCast(C, Ty, false);
295     // If we got a constantexpr back, try to simplify it with DL info.
296     return ConstantFoldConstant(C, DL, &TLI);
297   }
298 
299   auto *I = cast<Instruction>(V);
300   Info Entry = InstInfoMap.lookup(I);
301   assert(Entry.NewValue);
302   return Entry.NewValue;
303 }
304 
305 void TruncInstCombine::ReduceExpressionDag(Type *SclTy) {
306   for (auto &Itr : InstInfoMap) { // Forward
307     Instruction *I = Itr.first;
308     TruncInstCombine::Info &NodeInfo = Itr.second;
309 
310     assert(!NodeInfo.NewValue && "Instruction has been evaluated");
311 
312     IRBuilder<> Builder(I);
313     Value *Res = nullptr;
314     unsigned Opc = I->getOpcode();
315     switch (Opc) {
316     case Instruction::Trunc:
317     case Instruction::ZExt:
318     case Instruction::SExt: {
319       Type *Ty = getReducedType(I, SclTy);
320       // If the source type of the cast is the type we're trying for then we can
321       // just return the source.  There's no need to insert it because it is not
322       // new.
323       if (I->getOperand(0)->getType() == Ty) {
324         assert(!isa<TruncInst>(I) && "Cannot reach here with TruncInst");
325         NodeInfo.NewValue = I->getOperand(0);
326         continue;
327       }
328       // Otherwise, must be the same type of cast, so just reinsert a new one.
329       // This also handles the case of zext(trunc(x)) -> zext(x).
330       Res = Builder.CreateIntCast(I->getOperand(0), Ty,
331                                   Opc == Instruction::SExt);
332 
333       // Update Worklist entries with new value if needed.
334       // There are three possible changes to the Worklist:
335       // 1. Update Old-TruncInst -> New-TruncInst.
336       // 2. Remove Old-TruncInst (if New node is not TruncInst).
337       // 3. Add New-TruncInst (if Old node was not TruncInst).
338       auto Entry = find(Worklist, I);
339       if (Entry != Worklist.end()) {
340         if (auto *NewCI = dyn_cast<TruncInst>(Res))
341           *Entry = NewCI;
342         else
343           Worklist.erase(Entry);
344       } else if (auto *NewCI = dyn_cast<TruncInst>(Res))
345           Worklist.push_back(NewCI);
346       break;
347     }
348     case Instruction::Add:
349     case Instruction::Sub:
350     case Instruction::Mul:
351     case Instruction::And:
352     case Instruction::Or:
353     case Instruction::Xor: {
354       Value *LHS = getReducedOperand(I->getOperand(0), SclTy);
355       Value *RHS = getReducedOperand(I->getOperand(1), SclTy);
356       Res = Builder.CreateBinOp((Instruction::BinaryOps)Opc, LHS, RHS);
357       break;
358     }
359     case Instruction::Select: {
360       Value *Op0 = I->getOperand(0);
361       Value *LHS = getReducedOperand(I->getOperand(1), SclTy);
362       Value *RHS = getReducedOperand(I->getOperand(2), SclTy);
363       Res = Builder.CreateSelect(Op0, LHS, RHS);
364       break;
365     }
366     default:
367       llvm_unreachable("Unhandled instruction");
368     }
369 
370     NodeInfo.NewValue = Res;
371     if (auto *ResI = dyn_cast<Instruction>(Res))
372       ResI->takeName(I);
373   }
374 
375   Value *Res = getReducedOperand(CurrentTruncInst->getOperand(0), SclTy);
376   Type *DstTy = CurrentTruncInst->getType();
377   if (Res->getType() != DstTy) {
378     IRBuilder<> Builder(CurrentTruncInst);
379     Res = Builder.CreateIntCast(Res, DstTy, false);
380     if (auto *ResI = dyn_cast<Instruction>(Res))
381       ResI->takeName(CurrentTruncInst);
382   }
383   CurrentTruncInst->replaceAllUsesWith(Res);
384 
385   // Erase old expression dag, which was replaced by the reduced expression dag.
386   // We iterate backward, which means we visit the instruction before we visit
387   // any of its operands, this way, when we get to the operand, we already
388   // removed the instructions (from the expression dag) that uses it.
389   CurrentTruncInst->eraseFromParent();
390   for (auto I = InstInfoMap.rbegin(), E = InstInfoMap.rend(); I != E; ++I) {
391     // We still need to check that the instruction has no users before we erase
392     // it, because {SExt, ZExt}Inst Instruction might have other users that was
393     // not reduced, in such case, we need to keep that instruction.
394     if (I->first->use_empty())
395       I->first->eraseFromParent();
396   }
397 }
398 
399 bool TruncInstCombine::run(Function &F) {
400   bool MadeIRChange = false;
401 
402   // Collect all TruncInst in the function into the Worklist for evaluating.
403   for (auto &BB : F) {
404     // Ignore unreachable basic block.
405     if (!DT.isReachableFromEntry(&BB))
406       continue;
407     for (auto &I : BB)
408       if (auto *CI = dyn_cast<TruncInst>(&I))
409         Worklist.push_back(CI);
410   }
411 
412   // Process all TruncInst in the Worklist, for each instruction:
413   //   1. Check if it dominates an eligible expression dag to be reduced.
414   //   2. Create a reduced expression dag and replace the old one with it.
415   while (!Worklist.empty()) {
416     CurrentTruncInst = Worklist.pop_back_val();
417 
418     if (Type *NewDstSclTy = getBestTruncatedType()) {
419       LLVM_DEBUG(
420           dbgs() << "ICE: TruncInstCombine reducing type of expression dag "
421                     "dominated by: "
422                  << CurrentTruncInst << '\n');
423       ReduceExpressionDag(NewDstSclTy);
424       MadeIRChange = true;
425     }
426   }
427 
428   return MadeIRChange;
429 }
430