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