blob: 7a7eb6b6829331aa77ccb346798d6c129d877603 [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
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// This file implements routines for folding instructions into simpler forms
11// that do not require creating new instructions. For example, this does
12// constant folding, and can handle identities like (X&0)->0.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner40d8c282009-11-10 22:26:15 +000018#include "llvm/Support/ValueHandle.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000019#include "llvm/Instructions.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000020#include "llvm/Support/PatternMatch.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000021using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000022using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000023
Chris Lattnerd06094f2009-11-10 00:55:12 +000024/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +000025/// fold the result. If not, this returns null.
Chris Lattnerd06094f2009-11-10 00:55:12 +000026Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1,
27 const TargetData *TD) {
28 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
29 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
30 Constant *Ops[] = { CLHS, CRHS };
31 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
32 Ops, 2, TD);
33 }
34
35 // Canonicalize the constant to the RHS.
36 std::swap(Op0, Op1);
37 }
38
39 // X & undef -> 0
40 if (isa<UndefValue>(Op1))
41 return Constant::getNullValue(Op0->getType());
42
43 // X & X = X
44 if (Op0 == Op1)
45 return Op0;
46
47 // X & <0,0> = <0,0>
48 if (isa<ConstantAggregateZero>(Op1))
49 return Op1;
50
51 // X & <-1,-1> = X
52 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1))
53 if (CP->isAllOnesValue())
54 return Op0;
55
56 if (ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1)) {
57 // X & 0 = 0
58 if (Op1CI->isZero())
59 return Op1CI;
60 // X & -1 = X
61 if (Op1CI->isAllOnesValue())
62 return Op0;
63 }
64
65 // A & ~A = ~A & A = 0
66 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +000067 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
68 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +000069 return Constant::getNullValue(Op0->getType());
70
71 // (A | ?) & A = A
72 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
73 (A == Op1 || B == Op1))
74 return Op1;
75
76 // A & (A | ?) = A
77 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
78 (A == Op0 || B == Op0))
79 return Op0;
80
Chris Lattner9f3c25a2009-11-09 22:57:59 +000081 return 0;
82}
83
Chris Lattnerd06094f2009-11-10 00:55:12 +000084/// SimplifyOrInst - Given operands for an Or, see if we can
85/// fold the result. If not, this returns null.
86Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1,
87 const TargetData *TD) {
88 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
89 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
90 Constant *Ops[] = { CLHS, CRHS };
91 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
92 Ops, 2, TD);
93 }
94
95 // Canonicalize the constant to the RHS.
96 std::swap(Op0, Op1);
97 }
98
99 // X | undef -> -1
100 if (isa<UndefValue>(Op1))
101 return Constant::getAllOnesValue(Op0->getType());
102
103 // X | X = X
104 if (Op0 == Op1)
105 return Op0;
106
107 // X | <0,0> = X
108 if (isa<ConstantAggregateZero>(Op1))
109 return Op0;
110
111 // X | <-1,-1> = <-1,-1>
112 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1))
113 if (CP->isAllOnesValue())
114 return Op1;
115
116 if (ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1)) {
117 // X | 0 = X
118 if (Op1CI->isZero())
119 return Op0;
120 // X | -1 = -1
121 if (Op1CI->isAllOnesValue())
122 return Op1CI;
123 }
124
125 // A | ~A = ~A | A = -1
126 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000127 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
128 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000129 return Constant::getAllOnesValue(Op0->getType());
130
131 // (A & ?) | A = A
132 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
133 (A == Op1 || B == Op1))
134 return Op1;
135
136 // A | (A & ?) = A
137 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
138 (A == Op0 || B == Op0))
139 return Op0;
140
141 return 0;
142}
143
144
145
146
Chris Lattner210c5d42009-11-09 23:55:12 +0000147static const Type *GetCompareTy(Value *Op) {
148 return CmpInst::makeCmpResultType(Op->getType());
149}
150
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000151
Chris Lattner9dbb4292009-11-09 23:28:39 +0000152/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
153/// fold the result. If not, this returns null.
154Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
155 const TargetData *TD) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000156 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000157 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000158
Chris Lattnerd06094f2009-11-10 00:55:12 +0000159 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000160 if (Constant *CRHS = dyn_cast<Constant>(RHS))
161 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000162
163 // If we have a constant, make sure it is on the RHS.
164 std::swap(LHS, RHS);
165 Pred = CmpInst::getSwappedPredicate(Pred);
166 }
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000167
Chris Lattner210c5d42009-11-09 23:55:12 +0000168 // ITy - This is the return type of the compare we're considering.
169 const Type *ITy = GetCompareTy(LHS);
170
171 // icmp X, X -> true/false
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000172 if (LHS == RHS)
Chris Lattner210c5d42009-11-09 23:55:12 +0000173 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Chris Lattner9dbb4292009-11-09 23:28:39 +0000174
Chris Lattner210c5d42009-11-09 23:55:12 +0000175 if (isa<UndefValue>(RHS)) // X icmp undef -> undef
176 return UndefValue::get(ITy);
177
178 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
179 // addresses never equal each other! We already know that Op0 != Op1.
180 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
181 isa<ConstantPointerNull>(LHS)) &&
182 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
183 isa<ConstantPointerNull>(RHS)))
184 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
185
186 // See if we are doing a comparison with a constant.
187 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
188 // If we have an icmp le or icmp ge instruction, turn it into the
189 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
190 // them being folded in the code below.
191 switch (Pred) {
192 default: break;
193 case ICmpInst::ICMP_ULE:
194 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
195 return ConstantInt::getTrue(CI->getContext());
196 break;
197 case ICmpInst::ICMP_SLE:
198 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
199 return ConstantInt::getTrue(CI->getContext());
200 break;
201 case ICmpInst::ICMP_UGE:
202 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
203 return ConstantInt::getTrue(CI->getContext());
204 break;
205 case ICmpInst::ICMP_SGE:
206 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
207 return ConstantInt::getTrue(CI->getContext());
208 break;
209 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000210 }
211
212
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000213 return 0;
214}
215
Chris Lattner9dbb4292009-11-09 23:28:39 +0000216/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
217/// fold the result. If not, this returns null.
218Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
219 const TargetData *TD) {
220 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
221 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
222
Chris Lattnerd06094f2009-11-10 00:55:12 +0000223 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000224 if (Constant *CRHS = dyn_cast<Constant>(RHS))
225 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000226
227 // If we have a constant, make sure it is on the RHS.
228 std::swap(LHS, RHS);
229 Pred = CmpInst::getSwappedPredicate(Pred);
230 }
Chris Lattner9dbb4292009-11-09 23:28:39 +0000231
Chris Lattner210c5d42009-11-09 23:55:12 +0000232 // Fold trivial predicates.
233 if (Pred == FCmpInst::FCMP_FALSE)
234 return ConstantInt::get(GetCompareTy(LHS), 0);
235 if (Pred == FCmpInst::FCMP_TRUE)
236 return ConstantInt::get(GetCompareTy(LHS), 1);
237
Chris Lattner210c5d42009-11-09 23:55:12 +0000238 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
239 return UndefValue::get(GetCompareTy(LHS));
240
241 // fcmp x,x -> true/false. Not all compares are foldable.
242 if (LHS == RHS) {
243 if (CmpInst::isTrueWhenEqual(Pred))
244 return ConstantInt::get(GetCompareTy(LHS), 1);
245 if (CmpInst::isFalseWhenEqual(Pred))
246 return ConstantInt::get(GetCompareTy(LHS), 0);
247 }
248
249 // Handle fcmp with constant RHS
250 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
251 // If the constant is a nan, see if we can fold the comparison based on it.
252 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
253 if (CFP->getValueAPF().isNaN()) {
254 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
255 return ConstantInt::getFalse(CFP->getContext());
256 assert(FCmpInst::isUnordered(Pred) &&
257 "Comparison must be either ordered or unordered!");
258 // True if unordered.
259 return ConstantInt::getTrue(CFP->getContext());
260 }
261 }
262 }
263
Chris Lattner9dbb4292009-11-09 23:28:39 +0000264 return 0;
265}
266
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000267/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
268/// fold the result. If not, this returns null.
269Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
270 const TargetData *TD) {
271 // getelementptr P -> P.
272 if (NumOps == 1)
273 return Ops[0];
274
275 // TODO.
276 //if (isa<UndefValue>(Ops[0]))
277 // return UndefValue::get(GEP.getType());
278
279 // getelementptr P, 0 -> P.
280 if (NumOps == 2)
281 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
282 if (C->isZero())
283 return Ops[0];
284
285 // Check to see if this is constant foldable.
286 for (unsigned i = 0; i != NumOps; ++i)
287 if (!isa<Constant>(Ops[i]))
288 return 0;
289
290 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
291 (Constant *const*)Ops+1, NumOps-1);
292}
293
294
Chris Lattnerd06094f2009-11-10 00:55:12 +0000295//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000296
Chris Lattnerd06094f2009-11-10 00:55:12 +0000297/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
298/// fold the result. If not, this returns null.
299Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
300 const TargetData *TD) {
301 switch (Opcode) {
302 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD);
303 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD);
304 default:
305 if (Constant *CLHS = dyn_cast<Constant>(LHS))
306 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
307 Constant *COps[] = {CLHS, CRHS};
308 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
309 }
310 return 0;
311 }
312}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000313
314/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
315/// fold the result.
316Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
317 const TargetData *TD) {
318 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
319 return SimplifyICmpInst(Predicate, LHS, RHS, TD);
320 return SimplifyFCmpInst(Predicate, LHS, RHS, TD);
321}
322
Chris Lattnere3453782009-11-10 01:08:51 +0000323
324/// SimplifyInstruction - See if we can compute a simplified version of this
325/// instruction. If not, this returns null.
326Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD) {
327 switch (I->getOpcode()) {
328 default:
329 return ConstantFoldInstruction(I, TD);
330 case Instruction::And:
331 return SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD);
332 case Instruction::Or:
333 return SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD);
334 case Instruction::ICmp:
335 return SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
336 I->getOperand(0), I->getOperand(1), TD);
337 case Instruction::FCmp:
338 return SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
339 I->getOperand(0), I->getOperand(1), TD);
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000340 case Instruction::GetElementPtr: {
341 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
342 return SimplifyGEPInst(&Ops[0], Ops.size(), TD);
343 }
Chris Lattnere3453782009-11-10 01:08:51 +0000344 }
345}
346
Chris Lattner40d8c282009-11-10 22:26:15 +0000347/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
348/// delete the From instruction. In addition to a basic RAUW, this does a
349/// recursive simplification of the newly formed instructions. This catches
350/// things where one simplification exposes other opportunities. This only
351/// simplifies and deletes scalar operations, it does not change the CFG.
352///
353void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
354 const TargetData *TD) {
355 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
356
357 // FromHandle - This keeps a weakvh on the from value so that we can know if
358 // it gets deleted out from under us in a recursive simplification.
359 WeakVH FromHandle(From);
360
361 while (!From->use_empty()) {
362 // Update the instruction to use the new value.
363 Use &U = From->use_begin().getUse();
364 Instruction *User = cast<Instruction>(U.getUser());
365 U = To;
366
367 // See if we can simplify it.
368 if (Value *V = SimplifyInstruction(User, TD)) {
369 // Recursively simplify this.
370 ReplaceAndSimplifyAllUses(User, V, TD);
371
372 // If the recursive simplification ended up revisiting and deleting 'From'
373 // then we're done.
374 if (FromHandle == 0)
375 return;
376 }
377 }
378 From->eraseFromParent();
379}
380