blob: 0378ea79ef7430ed46596a17e9d8bf4484a9e527 [file] [log] [blame]
Amjad Aboudf1f57a32018-01-25 12:06:32 +00001//===- 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"
Amjad Aboudd895bff2018-01-31 10:41:31 +000034#include "llvm/IR/Dominators.h"
Amjad Aboudf1f57a32018-01-25 12:06:32 +000035#include "llvm/IR/IRBuilder.h"
36using 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.
42static 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
65bool 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
138unsigned 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
229Type *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.
278static 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
285Value *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
301void 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 NodeInfo.NewValue = I->getOperand(0);
321 continue;
322 }
323 // Otherwise, must be the same type of cast, so just reinsert a new one.
324 // This also handles the case of zext(trunc(x)) -> zext(x).
325 Res = Builder.CreateIntCast(I->getOperand(0), Ty,
326 Opc == Instruction::SExt);
327
328 // Update Worklist entries with new value if needed.
329 if (auto *NewCI = dyn_cast<TruncInst>(Res)) {
330 auto Entry = find(Worklist, I);
331 if (Entry != Worklist.end())
332 *Entry = NewCI;
333 }
334 break;
335 }
336 case Instruction::Add:
337 case Instruction::Sub:
338 case Instruction::Mul:
339 case Instruction::And:
340 case Instruction::Or:
341 case Instruction::Xor: {
342 Value *LHS = getReducedOperand(I->getOperand(0), SclTy);
343 Value *RHS = getReducedOperand(I->getOperand(1), SclTy);
344 Res = Builder.CreateBinOp((Instruction::BinaryOps)Opc, LHS, RHS);
345 break;
346 }
347 default:
348 llvm_unreachable("Unhandled instruction");
349 }
350
351 NodeInfo.NewValue = Res;
352 if (auto *ResI = dyn_cast<Instruction>(Res))
353 ResI->takeName(I);
354 }
355
356 Value *Res = getReducedOperand(CurrentTruncInst->getOperand(0), SclTy);
357 Type *DstTy = CurrentTruncInst->getType();
358 if (Res->getType() != DstTy) {
359 IRBuilder<> Builder(CurrentTruncInst);
360 Res = Builder.CreateIntCast(Res, DstTy, false);
361 if (auto *ResI = dyn_cast<Instruction>(Res))
362 ResI->takeName(CurrentTruncInst);
363 }
364 CurrentTruncInst->replaceAllUsesWith(Res);
365
366 // Erase old expression dag, which was replaced by the reduced expression dag.
367 // We iterate backward, which means we visit the instruction before we visit
368 // any of its operands, this way, when we get to the operand, we already
369 // removed the instructions (from the expression dag) that uses it.
370 CurrentTruncInst->eraseFromParent();
371 for (auto I = InstInfoMap.rbegin(), E = InstInfoMap.rend(); I != E; ++I) {
372 // We still need to check that the instruction has no users before we erase
373 // it, because {SExt, ZExt}Inst Instruction might have other users that was
374 // not reduced, in such case, we need to keep that instruction.
375 if (!I->first->getNumUses())
376 I->first->eraseFromParent();
377 }
378}
379
380bool TruncInstCombine::run(Function &F) {
381 bool MadeIRChange = false;
382
383 // Collect all TruncInst in the function into the Worklist for evaluating.
Amjad Aboudd895bff2018-01-31 10:41:31 +0000384 for (auto &BB : F) {
385 // Ignore unreachable basic block.
386 if (!DT.isReachableFromEntry(&BB))
387 continue;
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000388 for (auto &I : BB)
389 if (auto *CI = dyn_cast<TruncInst>(&I))
390 Worklist.push_back(CI);
Amjad Aboudd895bff2018-01-31 10:41:31 +0000391 }
Amjad Aboudf1f57a32018-01-25 12:06:32 +0000392
393 // Process all TruncInst in the Worklist, for each instruction:
394 // 1. Check if it dominates an eligible expression dag to be reduced.
395 // 2. Create a reduced expression dag and replace the old one with it.
396 while (!Worklist.empty()) {
397 CurrentTruncInst = Worklist.pop_back_val();
398
399 if (Type *NewDstSclTy = getBestTruncatedType()) {
400 DEBUG(dbgs() << "ICE: TruncInstCombine reducing type of expression dag "
401 "dominated by: "
402 << CurrentTruncInst << '\n');
403 ReduceExpressionDag(NewDstSclTy);
404 MadeIRChange = true;
405 }
406 }
407
408 return MadeIRChange;
409}