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