blob: b875420e5beb521ef015ecfc51f3fa07f7db0552 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
49#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
54#include "llvm/Support/InstVisitor.h"
55#include "llvm/Support/MathExtras.h"
56#include "llvm/Support/PatternMatch.h"
57#include "llvm/Support/Compiler.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/SmallPtrSet.h"
62#include "llvm/ADT/Statistic.h"
63#include "llvm/ADT/STLExtras.h"
64#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000065#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066#include <sstream>
67using namespace llvm;
68using namespace llvm::PatternMatch;
69
70STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76namespace {
77 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
80 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000081 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 DenseMap<Instruction*, unsigned> WorklistMap;
83 TargetData *TD;
84 bool MustPreserveLCSSA;
85 public:
86 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000087 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Owen Anderson175b6542009-07-22 00:24:57 +000089 LLVMContext *Context;
90 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +000091
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096 Worklist.push_back(I);
97 }
98
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
103
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
106
107 WorklistMap.erase(It);
108 }
109
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
112 Worklist.pop_back();
113 WorklistMap.erase(I);
114 return I;
115 }
116
117
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
122 void AddUsersToWorkList(Value &I) {
123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
124 UI != UE; ++UI)
125 AddToWorkList(cast<Instruction>(*UI));
126 }
127
128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
130 ///
131 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 AddToWorkList(Op);
135 }
136
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
140 ///
141 /// Return the specified operand before it is turned into an undef.
142 ///
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
145
Gabor Greif17396002008-06-12 21:37:33 +0000146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 AddToWorkList(Op);
149 // Set the operand to undef to drop the use.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000150 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 }
152
153 return R;
154 }
155
156 public:
157 virtual bool runOnFunction(Function &F);
158
159 bool DoOneIteration(Function &F, unsigned ItNum);
160
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 AU.addPreservedID(LCSSAID);
163 AU.setPreservesCFG();
164 }
165
Dan Gohmana80e2712009-07-21 23:21:54 +0000166 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
170 // Return Value:
171 // null - No change was made
172 // I - Change was made, I is still valid, I may be dead though
173 // otherwise - Change was made, replace I with returned instruction
174 //
175 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000176 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000178 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000180 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000198 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *LHS,
212 ConstantInt *RHS);
213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
215
Dan Gohman17f46f72009-07-28 01:40:03 +0000216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 ICmpInst::Predicate Cond, Instruction &I);
218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
219 BinaryOperator &I);
220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
222 Instruction *commonPointerCastTransforms(CastInst &CI);
223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000226 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000232 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000233 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 Instruction *visitBitCast(BitCastInst &CI);
235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
244 Instruction *visitAllocationInst(AllocationInst &AI);
245 Instruction *visitFreeInst(FreeInst &FI);
246 Instruction *visitLoadInst(LoadInst &LI);
247 Instruction *visitStoreInst(StoreInst &SI);
248 Instruction *visitBranchInst(BranchInst &BI);
249 Instruction *visitSwitchInst(SwitchInst &SI);
250 Instruction *visitInsertElementInst(InsertElementInst &IE);
251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254
255 // visitInstruction - Specify what to return for unhandled instructions...
256 Instruction *visitInstruction(Instruction &I) { return 0; }
257
258 private:
259 Instruction *visitCallSite(CallSite CS);
260 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000261 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267
268 public:
269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
271 //
272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
277 AddToWorkList(New);
278 return New;
279 }
280
281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
283 /// cast.
284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285 Instruction &Pos) {
286 if (V->getType() == Ty) return V;
287
288 if (Constant *CV = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000289 return ConstantExpr::getCast(opc, CV, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290
Gabor Greifa645dd32008-05-16 19:29:10 +0000291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 AddToWorkList(C);
293 return C;
294 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000295
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 }
299
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
305 // modified.
306 //
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
308 AddUsersToWorkList(I); // Add all modified instrs to worklist
309 if (&I != V) {
310 I.replaceAllUsesWith(V);
311 return &I;
312 } else {
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 return &I;
317 }
318 }
319
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
327 RemoveFromWorkList(&I);
328 I.eraseFromParent();
329 return 0; // Don't do anything with FI
330 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344
345 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346
347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
349 bool SimplifyCommutative(BinaryOperator &I);
350
351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
354
Chris Lattner676c78e2009-01-31 08:15:18 +0000355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
359 unsigned Depth);
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000362 unsigned Depth=0);
363
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
368
Evan Cheng63295ab2009-02-03 10:05:09 +0000369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
376
377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
387
388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
389 bool isSub, Instruction &I);
390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
391 bool isSigned, bool Inside, Instruction &IB);
392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
393 Instruction *MatchBSwap(BinaryOperator &I);
394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000396 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398
399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000400
Dan Gohman8fd520a2009-06-15 22:12:54 +0000401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000402 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000405
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407}
408
Dan Gohman089efff2008-05-13 00:00:25 +0000409char InstCombiner::ID = 0;
410static RegisterPass<InstCombiner>
411X("instcombine", "Combine redundant instructions");
412
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413// getComplexity: Assign a complexity or rank value to LLVM Values...
414// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson15b39322009-07-13 04:09:18 +0000415static unsigned getComplexity(LLVMContext *Context, Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000419 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 return 3;
421 return 4;
422 }
423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
425}
426
427// isOnlyUse - Return true if this instruction will be deleted if we stop using
428// it.
429static bool isOnlyUse(Value *V) {
430 return V->hasOneUse() || isa<Constant>(V);
431}
432
433// getPromotedType - Return the specified type promoted as it would be to pass
434// though a va_arg area...
435static const Type *getPromotedType(const Type *Ty) {
436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
438 return Type::Int32Ty;
439 }
440 return Ty;
441}
442
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 return 0;
455}
456
457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000466
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
469
470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
473
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000475 DstTy,
476 TD ? TD->getIntPtrType() : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
480 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482 Res = 0;
483
484 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485}
486
487/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488/// in any code being generated. It does not require codegen if V is simple
489/// enough or if the cast can be folded into other casts.
490static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
491 const Type *Ty, TargetData *TD) {
492 if (V->getType() == Ty || isa<Constant>(V)) return false;
493
494 // If this is another cast that can be eliminated, it isn't codegen either.
495 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000496 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 return false;
498 return true;
499}
500
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501// SimplifyCommutative - This performs a few simplifications for commutative
502// operators:
503//
504// 1. Order operands such that they are listed from right (least complex) to
505// left (most complex). This puts constants before unary operators before
506// binary operators.
507//
508// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
510//
511bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
512 bool Changed = false;
Owen Anderson15b39322009-07-13 04:09:18 +0000513 if (getComplexity(Context, I.getOperand(0)) <
514 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 Changed = !I.swapOperands();
516
517 if (!I.isAssociative()) return Changed;
518 Instruction::BinaryOps Opcode = I.getOpcode();
519 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000522 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 cast<Constant>(I.getOperand(1)),
524 cast<Constant>(Op->getOperand(1)));
525 I.setOperand(0, Op->getOperand(0));
526 I.setOperand(1, Folded);
527 return true;
528 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530 isOnlyUse(Op) && isOnlyUse(Op1)) {
531 Constant *C1 = cast<Constant>(Op->getOperand(1));
532 Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000535 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000536 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 Op1->getOperand(0),
538 Op1->getName(), &I);
539 AddToWorkList(New);
540 I.setOperand(0, New);
541 I.setOperand(1, Folded);
542 return true;
543 }
544 }
545 return Changed;
546}
547
548/// SimplifyCompare - For a CmpInst this function just orders the operands
549/// so that theyare listed from right (least complex) to left (most complex).
550/// This puts constants before unary operators before binary operators.
551bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson15b39322009-07-13 04:09:18 +0000552 if (getComplexity(Context, I.getOperand(0)) >=
553 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
562//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000563static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000564 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 return BinaryOperator::getNegArgument(V);
566
567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000569 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000573 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000574
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 return 0;
576}
577
Dan Gohman7ce405e2009-06-04 22:49:04 +0000578// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579// instruction if the LHS is a constant negative zero (which is the 'negate'
580// form).
581//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000582static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000583 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000584 return BinaryOperator::getFNegArgument(V);
585
586 // Constants can be considered to be negated values if they can be folded.
587 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000588 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000592 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000593
594 return 0;
595}
596
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000597static inline Value *dyn_castNotVal(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598 if (BinaryOperator::isNot(V))
599 return BinaryOperator::getNotArgument(V);
600
601 // Constants can be considered to be not'ed values...
602 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000603 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 return 0;
605}
606
607// dyn_castFoldableMul - If this value is a multiply that can be folded into
608// other computations (because it has a constant operand), return the
609// non-constant operand of the multiply, and set CST to point to the multiplier.
610// Otherwise, return null.
611//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000612static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 if (V->hasOneUse() && V->getType()->isInteger())
614 if (Instruction *I = dyn_cast<Instruction>(V)) {
615 if (I->getOpcode() == Instruction::Mul)
616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
617 return I->getOperand(0);
618 if (I->getOpcode() == Instruction::Shl)
619 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
620 // The multiplier is really 1 << CST.
621 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
622 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000623 CST = ConstantInt::get(V->getType()->getContext(),
624 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 return I->getOperand(0);
626 }
627 }
628 return 0;
629}
630
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000632static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000633 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000634 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635}
636/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000637static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000638 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000639 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664
665/// ShrinkDemandedConstant - Check to see if the specified operand of the
666/// specified instruction is a constant integer. If so, check to see if there
667/// are any bits set in the constant that are not demanded. If so, shrink the
668/// constant and return true.
669static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000670 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 assert(I && "No instruction?");
672 assert(OpNo < I->getNumOperands() && "Operand index too large");
673
674 // If the operand is not a constant integer, nothing to do.
675 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
676 if (!OpC) return false;
677
678 // If there are no bits set that aren't demanded, nothing to do.
679 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
680 if ((~Demanded & OpC->getValue()) == 0)
681 return false;
682
683 // This instruction is producing bits that are not demanded. Shrink the RHS.
684 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000685 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 return true;
687}
688
689// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
690// set of known zero and one bits, compute the maximum and minimum values that
691// could have the specified known zero and known one bits, returning them in
692// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000693static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 const APInt& KnownOne,
695 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000696 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
697 KnownZero.getBitWidth() == Min.getBitWidth() &&
698 KnownZero.getBitWidth() == Max.getBitWidth() &&
699 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 APInt UnknownBits = ~(KnownZero|KnownOne);
701
702 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
703 // bit if it is unknown.
704 Min = KnownOne;
705 Max = KnownOne|UnknownBits;
706
Dan Gohman7934d592009-04-25 17:12:48 +0000707 if (UnknownBits.isNegative()) { // Sign bit is unknown
708 Min.set(Min.getBitWidth()-1);
709 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 }
711}
712
713// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
714// a set of known zero and one bits, compute the maximum and minimum values that
715// could have the specified known zero and known one bits, returning them in
716// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000717static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000718 const APInt &KnownOne,
719 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000720 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
721 KnownZero.getBitWidth() == Min.getBitWidth() &&
722 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
724 APInt UnknownBits = ~(KnownZero|KnownOne);
725
726 // The minimum value is when the unknown bits are all zeros.
727 Min = KnownOne;
728 // The maximum value is when the unknown bits are all ones.
729 Max = KnownOne|UnknownBits;
730}
731
Chris Lattner676c78e2009-01-31 08:15:18 +0000732/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
733/// SimplifyDemandedBits knows about. See if the instruction has any
734/// properties that allow us to simplify its operands.
735bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000736 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000737 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
738 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
739
740 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
741 KnownZero, KnownOne, 0);
742 if (V == 0) return false;
743 if (V == &Inst) return true;
744 ReplaceInstUsesWith(Inst, V);
745 return true;
746}
747
748/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
749/// specified instruction operand if possible, updating it in place. It returns
750/// true if it made any change and false otherwise.
751bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
752 APInt &KnownZero, APInt &KnownOne,
753 unsigned Depth) {
754 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
755 KnownZero, KnownOne, Depth);
756 if (NewVal == 0) return false;
757 U.set(NewVal);
758 return true;
759}
760
761
762/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
763/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764/// that only the bits set in DemandedMask of the result of V are ever used
765/// downstream. Consequently, depending on the mask and V, it may be possible
766/// to replace V with a constant or one of its operands. In such cases, this
767/// function does the replacement and returns true. In all other cases, it
768/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000769/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770/// to be zero in the expression. These are provided to potentially allow the
771/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
772/// the expression. KnownOne and KnownZero always follow the invariant that
773/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
774/// the bits in KnownOne and KnownZero may only be accurate for those bits set
775/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
776/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000777///
778/// This returns null if it did not change anything and it permits no
779/// simplification. This returns V itself if it did some simplification of V's
780/// operands based on the information about what bits are demanded. This returns
781/// some other non-null value if it found out that V is equal to another value
782/// in the context where the specified bits are demanded, but not for all users.
783Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
784 APInt &KnownZero, APInt &KnownOne,
785 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 assert(V != 0 && "Null pointer of Value???");
787 assert(Depth <= 6 && "Limit Search Depth");
788 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000789 const Type *VTy = V->getType();
790 assert((TD || !isa<PointerType>(VTy)) &&
791 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000792 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
793 (!VTy->isIntOrIntVector() ||
794 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000795 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000797 "Value *V, DemandedMask, KnownZero and KnownOne "
798 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
800 // We know all of the bits for a constant!
801 KnownOne = CI->getValue() & DemandedMask;
802 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000803 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 }
Dan Gohman7934d592009-04-25 17:12:48 +0000805 if (isa<ConstantPointerNull>(V)) {
806 // We know all of the bits for a constant!
807 KnownOne.clear();
808 KnownZero = DemandedMask;
809 return 0;
810 }
811
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000812 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000814 if (DemandedMask == 0) { // Not demanding any bits from V.
815 if (isa<UndefValue>(V))
816 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000817 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 }
819
Chris Lattner08817332009-01-31 08:24:16 +0000820 if (Depth == 6) // Limit search depth.
821 return 0;
822
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000823 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
824 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
825
Dan Gohman7934d592009-04-25 17:12:48 +0000826 Instruction *I = dyn_cast<Instruction>(V);
827 if (!I) {
828 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
829 return 0; // Only analyze instructions.
830 }
831
Chris Lattner08817332009-01-31 08:24:16 +0000832 // If there are multiple uses of this value and we aren't at the root, then
833 // we can't do any simplifications of the operands, because DemandedMask
834 // only reflects the bits demanded by *one* of the users.
835 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000836 // Despite the fact that we can't simplify this instruction in all User's
837 // context, we can at least compute the knownzero/knownone bits, and we can
838 // do simplifications that apply to *just* the one user if we know that
839 // this instruction has a simpler value in that context.
840 if (I->getOpcode() == Instruction::And) {
841 // If either the LHS or the RHS are Zero, the result is zero.
842 ComputeMaskedBits(I->getOperand(1), DemandedMask,
843 RHSKnownZero, RHSKnownOne, Depth+1);
844 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
845 LHSKnownZero, LHSKnownOne, Depth+1);
846
847 // If all of the demanded bits are known 1 on one side, return the other.
848 // These bits cannot contribute to the result of the 'and' in this
849 // context.
850 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
851 (DemandedMask & ~LHSKnownZero))
852 return I->getOperand(0);
853 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
854 (DemandedMask & ~RHSKnownZero))
855 return I->getOperand(1);
856
857 // If all of the demanded bits in the inputs are known zeros, return zero.
858 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000859 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000860
861 } else if (I->getOpcode() == Instruction::Or) {
862 // We can simplify (X|Y) -> X or Y in the user's context if we know that
863 // only bits from X or Y are demanded.
864
865 // If either the LHS or the RHS are One, the result is One.
866 ComputeMaskedBits(I->getOperand(1), DemandedMask,
867 RHSKnownZero, RHSKnownOne, Depth+1);
868 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
869 LHSKnownZero, LHSKnownOne, Depth+1);
870
871 // If all of the demanded bits are known zero on one side, return the
872 // other. These bits cannot contribute to the result of the 'or' in this
873 // context.
874 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
875 (DemandedMask & ~LHSKnownOne))
876 return I->getOperand(0);
877 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
878 (DemandedMask & ~RHSKnownOne))
879 return I->getOperand(1);
880
881 // If all of the potentially set bits on one side are known to be set on
882 // the other side, just use the 'other' side.
883 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
884 (DemandedMask & (~RHSKnownZero)))
885 return I->getOperand(0);
886 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
887 (DemandedMask & (~LHSKnownZero)))
888 return I->getOperand(1);
889 }
890
Chris Lattner08817332009-01-31 08:24:16 +0000891 // Compute the KnownZero/KnownOne bits to simplify things downstream.
892 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
893 return 0;
894 }
895
896 // If this is the root being simplified, allow it to have multiple uses,
897 // just set the DemandedMask to all bits so that we can try to simplify the
898 // operands. This allows visitTruncInst (for example) to simplify the
899 // operand of a trunc without duplicating all the logic below.
900 if (Depth == 0 && !V->hasOneUse())
901 DemandedMask = APInt::getAllOnesValue(BitWidth);
902
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000904 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000905 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000906 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 case Instruction::And:
908 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000909 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
910 RHSKnownZero, RHSKnownOne, Depth+1) ||
911 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000913 return I;
914 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
915 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916
917 // If all of the demanded bits are known 1 on one side, return the other.
918 // These bits cannot contribute to the result of the 'and'.
919 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
920 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000921 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
923 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000924 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925
926 // If all of the demanded bits in the inputs are known zeros, return zero.
927 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000928 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929
930 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000931 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000932 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933
934 // Output known-1 bits are only known if set in both the LHS & RHS.
935 RHSKnownOne &= LHSKnownOne;
936 // Output known-0 are known to be clear if zero in either the LHS | RHS.
937 RHSKnownZero |= LHSKnownZero;
938 break;
939 case Instruction::Or:
940 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000941 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
942 RHSKnownZero, RHSKnownOne, Depth+1) ||
943 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000945 return I;
946 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
947 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948
949 // If all of the demanded bits are known zero on one side, return the other.
950 // These bits cannot contribute to the result of the 'or'.
951 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
952 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000953 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
955 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000956 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957
958 // If all of the potentially set bits on one side are known to be set on
959 // the other side, just use the 'other' side.
960 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
961 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
964 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
967 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000968 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000969 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970
971 // Output known-0 bits are only known if clear in both the LHS & RHS.
972 RHSKnownZero &= LHSKnownZero;
973 // Output known-1 are known to be set if set in either the LHS | RHS.
974 RHSKnownOne |= LHSKnownOne;
975 break;
976 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000977 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
978 RHSKnownZero, RHSKnownOne, Depth+1) ||
979 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000981 return I;
982 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
983 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000984
985 // If all of the demanded bits are known zero on one side, return the other.
986 // These bits cannot contribute to the result of the 'xor'.
987 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000988 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991
992 // Output known-0 bits are known if clear or set in both the LHS & RHS.
993 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
994 (RHSKnownOne & LHSKnownOne);
995 // Output known-1 are known to be set if set in only one of the LHS, RHS.
996 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
997 (RHSKnownOne & LHSKnownZero);
998
999 // If all of the demanded bits are known to be zero on one side or the
1000 // other, turn this into an *inclusive* or.
1001 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1002 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1003 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001004 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001006 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007 }
1008
1009 // If all of the demanded bits on one side are known, and all of the set
1010 // bits on that side are also known to be set on the other side, turn this
1011 // into an AND, as we know the bits will be cleared.
1012 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1013 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1014 // all known
1015 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001016 Constant *AndC = Constant::getIntegerValue(VTy,
1017 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001019 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001020 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 }
1022 }
1023
1024 // If the RHS is a constant, see if we can simplify it.
1025 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001026 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001027 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028
1029 RHSKnownZero = KnownZeroOut;
1030 RHSKnownOne = KnownOneOut;
1031 break;
1032 }
1033 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001034 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035 RHSKnownZero, RHSKnownOne, Depth+1) ||
1036 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001038 return I;
1039 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1040 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041
1042 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001043 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001045 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046
1047 // Only known if known in both the LHS and RHS.
1048 RHSKnownOne &= LHSKnownOne;
1049 RHSKnownZero &= LHSKnownZero;
1050 break;
1051 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001052 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 DemandedMask.zext(truncBf);
1054 RHSKnownZero.zext(truncBf);
1055 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001058 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 DemandedMask.trunc(BitWidth);
1060 RHSKnownZero.trunc(BitWidth);
1061 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001062 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063 break;
1064 }
1065 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001066 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001067 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001068
1069 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1070 if (const VectorType *SrcVTy =
1071 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1072 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1073 // Don't touch a bitcast between vectors of different element counts.
1074 return false;
1075 } else
1076 // Don't touch a scalar-to-vector bitcast.
1077 return false;
1078 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1079 // Don't touch a vector-to-scalar bitcast.
1080 return false;
1081
Chris Lattner676c78e2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001084 return I;
1085 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 break;
1087 case Instruction::ZExt: {
1088 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001089 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 DemandedMask.trunc(SrcBitWidth);
1092 RHSKnownZero.trunc(SrcBitWidth);
1093 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001094 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001095 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001096 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 DemandedMask.zext(BitWidth);
1098 RHSKnownZero.zext(BitWidth);
1099 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001100 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 // The top bits are known to be zero.
1102 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1103 break;
1104 }
1105 case Instruction::SExt: {
1106 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001107 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108
1109 APInt InputDemandedBits = DemandedMask &
1110 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1111
1112 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1113 // If any of the sign extended bits are demanded, we know that the sign
1114 // bit is demanded.
1115 if ((NewBits & DemandedMask) != 0)
1116 InputDemandedBits.set(SrcBitWidth-1);
1117
1118 InputDemandedBits.trunc(SrcBitWidth);
1119 RHSKnownZero.trunc(SrcBitWidth);
1120 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001121 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001123 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 InputDemandedBits.zext(BitWidth);
1125 RHSKnownZero.zext(BitWidth);
1126 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128
1129 // If the sign bit of the input is known set or clear, then we know the
1130 // top bits of the result.
1131
1132 // If the input sign bit is known zero, or if the NewBits are not demanded
1133 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001134 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001136 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1137 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1139 RHSKnownOne |= NewBits;
1140 }
1141 break;
1142 }
1143 case Instruction::Add: {
1144 // Figure out what the input bits are. If the top bits of the and result
1145 // are not demanded, then the add doesn't demand them from its input
1146 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001147 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148
1149 // If there is a constant on the RHS, there are a variety of xformations
1150 // we can do.
1151 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1152 // If null, this should be simplified elsewhere. Some of the xforms here
1153 // won't work if the RHS is zero.
1154 if (RHS->isZero())
1155 break;
1156
1157 // If the top bit of the output is demanded, demand everything from the
1158 // input. Otherwise, we demand all the input bits except NLZ top bits.
1159 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1160
1161 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001164 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165
1166 // If the RHS of the add has bits set that can't affect the input, reduce
1167 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001168 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001169 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170
1171 // Avoid excess work.
1172 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1173 break;
1174
1175 // Turn it into OR if input bits are zero.
1176 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1177 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001178 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001180 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 }
1182
1183 // We can say something about the output known-zero and known-one bits,
1184 // depending on potential carries from the input constant and the
1185 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1186 // bits set and the RHS constant is 0x01001, then we know we have a known
1187 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1188
1189 // To compute this, we first compute the potential carry bits. These are
1190 // the bits which may be modified. I'm not aware of a better way to do
1191 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001192 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1194
1195 // Now that we know which bits have carries, compute the known-1/0 sets.
1196
1197 // Bits are known one if they are known zero in one operand and one in the
1198 // other, and there is no input carry.
1199 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1200 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1201
1202 // Bits are known zero if they are known zero in both operands and there
1203 // is no input carry.
1204 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1205 } else {
1206 // If the high-bits of this ADD are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
1208 if (DemandedMask[BitWidth-1] == 0) {
1209 // Right fill the mask of bits for this ADD to demand the most
1210 // significant bit and all those below it.
1211 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001212 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1213 LHSKnownZero, LHSKnownOne, Depth+1) ||
1214 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001216 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 }
1218 }
1219 break;
1220 }
1221 case Instruction::Sub:
1222 // If the high-bits of this SUB are not demanded, then it does not demand
1223 // the high bits of its LHS or RHS.
1224 if (DemandedMask[BitWidth-1] == 0) {
1225 // Right fill the mask of bits for this SUB to demand the most
1226 // significant bit and all those below it.
1227 uint32_t NLZ = DemandedMask.countLeadingZeros();
1228 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1230 LHSKnownZero, LHSKnownOne, Depth+1) ||
1231 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001233 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001235 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1236 // the known zeros and ones.
1237 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 break;
1239 case Instruction::Shl:
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1242 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001243 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001245 return I;
1246 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 RHSKnownZero <<= ShiftAmt;
1248 RHSKnownOne <<= ShiftAmt;
1249 // low bits known zero.
1250 if (ShiftAmt)
1251 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1252 }
1253 break;
1254 case Instruction::LShr:
1255 // For a logical shift right
1256 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1258
1259 // Unsigned shift right.
1260 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001261 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001263 return I;
1264 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1266 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1267 if (ShiftAmt) {
1268 // Compute the new bits that are at the top now.
1269 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1270 RHSKnownZero |= HighBits; // high bits known zero.
1271 }
1272 }
1273 break;
1274 case Instruction::AShr:
1275 // If this is an arithmetic shift right and only the low-bit is set, we can
1276 // always convert this into a logical shr, even if the shift amount is
1277 // variable. The low bit of the shift cannot be an input sign bit unless
1278 // the shift amount is >= the size of the datatype, which is undefined.
1279 if (DemandedMask == 1) {
1280 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001281 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001283 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 }
1285
1286 // If the sign bit is the only bit demanded by this ashr, then there is no
1287 // need to do it, the shift doesn't change the high bit.
1288 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001289 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290
1291 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1293
1294 // Signed shift right.
1295 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1296 // If any of the "high bits" are demanded, we should set the sign bit as
1297 // demanded.
1298 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1299 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001300 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001302 return I;
1303 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 // Compute the new bits that are at the top now.
1305 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1306 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1307 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1308
1309 // Handle the sign bits.
1310 APInt SignBit(APInt::getSignBit(BitWidth));
1311 // Adjust to where it is now in the mask.
1312 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1313
1314 // If the input sign bit is known to be zero, or if none of the top bits
1315 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001316 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 (HighBits & ~DemandedMask) == HighBits) {
1318 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001319 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001321 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1323 RHSKnownOne |= HighBits;
1324 }
1325 }
1326 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001327 case Instruction::SRem:
1328 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001329 APInt RA = Rem->getValue().abs();
1330 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001331 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001332 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001333
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001334 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001335 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001337 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001338 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001339
1340 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1341 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001342
1343 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001344
Chris Lattner676c78e2009-01-31 08:15:18 +00001345 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001346 }
1347 }
1348 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001349 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001350 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1351 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001352 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1353 KnownZero2, KnownOne2, Depth+1) ||
1354 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001355 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001356 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001357
Chris Lattneree5417c2009-01-21 18:09:24 +00001358 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001359 Leaders = std::max(Leaders,
1360 KnownZero2.countLeadingOnes());
1361 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001362 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 }
Chris Lattner989ba312008-06-18 04:33:20 +00001364 case Instruction::Call:
1365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1366 switch (II->getIntrinsicID()) {
1367 default: break;
1368 case Intrinsic::bswap: {
1369 // If the only bits demanded come from one byte of the bswap result,
1370 // just shift the input byte into position to eliminate the bswap.
1371 unsigned NLZ = DemandedMask.countLeadingZeros();
1372 unsigned NTZ = DemandedMask.countTrailingZeros();
1373
1374 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1375 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1376 // have 14 leading zeros, round to 8.
1377 NLZ &= ~7;
1378 NTZ &= ~7;
1379 // If we need exactly one byte, we can do this transformation.
1380 if (BitWidth-NLZ-NTZ == 8) {
1381 unsigned ResultBit = NTZ;
1382 unsigned InputBit = BitWidth-NTZ-8;
1383
1384 // Replace this with either a left or right shift to get the byte into
1385 // the right place.
1386 Instruction *NewVal;
1387 if (InputBit > ResultBit)
1388 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001389 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001390 else
1391 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001392 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001393 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001394 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001395 }
1396
1397 // TODO: Could compute known zero/one bits based on the input.
1398 break;
1399 }
1400 }
1401 }
Chris Lattner4946e222008-06-18 18:11:55 +00001402 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001403 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001404 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405
1406 // If the client is only demanding bits that we know, return the known
1407 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001408 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1409 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 return false;
1411}
1412
1413
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001414/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001415/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416/// actually used by the caller. This method analyzes which elements of the
1417/// operand are undef and returns that information in UndefElts.
1418///
1419/// If the information about demanded elements can be used to simplify the
1420/// operation, the operation is simplified, then the resultant value is
1421/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001422Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1423 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 unsigned Depth) {
1425 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001426 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001427 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428
1429 if (isa<UndefValue>(V)) {
1430 // If the entire vector is undefined, just return this info.
1431 UndefElts = EltMask;
1432 return 0;
1433 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1434 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001435 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001437
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 UndefElts = 0;
1439 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1440 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001441 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442
1443 std::vector<Constant*> Elts;
1444 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001445 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001447 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1449 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001450 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 } else { // Otherwise, defined.
1452 Elts.push_back(CP->getOperand(i));
1453 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001454
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001456 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 return NewCP != CP ? NewCP : 0;
1458 } else if (isa<ConstantAggregateZero>(V)) {
1459 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1460 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001461
1462 // Check if this is identity. If so, return 0 since we are not simplifying
1463 // anything.
1464 if (DemandedElts == ((1ULL << VWidth) -1))
1465 return 0;
1466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001468 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001469 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001471 for (unsigned i = 0; i != VWidth; ++i) {
1472 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1473 Elts.push_back(Elt);
1474 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001476 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 }
1478
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001479 // Limit search depth.
1480 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001481 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001482
1483 // If multiple users are using the root value, procede with
1484 // simplification conservatively assuming that all elements
1485 // are needed.
1486 if (!V->hasOneUse()) {
1487 // Quit if we find multiple users of a non-root value though.
1488 // They'll be handled when it's their turn to be visited by
1489 // the main instcombine process.
1490 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001491 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001492 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001493
1494 // Conservatively assume that all elements are needed.
1495 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496 }
1497
1498 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001499 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001500
1501 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001502 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 Value *TmpV;
1504 switch (I->getOpcode()) {
1505 default: break;
1506
1507 case Instruction::InsertElement: {
1508 // If this is a variable index, we don't know which element it overwrites.
1509 // demand exactly the same input as we produce.
1510 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1511 if (Idx == 0) {
1512 // Note that we can't propagate undef elt info, because we don't know
1513 // which elt is getting updated.
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515 UndefElts2, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517 break;
1518 }
1519
1520 // If this is inserting an element that isn't demanded, remove this
1521 // insertelement.
1522 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001523 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 return AddSoonDeadInstToWorklist(*I, 0);
1525
1526 // Otherwise, the element inserted overwrites whatever was there, so the
1527 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001528 APInt DemandedElts2 = DemandedElts;
1529 DemandedElts2.clear(IdxNo);
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531 UndefElts, Depth+1);
1532 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533
1534 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001535 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001536 break;
1537 }
1538 case Instruction::ShuffleVector: {
1539 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001540 uint64_t LHSVWidth =
1541 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001542 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001543 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001544 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001545 unsigned MaskVal = Shuffle->getMaskValue(i);
1546 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001547 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001548 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001549 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001550 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001551 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001552 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001553 }
1554 }
1555 }
1556
Nate Begemanb4d176f2009-02-11 22:36:25 +00001557 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001559 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001560 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
Nate Begemanb4d176f2009-02-11 22:36:25 +00001562 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001563 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1564 UndefElts3, Depth+1);
1565 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1566
1567 bool NewUndefElts = false;
1568 for (unsigned i = 0; i < VWidth; i++) {
1569 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001570 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001571 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001572 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001573 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001574 NewUndefElts = true;
1575 UndefElts.set(i);
1576 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001577 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001578 if (UndefElts3[MaskVal - LHSVWidth]) {
1579 NewUndefElts = true;
1580 UndefElts.set(i);
1581 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001582 }
1583 }
1584
1585 if (NewUndefElts) {
1586 // Add additional discovered undefs.
1587 std::vector<Constant*> Elts;
1588 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001589 if (UndefElts[i])
Owen Andersonb99ecca2009-07-30 23:03:37 +00001590 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001591 else
Owen Andersoneacb44d2009-07-24 23:12:02 +00001592 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001593 Shuffle->getMaskValue(i)));
1594 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001595 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001596 MadeChange = true;
1597 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598 break;
1599 }
1600 case Instruction::BitCast: {
1601 // Vector->vector casts only.
1602 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1603 if (!VTy) break;
1604 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001605 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 unsigned Ratio;
1607
1608 if (VWidth == InVWidth) {
1609 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1610 // elements as are demanded of us.
1611 Ratio = 1;
1612 InputDemandedElts = DemandedElts;
1613 } else if (VWidth > InVWidth) {
1614 // Untested so far.
1615 break;
1616
1617 // If there are more elements in the result than there are in the source,
1618 // then an input element is live if any of the corresponding output
1619 // elements are live.
1620 Ratio = VWidth/InVWidth;
1621 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001622 if (DemandedElts[OutIdx])
1623 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624 }
1625 } else {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the source than there are in the result,
1630 // then an input element is live if the corresponding output element is
1631 // live.
1632 Ratio = InVWidth/VWidth;
1633 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001634 if (DemandedElts[InIdx/Ratio])
1635 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 }
1637
1638 // div/rem demand all inputs, because they don't want divide by zero.
1639 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1640 UndefElts2, Depth+1);
1641 if (TmpV) {
1642 I->setOperand(0, TmpV);
1643 MadeChange = true;
1644 }
1645
1646 UndefElts = UndefElts2;
1647 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001648 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 // If there are more elements in the result than there are in the source,
1650 // then an output element is undef if the corresponding input element is
1651 // undef.
1652 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001653 if (UndefElts2[OutIdx/Ratio])
1654 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001655 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001656 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 // If there are more elements in the source than there are in the result,
1658 // then a result element is undef if all of the corresponding input
1659 // elements are undef.
1660 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001662 if (!UndefElts2[InIdx]) // Not undef?
1663 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001664 }
1665 break;
1666 }
1667 case Instruction::And:
1668 case Instruction::Or:
1669 case Instruction::Xor:
1670 case Instruction::Add:
1671 case Instruction::Sub:
1672 case Instruction::Mul:
1673 // div/rem demand all inputs, because they don't want divide by zero.
1674 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1675 UndefElts, Depth+1);
1676 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1677 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1678 UndefElts2, Depth+1);
1679 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1680
1681 // Output elements are undefined if both are undefined. Consider things
1682 // like undef&0. The result is known zero, not undef.
1683 UndefElts &= UndefElts2;
1684 break;
1685
1686 case Instruction::Call: {
1687 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1688 if (!II) break;
1689 switch (II->getIntrinsicID()) {
1690 default: break;
1691
1692 // Binary vector operations that work column-wise. A dest element is a
1693 // function of the corresponding input elements from the two inputs.
1694 case Intrinsic::x86_sse_sub_ss:
1695 case Intrinsic::x86_sse_mul_ss:
1696 case Intrinsic::x86_sse_min_ss:
1697 case Intrinsic::x86_sse_max_ss:
1698 case Intrinsic::x86_sse2_sub_sd:
1699 case Intrinsic::x86_sse2_mul_sd:
1700 case Intrinsic::x86_sse2_min_sd:
1701 case Intrinsic::x86_sse2_max_sd:
1702 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1708
1709 // If only the low elt is demanded and this is a scalarizable intrinsic,
1710 // scalarize it now.
1711 if (DemandedElts == 1) {
1712 switch (II->getIntrinsicID()) {
1713 default: break;
1714 case Intrinsic::x86_sse_sub_ss:
1715 case Intrinsic::x86_sse_mul_ss:
1716 case Intrinsic::x86_sse2_sub_sd:
1717 case Intrinsic::x86_sse2_mul_sd:
1718 // TODO: Lower MIN/MAX/ABS/etc
1719 Value *LHS = II->getOperand(1);
1720 Value *RHS = II->getOperand(2);
1721 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001722 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001723 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001724 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001725 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726
1727 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001728 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001729 case Intrinsic::x86_sse_sub_ss:
1730 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001731 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001732 II->getName()), *II);
1733 break;
1734 case Intrinsic::x86_sse_mul_ss:
1735 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001736 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737 II->getName()), *II);
1738 break;
1739 }
1740
1741 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001742 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001743 UndefValue::get(II->getType()), TmpV,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001744 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745 InsertNewInstBefore(New, *II);
1746 AddSoonDeadInstToWorklist(*II, 0);
1747 return New;
1748 }
1749 }
1750
1751 // Output elements are undefined if both are undefined. Consider things
1752 // like undef&0. The result is known zero, not undef.
1753 UndefElts &= UndefElts2;
1754 break;
1755 }
1756 break;
1757 }
1758 }
1759 return MadeChange ? I : 0;
1760}
1761
Dan Gohman5d56fd42008-05-19 22:14:15 +00001762
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763/// AssociativeOpt - Perform an optimization on an associative operator. This
1764/// function is designed to check a chain of associative operators for a
1765/// potential to apply a certain optimization. Since the optimization may be
1766/// applicable if the expression was reassociated, this checks the chain, then
1767/// reassociates the expression as necessary to expose the optimization
1768/// opportunity. This makes use of a special Functor, which must define
1769/// 'shouldApply' and 'apply' methods.
1770///
1771template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001772static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 unsigned Opcode = Root.getOpcode();
1774 Value *LHS = Root.getOperand(0);
1775
1776 // Quick check, see if the immediate LHS matches...
1777 if (F.shouldApply(LHS))
1778 return F.apply(Root);
1779
1780 // Otherwise, if the LHS is not of the same opcode as the root, return.
1781 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1782 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1783 // Should we apply this transform to the RHS?
1784 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1785
1786 // If not to the RHS, check to see if we should apply to the LHS...
1787 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1788 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1789 ShouldApply = true;
1790 }
1791
1792 // If the functor wants to apply the optimization to the RHS of LHSI,
1793 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1794 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001795 // Now all of the instructions are in the current basic block, go ahead
1796 // and perform the reassociation.
1797 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1798
1799 // First move the selected RHS to the LHS of the root...
1800 Root.setOperand(0, LHSI->getOperand(1));
1801
1802 // Make what used to be the LHS of the root be the user of the root...
1803 Value *ExtraOperand = TmpLHSI->getOperand(1);
1804 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001805 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806 return 0;
1807 }
1808 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1809 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001811 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812 ARI = Root;
1813
1814 // Now propagate the ExtraOperand down the chain of instructions until we
1815 // get to LHSI.
1816 while (TmpLHSI != LHSI) {
1817 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1818 // Move the instruction to immediately before the chain we are
1819 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001820 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821 ARI = NextLHSI;
1822
1823 Value *NextOp = NextLHSI->getOperand(1);
1824 NextLHSI->setOperand(1, ExtraOperand);
1825 TmpLHSI = NextLHSI;
1826 ExtraOperand = NextOp;
1827 }
1828
1829 // Now that the instructions are reassociated, have the functor perform
1830 // the transformation...
1831 return F.apply(Root);
1832 }
1833
1834 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1835 }
1836 return 0;
1837}
1838
Dan Gohman089efff2008-05-13 00:00:25 +00001839namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840
Nick Lewycky27f6c132008-05-23 04:34:58 +00001841// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842struct AddRHS {
1843 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001844 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001845 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1846 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001847 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001848 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849 }
1850};
1851
1852// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1853// iff C1&C2 == 0
1854struct AddMaskingAnd {
1855 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001856 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857 bool shouldApply(Value *LHS) const {
1858 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001859 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001860 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861 }
1862 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001863 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001864 }
1865};
1866
Dan Gohman089efff2008-05-13 00:00:25 +00001867}
1868
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001869static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1870 InstCombiner *IC) {
Owen Anderson5349f052009-07-06 23:00:19 +00001871 LLVMContext *Context = IC->getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00001872
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001873 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001874 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875 }
1876
1877 // Figure out if the constant is the left or the right argument.
1878 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1879 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1880
1881 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1882 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001883 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1884 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885 }
1886
1887 Value *Op0 = SO, *Op1 = ConstOperand;
1888 if (!ConstIsRHS)
1889 std::swap(Op0, Op1);
1890 Instruction *New;
1891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001892 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001894 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1895 Op0, Op1, SO->getName()+".cmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001897 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898 }
1899 return IC->InsertNewInstBefore(New, I);
1900}
1901
1902// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1903// constant as the other operand, try to fold the binary operator into the
1904// select arguments. This also works for Cast instructions, which obviously do
1905// not have a second operand.
1906static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1907 InstCombiner *IC) {
1908 // Don't modify shared select instructions
1909 if (!SI->hasOneUse()) return 0;
1910 Value *TV = SI->getOperand(1);
1911 Value *FV = SI->getOperand(2);
1912
1913 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1914 // Bool selects with constant operands can be folded to logical ops.
1915 if (SI->getType() == Type::Int1Ty) return 0;
1916
1917 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1918 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1919
Gabor Greifd6da1d02008-04-06 20:25:17 +00001920 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1921 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001922 }
1923 return 0;
1924}
1925
1926
1927/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1928/// node as operand #0, see if we can fold the instruction into the PHI (which
1929/// is only possible if all operands to the PHI are constants).
1930Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1931 PHINode *PN = cast<PHINode>(I.getOperand(0));
1932 unsigned NumPHIValues = PN->getNumIncomingValues();
1933 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1934
1935 // Check to see if all of the operands of the PHI are constants. If there is
1936 // one non-constant value, remember the BB it is. If there is more than one
1937 // or if *it* is a PHI, bail out.
1938 BasicBlock *NonConstBB = 0;
1939 for (unsigned i = 0; i != NumPHIValues; ++i)
1940 if (!isa<Constant>(PN->getIncomingValue(i))) {
1941 if (NonConstBB) return 0; // More than one non-const value.
1942 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1943 NonConstBB = PN->getIncomingBlock(i);
1944
1945 // If the incoming non-constant value is in I's block, we have an infinite
1946 // loop.
1947 if (NonConstBB == I.getParent())
1948 return 0;
1949 }
1950
1951 // If there is exactly one non-constant value, we can insert a copy of the
1952 // operation in that block. However, if this is a critical edge, we would be
1953 // inserting the computation one some other paths (e.g. inside a loop). Only
1954 // do this if the pred block is unconditionally branching into the phi block.
1955 if (NonConstBB) {
1956 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1957 if (!BI || !BI->isUnconditional()) return 0;
1958 }
1959
1960 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001961 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001962 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1963 InsertNewInstBefore(NewPN, *PN);
1964 NewPN->takeName(PN);
1965
1966 // Next, add all of the operands to the PHI.
1967 if (I.getNumOperands() == 2) {
1968 Constant *C = cast<Constant>(I.getOperand(1));
1969 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001970 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001971 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1972 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00001973 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974 else
Owen Anderson02b48c32009-07-29 18:55:55 +00001975 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 } else {
1977 assert(PN->getIncomingBlock(i) == NonConstBB);
1978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001979 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980 PN->getIncomingValue(i), C, "phitmp",
1981 NonConstBB->getTerminator());
1982 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001983 InV = CmpInst::Create(*Context, CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 CI->getPredicate(),
1985 PN->getIncomingValue(i), C, "phitmp",
1986 NonConstBB->getTerminator());
1987 else
Edwin Törökbd448e32009-07-14 16:55:14 +00001988 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989
1990 AddToWorkList(cast<Instruction>(InV));
1991 }
1992 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1993 }
1994 } else {
1995 CastInst *CI = cast<CastInst>(&I);
1996 const Type *RetTy = CI->getType();
1997 for (unsigned i = 0; i != NumPHIValues; ++i) {
1998 Value *InV;
1999 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002000 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001 } else {
2002 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002003 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004 I.getType(), "phitmp",
2005 NonConstBB->getTerminator());
2006 AddToWorkList(cast<Instruction>(InV));
2007 }
2008 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2009 }
2010 }
2011 return ReplaceInstUsesWith(I, NewPN);
2012}
2013
Chris Lattner55476162008-01-29 06:52:45 +00002014
Chris Lattner3554f972008-05-20 05:46:13 +00002015/// WillNotOverflowSignedAdd - Return true if we can prove that:
2016/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2017/// This basically requires proving that the add in the original type would not
2018/// overflow to change the sign bit or have a carry out.
2019bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2020 // There are different heuristics we can use for this. Here are some simple
2021 // ones.
2022
2023 // Add has the property that adding any two 2's complement numbers can only
2024 // have one carry bit which can change a sign. As such, if LHS and RHS each
2025 // have at least two sign bits, we know that the addition of the two values will
2026 // sign extend fine.
2027 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2028 return true;
2029
2030
2031 // If one of the operands only has one non-zero bit, and if the other operand
2032 // has a known-zero bit in a more significant place than it (not including the
2033 // sign bit) the ripple may go up to and fill the zero, but won't change the
2034 // sign. For example, (X & ~4) + 1.
2035
2036 // TODO: Implement.
2037
2038 return false;
2039}
2040
Chris Lattner55476162008-01-29 06:52:45 +00002041
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2043 bool Changed = SimplifyCommutative(I);
2044 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2045
2046 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2047 // X + undef -> undef
2048 if (isa<UndefValue>(RHS))
2049 return ReplaceInstUsesWith(I, RHS);
2050
2051 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002052 if (RHSC->isNullValue())
2053 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002054
2055 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2056 // X + (signbit) --> X ^ signbit
2057 const APInt& Val = CI->getValue();
2058 uint32_t BitWidth = Val.getBitWidth();
2059 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002060 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061
2062 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2063 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002064 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002065 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002066
Eli Friedmana21526d2009-07-13 22:27:52 +00002067 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002068 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedmana21526d2009-07-13 22:27:52 +00002069 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002070 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002071 }
2072
2073 if (isa<PHINode>(LHS))
2074 if (Instruction *NV = FoldOpIntoPhi(I))
2075 return NV;
2076
2077 ConstantInt *XorRHS = 0;
2078 Value *XorLHS = 0;
2079 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002080 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002081 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2083
2084 uint32_t Size = TySizeBits / 2;
2085 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2086 APInt CFF80Val(-C0080Val);
2087 do {
2088 if (TySizeBits > Size) {
2089 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2090 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2091 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2092 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2093 // This is a sign extend if the top bits are known zero.
2094 if (!MaskedValueIsZero(XorLHS,
2095 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2096 Size = 0; // Not a sign ext, but can't be any others either.
2097 break;
2098 }
2099 }
2100 Size >>= 1;
2101 C0080Val = APIntOps::lshr(C0080Val, Size);
2102 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2103 } while (Size >= 1);
2104
2105 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002106 // with funny bit widths then this switch statement should be removed. It
2107 // is just here to get the size of the "middle" type back up to something
2108 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002109 const Type *MiddleType = 0;
2110 switch (Size) {
2111 default: break;
2112 case 32: MiddleType = Type::Int32Ty; break;
2113 case 16: MiddleType = Type::Int16Ty; break;
2114 case 8: MiddleType = Type::Int8Ty; break;
2115 }
2116 if (MiddleType) {
2117 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2118 InsertNewInstBefore(NewTrunc, I);
2119 return new SExtInst(NewTrunc, I.getType(), I.getName());
2120 }
2121 }
2122 }
2123
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002124 if (I.getType() == Type::Int1Ty)
2125 return BinaryOperator::CreateXor(LHS, RHS);
2126
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002127 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002128 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002129 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002130 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002131
2132 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2133 if (RHSI->getOpcode() == Instruction::Sub)
2134 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2135 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2136 }
2137 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2138 if (LHSI->getOpcode() == Instruction::Sub)
2139 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2140 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2141 }
2142 }
2143
2144 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002145 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002146 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002147 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002148 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002149 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002150 InsertNewInstBefore(NewAdd, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00002151 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002152 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002153 }
2154
Gabor Greifa645dd32008-05-16 19:29:10 +00002155 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002156 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157
2158 // A + -B --> A - B
2159 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002160 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162
2163
2164 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002165 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002167 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168
2169 // X*C1 + X*C2 --> X * (C1+C2)
2170 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002171 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002172 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002173 }
2174
2175 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002176 if (dyn_castFoldableMul(RHS, C2) == LHS)
2177 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178
2179 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002180 if (dyn_castNotVal(LHS) == RHS ||
2181 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002182 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183
2184
2185 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002186 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2187 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002189
2190 // A+B --> A|B iff A and B have no bits set in common.
2191 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2192 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2193 APInt LHSKnownOne(IT->getBitWidth(), 0);
2194 APInt LHSKnownZero(IT->getBitWidth(), 0);
2195 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2196 if (LHSKnownZero != 0) {
2197 APInt RHSKnownOne(IT->getBitWidth(), 0);
2198 APInt RHSKnownZero(IT->getBitWidth(), 0);
2199 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2200
2201 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002202 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002203 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002204 }
2205 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002206
Nick Lewycky83598a72008-02-03 07:42:09 +00002207 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002208 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002209 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002210 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2211 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002212 if (W != Y) {
2213 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002214 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002215 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002216 std::swap(W, X);
2217 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002218 std::swap(Y, Z);
2219 std::swap(W, X);
2220 }
2221 }
2222
2223 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002224 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002225 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002226 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002227 }
2228 }
2229 }
2230
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002231 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2232 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002233 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002234 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235
2236 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002237 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002238 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002239 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002240 if (Anded == CRHS) {
2241 // See if all bits from the first bit set in the Add RHS up are included
2242 // in the mask. First, get the rightmost bit.
2243 const APInt& AddRHSV = CRHS->getValue();
2244
2245 // Form a mask of all bits from the lowest bit added through the top.
2246 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2247
2248 // See if the and mask includes all of these bits.
2249 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2250
2251 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2252 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002253 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002254 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002255 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 }
2257 }
2258 }
2259
2260 // Try to fold constant add into select arguments.
2261 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2262 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2263 return R;
2264 }
2265
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002266 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002267 {
2268 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002269 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002270 if (!SI) {
2271 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002272 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002273 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002274 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002275 Value *TV = SI->getTrueValue();
2276 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002277 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002278
2279 // Can we fold the add into the argument of the select?
2280 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002281 if (match(FV, m_Zero()) &&
2282 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002283 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002284 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002285 if (match(TV, m_Zero()) &&
2286 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002287 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002288 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002289 }
2290 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291
Chris Lattner3554f972008-05-20 05:46:13 +00002292 // Check for (add (sext x), y), see if we can merge this into an
2293 // integer add followed by a sext.
2294 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2295 // (add (sext x), cst) --> (sext (add x, cst'))
2296 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2297 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002298 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002299 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002300 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002301 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2302 // Insert the new, smaller add.
2303 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2304 CI, "addconv");
2305 InsertNewInstBefore(NewAdd, I);
2306 return new SExtInst(NewAdd, I.getType());
2307 }
2308 }
2309
2310 // (add (sext x), (sext y)) --> (sext (add int x, y))
2311 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2312 // Only do this if x/y have the same type, if at last one of them has a
2313 // single use (so we don't increase the number of sexts), and if the
2314 // integer add will not overflow.
2315 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2316 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2317 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2318 RHSConv->getOperand(0))) {
2319 // Insert the new integer add.
2320 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2321 RHSConv->getOperand(0),
2322 "addconv");
2323 InsertNewInstBefore(NewAdd, I);
2324 return new SExtInst(NewAdd, I.getType());
2325 }
2326 }
2327 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002328
2329 return Changed ? &I : 0;
2330}
2331
2332Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2333 bool Changed = SimplifyCommutative(I);
2334 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2335
2336 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2337 // X + 0 --> X
2338 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002339 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002340 (I.getType())->getValueAPF()))
2341 return ReplaceInstUsesWith(I, LHS);
2342 }
2343
2344 if (isa<PHINode>(LHS))
2345 if (Instruction *NV = FoldOpIntoPhi(I))
2346 return NV;
2347 }
2348
2349 // -A + B --> B - A
2350 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002351 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002352 return BinaryOperator::CreateFSub(RHS, LHSV);
2353
2354 // A + -B --> A - B
2355 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002356 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002357 return BinaryOperator::CreateFSub(LHS, V);
2358
2359 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2360 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2361 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2362 return ReplaceInstUsesWith(I, LHS);
2363
Chris Lattner3554f972008-05-20 05:46:13 +00002364 // Check for (add double (sitofp x), y), see if we can merge this into an
2365 // integer add followed by a promotion.
2366 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2367 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2368 // ... if the constant fits in the integer value. This is useful for things
2369 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2370 // requires a constant pool load, and generally allows the add to be better
2371 // instcombined.
2372 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2373 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002374 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002375 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002376 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002377 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2378 // Insert the new integer add.
2379 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2380 CI, "addconv");
2381 InsertNewInstBefore(NewAdd, I);
2382 return new SIToFPInst(NewAdd, I.getType());
2383 }
2384 }
2385
2386 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2387 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2388 // Only do this if x/y have the same type, if at last one of them has a
2389 // single use (so we don't increase the number of int->fp conversions),
2390 // and if the integer add will not overflow.
2391 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2392 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2393 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2394 RHSConv->getOperand(0))) {
2395 // Insert the new integer add.
2396 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2397 RHSConv->getOperand(0),
2398 "addconv");
2399 InsertNewInstBefore(NewAdd, I);
2400 return new SIToFPInst(NewAdd, I.getType());
2401 }
2402 }
2403 }
2404
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002405 return Changed ? &I : 0;
2406}
2407
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002408Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2410
Dan Gohman7ce405e2009-06-04 22:49:04 +00002411 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002412 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002413
2414 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002415 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002416 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417
2418 if (isa<UndefValue>(Op0))
2419 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2420 if (isa<UndefValue>(Op1))
2421 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2422
2423 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424 // Replace (-1 - A) with (~A)...
2425 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002426 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427
2428 // C - ~X == X + (1+C)
2429 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002430 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002431 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432
2433 // -(X >>u 31) -> (X >>s 31)
2434 // -(X >>s 31) -> (X >>u 31)
2435 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002436 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002437 if (SI->getOpcode() == Instruction::LShr) {
2438 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2439 // Check to see if we are shifting out everything but the sign bit.
2440 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2441 SI->getType()->getPrimitiveSizeInBits()-1) {
2442 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002443 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444 SI->getOperand(0), CU, SI->getName());
2445 }
2446 }
2447 }
2448 else if (SI->getOpcode() == Instruction::AShr) {
2449 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450 // Check to see if we are shifting out everything but the sign bit.
2451 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452 SI->getType()->getPrimitiveSizeInBits()-1) {
2453 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455 SI->getOperand(0), CU, SI->getName());
2456 }
2457 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002458 }
2459 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460 }
2461
2462 // Try to fold constant sub into select arguments.
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2465 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002466
2467 // C - zext(bool) -> bool ? C - 1 : C
2468 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2469 if (ZI->getSrcTy() == Type::Int1Ty)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002470 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002471 }
2472
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002473 if (I.getType() == Type::Int1Ty)
2474 return BinaryOperator::CreateXor(Op0, Op1);
2475
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002476 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002477 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002479 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002480 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002481 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002482 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002483 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002487 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002488 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489 }
2490 }
2491
2492 if (Op1I->hasOneUse()) {
2493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2495 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002496 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002497 // Swap the two operands of the subexpr...
2498 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2499 Op1I->setOperand(0, IIOp1);
2500 Op1I->setOperand(1, IIOp0);
2501
2502 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002503 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 }
2505
2506 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2507 //
2508 if (Op1I->getOpcode() == Instruction::And &&
2509 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2510 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2511
2512 Value *NewNot =
Dan Gohmancdff2122009-08-12 16:23:25 +00002513 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 }
2516
2517 // 0 - (X sdiv C) -> (X sdiv -C)
2518 if (Op1I->getOpcode() == Instruction::SDiv)
2519 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2520 if (CSI->isZero())
2521 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002522 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002523 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524
2525 // X - X*C --> X * (1-C)
2526 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002527 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002528 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002529 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002530 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002531 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002532 }
2533 }
2534 }
2535
Dan Gohman7ce405e2009-06-04 22:49:04 +00002536 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2537 if (Op0I->getOpcode() == Instruction::Add) {
2538 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2539 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2540 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2541 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2542 } else if (Op0I->getOpcode() == Instruction::Sub) {
2543 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002544 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002545 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002546 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002547 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548
2549 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002550 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002551 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002552 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553
2554 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002555 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002556 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002557 }
2558 return 0;
2559}
2560
Dan Gohman7ce405e2009-06-04 22:49:04 +00002561Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2562 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2563
2564 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002565 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002566 return BinaryOperator::CreateFAdd(Op0, V);
2567
2568 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2569 if (Op1I->getOpcode() == Instruction::FAdd) {
2570 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002571 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002572 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002573 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002574 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002575 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002576 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002577 }
2578
2579 return 0;
2580}
2581
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002582/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2583/// comparison only checks the sign bit. If it only checks the sign bit, set
2584/// TrueIfSigned if the result of the comparison is true when the input value is
2585/// signed.
2586static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2587 bool &TrueIfSigned) {
2588 switch (pred) {
2589 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2590 TrueIfSigned = true;
2591 return RHS->isZero();
2592 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2593 TrueIfSigned = true;
2594 return RHS->isAllOnesValue();
2595 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2596 TrueIfSigned = false;
2597 return RHS->isAllOnesValue();
2598 case ICmpInst::ICMP_UGT:
2599 // True if LHS u> RHS and RHS == high-bit-mask - 1
2600 TrueIfSigned = true;
2601 return RHS->getValue() ==
2602 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2603 case ICmpInst::ICMP_UGE:
2604 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2605 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002606 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002607 default:
2608 return false;
2609 }
2610}
2611
2612Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2613 bool Changed = SimplifyCommutative(I);
2614 Value *Op0 = I.getOperand(0);
2615
Eli Friedmane426ded2009-07-18 09:12:15 +00002616 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002617 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002618
2619 // Simplify mul instructions with a constant RHS...
2620 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2621 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2622
2623 // ((X << C1)*C2) == (X * (C2 << C1))
2624 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2625 if (SI->getOpcode() == Instruction::Shl)
2626 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002627 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002628 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002629
2630 if (CI->isZero())
2631 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2632 if (CI->equalsInt(1)) // X * 1 == X
2633 return ReplaceInstUsesWith(I, Op0);
2634 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002635 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002636
2637 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2638 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002639 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002640 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002641 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002642 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002643 if (Op1->isNullValue())
2644 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002645
2646 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2647 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002648 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002649
2650 // As above, vector X*splat(1.0) -> X in all defined cases.
2651 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002652 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2653 if (CI->equalsInt(1))
2654 return ReplaceInstUsesWith(I, Op0);
2655 }
2656 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002657 }
2658
2659 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2660 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002661 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002662 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002663 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 Op1, "tmp");
2665 InsertNewInstBefore(Add, I);
Owen Anderson02b48c32009-07-29 18:55:55 +00002666 Value *C1C2 = ConstantExpr::getMul(Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
2670 }
2671
2672 // Try to fold constant mul into select arguments.
2673 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2674 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2675 return R;
2676
2677 if (isa<PHINode>(Op0))
2678 if (Instruction *NV = FoldOpIntoPhi(I))
2679 return NV;
2680 }
2681
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002682 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2683 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002685
Nick Lewycky1c246402008-11-21 07:33:58 +00002686 // (X / Y) * Y = X - (X % Y)
2687 // (X / Y) * -Y = (X % Y) - X
2688 {
2689 Value *Op1 = I.getOperand(1);
2690 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2691 if (!BO ||
2692 (BO->getOpcode() != Instruction::UDiv &&
2693 BO->getOpcode() != Instruction::SDiv)) {
2694 Op1 = Op0;
2695 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2696 }
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002697 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002698 if (BO && BO->hasOneUse() &&
2699 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2700 (BO->getOpcode() == Instruction::UDiv ||
2701 BO->getOpcode() == Instruction::SDiv)) {
2702 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2703
Dan Gohman07878902009-08-12 16:33:09 +00002704 // If the division is exact, X % Y is zero.
2705 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2706 if (SDiv->isExact()) {
2707 if (Op1BO == Op1)
2708 return ReplaceInstUsesWith(I, Op0BO);
2709 else
2710 return BinaryOperator::CreateNeg(Op0BO);
2711 }
2712
Nick Lewycky1c246402008-11-21 07:33:58 +00002713 Instruction *Rem;
2714 if (BO->getOpcode() == Instruction::UDiv)
2715 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2716 else
2717 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2718
2719 InsertNewInstBefore(Rem, I);
2720 Rem->takeName(BO);
2721
2722 if (Op1BO == Op1)
2723 return BinaryOperator::CreateSub(Op0BO, Rem);
2724 else
2725 return BinaryOperator::CreateSub(Rem, Op0BO);
2726 }
2727 }
2728
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002729 if (I.getType() == Type::Int1Ty)
2730 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2731
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732 // If one of the operands of the multiply is a cast from a boolean value, then
2733 // we know the bool is either zero or one, so this is a 'masking' multiply.
2734 // See if we can simplify things based on how the boolean was originally
2735 // formed.
2736 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002737 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002738 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2739 BoolCast = CI;
2740 if (!BoolCast)
2741 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2742 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2743 BoolCast = CI;
2744 if (BoolCast) {
2745 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2746 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2747 const Type *SCOpTy = SCIOp0->getType();
2748 bool TIS = false;
2749
2750 // If the icmp is true iff the sign bit of X is set, then convert this
2751 // multiply into a shift/and combination.
2752 if (isa<ConstantInt>(SCIOp1) &&
2753 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2754 TIS) {
2755 // Shift the X value right to turn it into "all signbits".
Owen Andersoneacb44d2009-07-24 23:12:02 +00002756 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002757 SCOpTy->getPrimitiveSizeInBits()-1);
2758 Value *V =
2759 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002760 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 BoolCast->getOperand(0)->getName()+
2762 ".mask"), I);
2763
2764 // If the multiply type is not the same as the source type, sign extend
2765 // or truncate to the multiply type.
2766 if (I.getType() != V->getType()) {
2767 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2768 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2769 Instruction::CastOps opcode =
2770 (SrcBits == DstBits ? Instruction::BitCast :
2771 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2772 V = InsertCastBefore(opcode, V, I.getType(), I);
2773 }
2774
2775 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002776 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 }
2778 }
2779 }
2780
2781 return Changed ? &I : 0;
2782}
2783
Dan Gohman7ce405e2009-06-04 22:49:04 +00002784Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2785 bool Changed = SimplifyCommutative(I);
2786 Value *Op0 = I.getOperand(0);
2787
2788 // Simplify mul instructions with a constant RHS...
2789 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2790 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2791 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2792 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2793 if (Op1F->isExactlyValue(1.0))
2794 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2795 } else if (isa<VectorType>(Op1->getType())) {
2796 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2797 // As above, vector X*splat(1.0) -> X in all defined cases.
2798 if (Constant *Splat = Op1V->getSplatValue()) {
2799 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2800 if (F->isExactlyValue(1.0))
2801 return ReplaceInstUsesWith(I, Op0);
2802 }
2803 }
2804 }
2805
2806 // Try to fold constant mul into select arguments.
2807 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2808 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2809 return R;
2810
2811 if (isa<PHINode>(Op0))
2812 if (Instruction *NV = FoldOpIntoPhi(I))
2813 return NV;
2814 }
2815
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002816 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2817 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002818 return BinaryOperator::CreateFMul(Op0v, Op1v);
2819
2820 return Changed ? &I : 0;
2821}
2822
Chris Lattner76972db2008-07-14 00:15:52 +00002823/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2824/// instruction.
2825bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2826 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2827
2828 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2829 int NonNullOperand = -1;
2830 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2831 if (ST->isNullValue())
2832 NonNullOperand = 2;
2833 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2834 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2835 if (ST->isNullValue())
2836 NonNullOperand = 1;
2837
2838 if (NonNullOperand == -1)
2839 return false;
2840
2841 Value *SelectCond = SI->getOperand(0);
2842
2843 // Change the div/rem to use 'Y' instead of the select.
2844 I.setOperand(1, SI->getOperand(NonNullOperand));
2845
2846 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2847 // problem. However, the select, or the condition of the select may have
2848 // multiple uses. Based on our knowledge that the operand must be non-zero,
2849 // propagate the known value for the select into other uses of it, and
2850 // propagate a known value of the condition into its other users.
2851
2852 // If the select and condition only have a single use, don't bother with this,
2853 // early exit.
2854 if (SI->use_empty() && SelectCond->hasOneUse())
2855 return true;
2856
2857 // Scan the current block backward, looking for other uses of SI.
2858 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2859
2860 while (BBI != BBFront) {
2861 --BBI;
2862 // If we found a call to a function, we can't assume it will return, so
2863 // information from below it cannot be propagated above it.
2864 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2865 break;
2866
2867 // Replace uses of the select or its condition with the known values.
2868 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2869 I != E; ++I) {
2870 if (*I == SI) {
2871 *I = SI->getOperand(NonNullOperand);
2872 AddToWorkList(BBI);
2873 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002874 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2875 ConstantInt::getFalse(*Context);
Chris Lattner76972db2008-07-14 00:15:52 +00002876 AddToWorkList(BBI);
2877 }
2878 }
2879
2880 // If we past the instruction, quit looking for it.
2881 if (&*BBI == SI)
2882 SI = 0;
2883 if (&*BBI == SelectCond)
2884 SelectCond = 0;
2885
2886 // If we ran out of things to eliminate, break out of the loop.
2887 if (SelectCond == 0 && SI == 0)
2888 break;
2889
2890 }
2891 return true;
2892}
2893
2894
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895/// This function implements the transforms on div instructions that work
2896/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2897/// used by the visitors to those instructions.
2898/// @brief Transforms common to all three div instructions
2899Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2900 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2901
Chris Lattner653ef3c2008-02-19 06:12:18 +00002902 // undef / X -> 0 for integer.
2903 // undef / X -> undef for FP (the undef could be a snan).
2904 if (isa<UndefValue>(Op0)) {
2905 if (Op0->getType()->isFPOrFPVector())
2906 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002907 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002908 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002909
2910 // X / undef -> undef
2911 if (isa<UndefValue>(Op1))
2912 return ReplaceInstUsesWith(I, Op1);
2913
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002914 return 0;
2915}
2916
2917/// This function implements the transforms common to both integer division
2918/// instructions (udiv and sdiv). It is called by the visitors to those integer
2919/// division instructions.
2920/// @brief Common integer divide transforms
2921Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2922 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2923
Chris Lattnercefb36c2008-05-16 02:59:42 +00002924 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002925 if (Op0 == Op1) {
2926 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002927 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002928 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002929 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002930 }
2931
Owen Andersoneacb44d2009-07-24 23:12:02 +00002932 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002933 return ReplaceInstUsesWith(I, CI);
2934 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002935
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002936 if (Instruction *Common = commonDivTransforms(I))
2937 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002938
2939 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2940 // This does not apply for fdiv.
2941 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2942 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943
2944 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2945 // div X, 1 == X
2946 if (RHS->equalsInt(1))
2947 return ReplaceInstUsesWith(I, Op0);
2948
2949 // (X / C1) / C2 -> X / (C1*C2)
2950 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2951 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2952 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002953 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002954 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00002955 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002956 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002957 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002958 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002959 }
2960
2961 if (!RHS->isZero()) { // avoid X udiv 0
2962 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2963 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2964 return R;
2965 if (isa<PHINode>(Op0))
2966 if (Instruction *NV = FoldOpIntoPhi(I))
2967 return NV;
2968 }
2969 }
2970
2971 // 0 / X == 0, we don't need to preserve faults!
2972 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2973 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00002974 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002975
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002976 // It can't be division by zero, hence it must be division by one.
2977 if (I.getType() == Type::Int1Ty)
2978 return ReplaceInstUsesWith(I, Op0);
2979
Nick Lewycky94418732008-11-27 20:21:08 +00002980 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2981 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2982 // div X, 1 == X
2983 if (X->isOne())
2984 return ReplaceInstUsesWith(I, Op0);
2985 }
2986
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002987 return 0;
2988}
2989
2990Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2992
2993 // Handle the integer div common cases
2994 if (Instruction *Common = commonIDivTransforms(I))
2995 return Common;
2996
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002997 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00002998 // X udiv C^2 -> X >> C
2999 // Check to see if this is an unsigned division with an exact power of 2,
3000 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003001 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003002 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003003 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003004
3005 // X udiv C, where C >= signbit
3006 if (C->getValue().isNegative()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00003007 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3008 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky240182a2008-11-27 22:41:10 +00003009 I);
Owen Andersonaac28372009-07-31 20:28:14 +00003010 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003011 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003012 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 }
3014
3015 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3016 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3017 if (RHSI->getOpcode() == Instruction::Shl &&
3018 isa<ConstantInt>(RHSI->getOperand(0))) {
3019 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3020 if (C1.isPowerOf2()) {
3021 Value *N = RHSI->getOperand(1);
3022 const Type *NTy = N->getType();
3023 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003024 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003025 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003026 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003027 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028 }
3029 }
3030 }
3031
3032 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3033 // where C1&C2 are powers of two.
3034 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3035 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3036 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3037 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3038 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3039 // Compute the shift amounts
3040 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3041 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003042 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003043 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003044 Op0, TC, SI->getName()+".t");
3045 TSI = InsertNewInstBefore(TSI, I);
3046
3047 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003048 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003049 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003050 Op0, FC, SI->getName()+".f");
3051 FSI = InsertNewInstBefore(FSI, I);
3052
3053 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003054 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003055 }
3056 }
3057 return 0;
3058}
3059
3060Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3061 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3062
3063 // Handle the integer div common cases
3064 if (Instruction *Common = commonIDivTransforms(I))
3065 return Common;
3066
3067 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3068 // sdiv X, -1 == -X
3069 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003070 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003071
Dan Gohman07878902009-08-12 16:33:09 +00003072 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003073 if (cast<SDivOperator>(&I)->isExact() &&
3074 RHS->getValue().isNonNegative() &&
3075 RHS->getValue().isPowerOf2()) {
3076 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3077 RHS->getValue().exactLogBase2());
3078 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3079 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003080
3081 // -X/C --> X/-C provided the negation doesn't overflow.
3082 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3083 if (isa<Constant>(Sub->getOperand(0)) &&
3084 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3085 Sub->hasNoSignedOverflow())
3086 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3087 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088 }
3089
3090 // If the sign bits of both operands are zero (i.e. we can prove they are
3091 // unsigned inputs), turn this into a udiv.
3092 if (I.getType()->isInteger()) {
3093 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003094 if (MaskedValueIsZero(Op0, Mask)) {
3095 if (MaskedValueIsZero(Op1, Mask)) {
3096 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3097 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3098 }
3099 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003100 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003101 ShiftedInt->getValue().isPowerOf2()) {
3102 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3103 // Safe because the only negative value (1 << Y) can take on is
3104 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3105 // the sign bit set.
3106 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3107 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003109 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003110
3111 return 0;
3112}
3113
3114Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3115 return commonDivTransforms(I);
3116}
3117
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118/// This function implements the transforms on rem instructions that work
3119/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3120/// is used by the visitors to those instructions.
3121/// @brief Transforms common to all three rem instructions
3122Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3123 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3124
Chris Lattner653ef3c2008-02-19 06:12:18 +00003125 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3126 if (I.getType()->isFPOrFPVector())
3127 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003128 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003129 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003130 if (isa<UndefValue>(Op1))
3131 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3132
3133 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003134 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3135 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136
3137 return 0;
3138}
3139
3140/// This function implements the transforms common to both integer remainder
3141/// instructions (urem and srem). It is called by the visitors to those integer
3142/// remainder instructions.
3143/// @brief Common integer remainder transforms
3144Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3146
3147 if (Instruction *common = commonRemTransforms(I))
3148 return common;
3149
Dale Johannesena51f7372009-01-21 00:35:19 +00003150 // 0 % X == 0 for integer, we don't need to preserve faults!
3151 if (Constant *LHS = dyn_cast<Constant>(Op0))
3152 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003153 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3156 // X % 0 == undef, we don't need to preserve faults!
3157 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003158 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159
3160 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003161 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162
3163 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3164 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3165 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3166 return R;
3167 } else if (isa<PHINode>(Op0I)) {
3168 if (Instruction *NV = FoldOpIntoPhi(I))
3169 return NV;
3170 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003171
3172 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003173 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003174 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175 }
3176 }
3177
3178 return 0;
3179}
3180
3181Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3182 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3183
3184 if (Instruction *common = commonIRemTransforms(I))
3185 return common;
3186
3187 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3188 // X urem C^2 -> X and C
3189 // Check to see if this is an unsigned remainder with an exact power of 2,
3190 // if so, convert to a bitwise and.
3191 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3192 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003193 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003194 }
3195
3196 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3197 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3198 if (RHSI->getOpcode() == Instruction::Shl &&
3199 isa<ConstantInt>(RHSI->getOperand(0))) {
3200 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003201 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003202 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003204 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 }
3206 }
3207 }
3208
3209 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3210 // where C1&C2 are powers of two.
3211 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3212 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3213 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3214 // STO == 0 and SFO == 0 handled above.
3215 if ((STO->getValue().isPowerOf2()) &&
3216 (SFO->getValue().isPowerOf2())) {
3217 Value *TrueAnd = InsertNewInstBefore(
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003218 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Anderson24be4c12009-07-03 00:17:18 +00003219 SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 Value *FalseAnd = InsertNewInstBefore(
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003221 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Anderson24be4c12009-07-03 00:17:18 +00003222 SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003223 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 }
3225 }
3226 }
3227
3228 return 0;
3229}
3230
3231Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3232 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3233
Dan Gohmandb3dd962007-11-05 23:16:33 +00003234 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003235 if (Instruction *common = commonIRemTransforms(I))
3236 return common;
3237
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003238 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003239 if (!isa<Constant>(RHSNeg) ||
3240 (isa<ConstantInt>(RHSNeg) &&
3241 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242 // X % -Y -> X % Y
3243 AddUsesToWorkList(I);
3244 I.setOperand(1, RHSNeg);
3245 return &I;
3246 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003247
Dan Gohmandb3dd962007-11-05 23:16:33 +00003248 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003250 if (I.getType()->isInteger()) {
3251 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3252 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3253 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003254 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003255 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256 }
3257
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003258 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003259 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3260 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003261
Nick Lewyckyfd746832008-12-20 16:48:00 +00003262 bool hasNegative = false;
3263 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3264 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3265 if (RHS->getValue().isNegative())
3266 hasNegative = true;
3267
3268 if (hasNegative) {
3269 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003270 for (unsigned i = 0; i != VWidth; ++i) {
3271 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3272 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003273 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003274 else
3275 Elts[i] = RHS;
3276 }
3277 }
3278
Owen Anderson2f422e02009-07-28 21:19:26 +00003279 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003280 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003281 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003282 I.setOperand(1, NewRHSV);
3283 return &I;
3284 }
3285 }
3286 }
3287
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003288 return 0;
3289}
3290
3291Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3292 return commonRemTransforms(I);
3293}
3294
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295// isOneBitSet - Return true if there is exactly one bit set in the specified
3296// constant.
3297static bool isOneBitSet(const ConstantInt *CI) {
3298 return CI->getValue().isPowerOf2();
3299}
3300
3301// isHighOnes - Return true if the constant is of the form 1+0+.
3302// This is the same as lowones(~X).
3303static bool isHighOnes(const ConstantInt *CI) {
3304 return (~CI->getValue() + 1).isPowerOf2();
3305}
3306
3307/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3308/// are carefully arranged to allow folding of expressions such as:
3309///
3310/// (A < B) | (A > B) --> (A != B)
3311///
3312/// Note that this is only valid if the first and second predicates have the
3313/// same sign. Is illegal to do: (A u< B) | (A s> B)
3314///
3315/// Three bits are used to represent the condition, as follows:
3316/// 0 A > B
3317/// 1 A == B
3318/// 2 A < B
3319///
3320/// <=> Value Definition
3321/// 000 0 Always false
3322/// 001 1 A > B
3323/// 010 2 A == B
3324/// 011 3 A >= B
3325/// 100 4 A < B
3326/// 101 5 A != B
3327/// 110 6 A <= B
3328/// 111 7 Always true
3329///
3330static unsigned getICmpCode(const ICmpInst *ICI) {
3331 switch (ICI->getPredicate()) {
3332 // False -> 0
3333 case ICmpInst::ICMP_UGT: return 1; // 001
3334 case ICmpInst::ICMP_SGT: return 1; // 001
3335 case ICmpInst::ICMP_EQ: return 2; // 010
3336 case ICmpInst::ICMP_UGE: return 3; // 011
3337 case ICmpInst::ICMP_SGE: return 3; // 011
3338 case ICmpInst::ICMP_ULT: return 4; // 100
3339 case ICmpInst::ICMP_SLT: return 4; // 100
3340 case ICmpInst::ICMP_NE: return 5; // 101
3341 case ICmpInst::ICMP_ULE: return 6; // 110
3342 case ICmpInst::ICMP_SLE: return 6; // 110
3343 // True -> 7
3344 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003345 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346 return 0;
3347 }
3348}
3349
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003350/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3351/// predicate into a three bit mask. It also returns whether it is an ordered
3352/// predicate by reference.
3353static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3354 isOrdered = false;
3355 switch (CC) {
3356 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3357 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003358 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3359 case FCmpInst::FCMP_UGT: return 1; // 001
3360 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3361 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003362 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3363 case FCmpInst::FCMP_UGE: return 3; // 011
3364 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3365 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003366 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3367 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003368 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3369 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003370 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003371 default:
3372 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003373 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003374 return 0;
3375 }
3376}
3377
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378/// getICmpValue - This is the complement of getICmpCode, which turns an
3379/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003380/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003381/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003382static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003383 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003385 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003386 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387 case 1:
3388 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003389 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003390 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003391 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3392 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393 case 3:
3394 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003395 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003396 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003397 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003398 case 4:
3399 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003400 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003401 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003402 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3403 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003404 case 6:
3405 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003406 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003407 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003408 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003409 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003410 }
3411}
3412
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003413/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3414/// opcode and two operands into either a FCmp instruction. isordered is passed
3415/// in to determine which kind of predicate to use in the new fcmp instruction.
3416static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003417 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003418 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003419 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003420 case 0:
3421 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003423 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003424 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003425 case 1:
3426 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003428 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003429 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003430 case 2:
3431 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003433 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003434 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003435 case 3:
3436 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003438 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003439 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003440 case 4:
3441 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003443 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003445 case 5:
3446 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003447 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003448 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003449 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003450 case 6:
3451 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003452 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003453 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003454 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003455 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003456 }
3457}
3458
Chris Lattner2972b822008-11-16 04:55:20 +00003459/// PredicatesFoldable - Return true if both predicates match sign or if at
3460/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3462 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003463 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3464 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003465}
3466
3467namespace {
3468// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3469struct FoldICmpLogical {
3470 InstCombiner &IC;
3471 Value *LHS, *RHS;
3472 ICmpInst::Predicate pred;
3473 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3474 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3475 pred(ICI->getPredicate()) {}
3476 bool shouldApply(Value *V) const {
3477 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3478 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003479 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3480 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003481 return false;
3482 }
3483 Instruction *apply(Instruction &Log) const {
3484 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3485 if (ICI->getOperand(0) != LHS) {
3486 assert(ICI->getOperand(1) == LHS);
3487 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3488 }
3489
3490 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3491 unsigned LHSCode = getICmpCode(ICI);
3492 unsigned RHSCode = getICmpCode(RHSICI);
3493 unsigned Code;
3494 switch (Log.getOpcode()) {
3495 case Instruction::And: Code = LHSCode & RHSCode; break;
3496 case Instruction::Or: Code = LHSCode | RHSCode; break;
3497 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003498 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499 }
3500
3501 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3502 ICmpInst::isSignedPredicate(ICI->getPredicate());
3503
Owen Anderson24be4c12009-07-03 00:17:18 +00003504 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 if (Instruction *I = dyn_cast<Instruction>(RV))
3506 return I;
3507 // Otherwise, it's a constant boolean value...
3508 return IC.ReplaceInstUsesWith(Log, RV);
3509 }
3510};
3511} // end anonymous namespace
3512
3513// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3514// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3515// guaranteed to be a binary operator.
3516Instruction *InstCombiner::OptAndOp(Instruction *Op,
3517 ConstantInt *OpRHS,
3518 ConstantInt *AndRHS,
3519 BinaryOperator &TheAnd) {
3520 Value *X = Op->getOperand(0);
3521 Constant *Together = 0;
3522 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003523 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524
3525 switch (Op->getOpcode()) {
3526 case Instruction::Xor:
3527 if (Op->hasOneUse()) {
3528 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003529 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530 InsertNewInstBefore(And, TheAnd);
3531 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003532 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533 }
3534 break;
3535 case Instruction::Or:
3536 if (Together == AndRHS) // (X | C) & C --> C
3537 return ReplaceInstUsesWith(TheAnd, AndRHS);
3538
3539 if (Op->hasOneUse() && Together != OpRHS) {
3540 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003541 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542 InsertNewInstBefore(Or, TheAnd);
3543 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003544 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003545 }
3546 break;
3547 case Instruction::Add:
3548 if (Op->hasOneUse()) {
3549 // Adding a one to a single bit bit-field should be turned into an XOR
3550 // of the bit. First thing to check is to see if this AND is with a
3551 // single bit constant.
3552 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3553
3554 // If there is only one bit set...
3555 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3556 // Ok, at this point, we know that we are masking the result of the
3557 // ADD down to exactly one bit. If the constant we are adding has
3558 // no bits set below this bit, then we can eliminate the ADD.
3559 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3560
3561 // Check to see if any bits below the one bit set in AndRHSV are set.
3562 if ((AddRHS & (AndRHSV-1)) == 0) {
3563 // If not, the only thing that can effect the output of the AND is
3564 // the bit specified by AndRHSV. If that bit is set, the effect of
3565 // the XOR is to toggle the bit. If it is clear, then the ADD has
3566 // no effect.
3567 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3568 TheAnd.setOperand(0, X);
3569 return &TheAnd;
3570 } else {
3571 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003572 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003573 InsertNewInstBefore(NewAnd, TheAnd);
3574 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003575 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003576 }
3577 }
3578 }
3579 }
3580 break;
3581
3582 case Instruction::Shl: {
3583 // We know that the AND will not produce any of the bits shifted in, so if
3584 // the anded constant includes them, clear them now!
3585 //
3586 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3587 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3588 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003589 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003590
3591 if (CI->getValue() == ShlMask) {
3592 // Masking out bits that the shift already masks
3593 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3594 } else if (CI != AndRHS) { // Reducing bits set in and.
3595 TheAnd.setOperand(1, CI);
3596 return &TheAnd;
3597 }
3598 break;
3599 }
3600 case Instruction::LShr:
3601 {
3602 // We know that the AND will not produce any of the bits shifted in, so if
3603 // the anded constant includes them, clear them now! This only applies to
3604 // unsigned shifts, because a signed shr may bring in set bits!
3605 //
3606 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3607 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3608 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003609 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003610
3611 if (CI->getValue() == ShrMask) {
3612 // Masking out bits that the shift already masks.
3613 return ReplaceInstUsesWith(TheAnd, Op);
3614 } else if (CI != AndRHS) {
3615 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3616 return &TheAnd;
3617 }
3618 break;
3619 }
3620 case Instruction::AShr:
3621 // Signed shr.
3622 // See if this is shifting in some sign extension, then masking it out
3623 // with an and.
3624 if (Op->hasOneUse()) {
3625 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3626 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3627 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003628 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003629 if (C == AndRHS) { // Masking out bits shifted in.
3630 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3631 // Make the argument unsigned.
3632 Value *ShVal = Op->getOperand(0);
3633 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003634 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003635 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003636 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003637 }
3638 }
3639 break;
3640 }
3641 return 0;
3642}
3643
3644
3645/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3646/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3647/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3648/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3649/// insert new instructions.
3650Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3651 bool isSigned, bool Inside,
3652 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003653 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3655 "Lo is not <= Hi in range emission code!");
3656
3657 if (Inside) {
3658 if (Lo == Hi) // Trivially false.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003659 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003660
3661 // V >= Min && V < Hi --> V < Hi
3662 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3663 ICmpInst::Predicate pred = (isSigned ?
3664 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003665 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003666 }
3667
3668 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003669 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003670 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003671 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003672 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003673 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003674 }
3675
3676 if (Lo == Hi) // Trivially true.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003677 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003678
3679 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003680 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003681 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3682 ICmpInst::Predicate pred = (isSigned ?
3683 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003684 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003685 }
3686
3687 // Emit V-Lo >u Hi-1-Lo
3688 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003689 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003690 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003692 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003693 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003694}
3695
3696// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3697// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3698// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3699// not, since all 1s are not contiguous.
3700static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3701 const APInt& V = Val->getValue();
3702 uint32_t BitWidth = Val->getType()->getBitWidth();
3703 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3704
3705 // look for the first zero bit after the run of ones
3706 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3707 // look for the first non-zero bit
3708 ME = V.getActiveBits();
3709 return true;
3710}
3711
3712/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3713/// where isSub determines whether the operator is a sub. If we can fold one of
3714/// the following xforms:
3715///
3716/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3717/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3718/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3719///
3720/// return (A +/- B).
3721///
3722Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3723 ConstantInt *Mask, bool isSub,
3724 Instruction &I) {
3725 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3726 if (!LHSI || LHSI->getNumOperands() != 2 ||
3727 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3728
3729 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3730
3731 switch (LHSI->getOpcode()) {
3732 default: return 0;
3733 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003734 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003735 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3736 if ((Mask->getValue().countLeadingZeros() +
3737 Mask->getValue().countPopulation()) ==
3738 Mask->getValue().getBitWidth())
3739 break;
3740
3741 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3742 // part, we don't need any explicit masks to take them out of A. If that
3743 // is all N is, ignore it.
3744 uint32_t MB = 0, ME = 0;
3745 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3746 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3747 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3748 if (MaskedValueIsZero(RHS, Mask))
3749 break;
3750 }
3751 }
3752 return 0;
3753 case Instruction::Or:
3754 case Instruction::Xor:
3755 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3756 if ((Mask->getValue().countLeadingZeros() +
3757 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003758 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003759 break;
3760 return 0;
3761 }
3762
3763 Instruction *New;
3764 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003765 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003766 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003767 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003768 return InsertNewInstBefore(New, I);
3769}
3770
Chris Lattner0631ea72008-11-16 05:06:21 +00003771/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3772Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3773 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003774 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003775 ConstantInt *LHSCst, *RHSCst;
3776 ICmpInst::Predicate LHSCC, RHSCC;
3777
Chris Lattnerf3803482008-11-16 05:10:52 +00003778 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003779 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003780 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003781 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003782 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003783 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003784
3785 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3786 // where C is a power of 2
3787 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3788 LHSCst->getValue().isPowerOf2()) {
3789 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3790 InsertNewInstBefore(NewOr, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003791 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003792 }
3793
3794 // From here on, we only handle:
3795 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3796 if (Val != Val2) return 0;
3797
Chris Lattner0631ea72008-11-16 05:06:21 +00003798 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3799 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3800 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3801 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3802 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3803 return 0;
3804
3805 // We can't fold (ugt x, C) & (sgt x, C2).
3806 if (!PredicatesFoldable(LHSCC, RHSCC))
3807 return 0;
3808
3809 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003810 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003811 if (ICmpInst::isSignedPredicate(LHSCC) ||
3812 (ICmpInst::isEquality(LHSCC) &&
3813 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003814 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003815 else
Chris Lattner665298f2008-11-16 05:14:43 +00003816 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3817
3818 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003819 std::swap(LHS, RHS);
3820 std::swap(LHSCst, RHSCst);
3821 std::swap(LHSCC, RHSCC);
3822 }
3823
3824 // At this point, we know we have have two icmp instructions
3825 // comparing a value against two constants and and'ing the result
3826 // together. Because of the above check, we know that we only have
3827 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3828 // (from the FoldICmpLogical check above), that the two constants
3829 // are not equal and that the larger constant is on the RHS
3830 assert(LHSCst != RHSCst && "Compares not folded above?");
3831
3832 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003833 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003834 case ICmpInst::ICMP_EQ:
3835 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003836 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003837 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3838 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3839 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003840 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003841 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3842 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3843 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3844 return ReplaceInstUsesWith(I, LHS);
3845 }
3846 case ICmpInst::ICMP_NE:
3847 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003848 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003849 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003850 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003851 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003852 break; // (X != 13 & X u< 15) -> no change
3853 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003854 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003855 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003856 break; // (X != 13 & X s< 15) -> no change
3857 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3858 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3859 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3860 return ReplaceInstUsesWith(I, RHS);
3861 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003862 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003863 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003864 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3865 Val->getName()+".off");
3866 InsertNewInstBefore(Add, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003867 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003868 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003869 }
3870 break; // (X != 13 & X != 15) -> no change
3871 }
3872 break;
3873 case ICmpInst::ICMP_ULT:
3874 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003875 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003876 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3877 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003878 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003879 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3880 break;
3881 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3882 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3883 return ReplaceInstUsesWith(I, LHS);
3884 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3885 break;
3886 }
3887 break;
3888 case ICmpInst::ICMP_SLT:
3889 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003890 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003891 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3892 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003893 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003894 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3895 break;
3896 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3897 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3898 return ReplaceInstUsesWith(I, LHS);
3899 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3900 break;
3901 }
3902 break;
3903 case ICmpInst::ICMP_UGT:
3904 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003905 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003906 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3907 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3908 return ReplaceInstUsesWith(I, RHS);
3909 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3910 break;
3911 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003912 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003913 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003914 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003915 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003916 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003917 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003918 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3919 break;
3920 }
3921 break;
3922 case ICmpInst::ICMP_SGT:
3923 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003924 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003925 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3926 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3927 return ReplaceInstUsesWith(I, RHS);
3928 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3929 break;
3930 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003931 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003932 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003933 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003934 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003935 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003936 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003937 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3938 break;
3939 }
3940 break;
3941 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003942
3943 return 0;
3944}
3945
Chris Lattner93a359a2009-07-23 05:14:02 +00003946Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3947 FCmpInst *RHS) {
3948
3949 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3950 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3951 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3952 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3953 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3954 // If either of the constants are nans, then the whole thing returns
3955 // false.
3956 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003957 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003958 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3959 LHS->getOperand(0), RHS->getOperand(0));
3960 }
Chris Lattnercf373552009-07-23 05:32:17 +00003961
3962 // Handle vector zeros. This occurs because the canonical form of
3963 // "fcmp ord x,x" is "fcmp ord x, 0".
3964 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3965 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3966 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3967 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003968 return 0;
3969 }
3970
3971 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3972 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3973 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3974
3975
3976 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3977 // Swap RHS operands to match LHS.
3978 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3979 std::swap(Op1LHS, Op1RHS);
3980 }
3981
3982 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3983 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3984 if (Op0CC == Op1CC)
3985 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3986
3987 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003988 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003989 if (Op0CC == FCmpInst::FCMP_TRUE)
3990 return ReplaceInstUsesWith(I, RHS);
3991 if (Op1CC == FCmpInst::FCMP_TRUE)
3992 return ReplaceInstUsesWith(I, LHS);
3993
3994 bool Op0Ordered;
3995 bool Op1Ordered;
3996 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3997 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3998 if (Op1Pred == 0) {
3999 std::swap(LHS, RHS);
4000 std::swap(Op0Pred, Op1Pred);
4001 std::swap(Op0Ordered, Op1Ordered);
4002 }
4003 if (Op0Pred == 0) {
4004 // uno && ueq -> uno && (uno || eq) -> ueq
4005 // ord && olt -> ord && (ord && lt) -> olt
4006 if (Op0Ordered == Op1Ordered)
4007 return ReplaceInstUsesWith(I, RHS);
4008
4009 // uno && oeq -> uno && (ord && eq) -> false
4010 // uno && ord -> false
4011 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004012 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004013 // ord && ueq -> ord && (uno || eq) -> oeq
4014 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4015 Op0LHS, Op0RHS, Context));
4016 }
4017 }
4018
4019 return 0;
4020}
4021
Chris Lattner0631ea72008-11-16 05:06:21 +00004022
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004023Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4024 bool Changed = SimplifyCommutative(I);
4025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4026
4027 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004029
4030 // and X, X = X
4031 if (Op0 == Op1)
4032 return ReplaceInstUsesWith(I, Op1);
4033
4034 // See if we can simplify any instructions used by the instruction whose sole
4035 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004036 if (SimplifyDemandedInstructionBits(I))
4037 return &I;
4038 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004039 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4040 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4041 return ReplaceInstUsesWith(I, I.getOperand(0));
4042 } else if (isa<ConstantAggregateZero>(Op1)) {
4043 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4044 }
4045 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004046
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004047 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4048 const APInt& AndRHSMask = AndRHS->getValue();
4049 APInt NotAndRHS(~AndRHSMask);
4050
4051 // Optimize a variety of ((val OP C1) & C2) combinations...
4052 if (isa<BinaryOperator>(Op0)) {
4053 Instruction *Op0I = cast<Instruction>(Op0);
4054 Value *Op0LHS = Op0I->getOperand(0);
4055 Value *Op0RHS = Op0I->getOperand(1);
4056 switch (Op0I->getOpcode()) {
4057 case Instruction::Xor:
4058 case Instruction::Or:
4059 // If the mask is only needed on one incoming arm, push it up.
4060 if (Op0I->hasOneUse()) {
4061 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4062 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004063 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004064 Op0RHS->getName()+".masked");
4065 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004066 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004067 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4068 }
4069 if (!isa<Constant>(Op0RHS) &&
4070 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4071 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004072 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004073 Op0LHS->getName()+".masked");
4074 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004075 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4077 }
4078 }
4079
4080 break;
4081 case Instruction::Add:
4082 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4083 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4084 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4085 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004086 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004087 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004088 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089 break;
4090
4091 case Instruction::Sub:
4092 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4093 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4094 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4095 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004096 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004097
Nick Lewyckya349ba42008-07-10 05:51:40 +00004098 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4099 // has 1's for all bits that the subtraction with A might affect.
4100 if (Op0I->hasOneUse()) {
4101 uint32_t BitWidth = AndRHSMask.getBitWidth();
4102 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4103 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4104
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004105 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004106 if (!(A && A->isZero()) && // avoid infinite recursion.
4107 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohmancdff2122009-08-12 16:23:25 +00004108 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004109 InsertNewInstBefore(NewNeg, I);
4110 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4111 }
4112 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004113 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004114
4115 case Instruction::Shl:
4116 case Instruction::LShr:
4117 // (1 << x) & 1 --> zext(x == 0)
4118 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004119 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00004120 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00004121 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004122 InsertNewInstBefore(NewICmp, I);
4123 return new ZExtInst(NewICmp, I.getType());
4124 }
4125 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004126 }
4127
4128 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4129 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4130 return Res;
4131 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4132 // If this is an integer truncation or change from signed-to-unsigned, and
4133 // if the source is an and/or with immediate, transform it. This
4134 // frequently occurs for bitfield accesses.
4135 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4136 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4137 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004138 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004139 if (CastOp->getOpcode() == Instruction::And) {
4140 // Change: and (cast (and X, C1) to T), C2
4141 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4142 // This will fold the two constants together, which may allow
4143 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004144 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004145 CastOp->getOperand(0), I.getType(),
4146 CastOp->getName()+".shrunk");
4147 NewCast = InsertNewInstBefore(NewCast, I);
4148 // trunc_or_bitcast(C1)&C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004149 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004150 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4151 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004152 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004153 } else if (CastOp->getOpcode() == Instruction::Or) {
4154 // Change: and (cast (or X, C1) to T), C2
4155 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004156 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004157 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4158 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004159 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160 return ReplaceInstUsesWith(I, AndRHS);
4161 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004162 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163 }
4164 }
4165
4166 // Try to fold constant and into select arguments.
4167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4168 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4169 return R;
4170 if (isa<PHINode>(Op0))
4171 if (Instruction *NV = FoldOpIntoPhi(I))
4172 return NV;
4173 }
4174
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004175 Value *Op0NotVal = dyn_castNotVal(Op0);
4176 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004177
4178 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004179 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004180
4181 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4182 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004183 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004184 I.getName()+".demorgan");
4185 InsertNewInstBefore(Or, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00004186 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004187 }
4188
4189 {
4190 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004191 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004192 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4193 return ReplaceInstUsesWith(I, Op1);
4194
4195 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004196 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004197 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004198 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004199 }
4200 }
4201
Dan Gohmancdff2122009-08-12 16:23:25 +00004202 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4204 return ReplaceInstUsesWith(I, Op0);
4205
4206 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004207 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004208 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004209 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004210 }
4211 }
4212
4213 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004214 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004215 if (A == Op1) { // (A^B)&A -> A&(A^B)
4216 I.swapOperands(); // Simplify below
4217 std::swap(Op0, Op1);
4218 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4219 cast<BinaryOperator>(Op0)->swapOperands();
4220 I.swapOperands(); // Simplify below
4221 std::swap(Op0, Op1);
4222 }
4223 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004224
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004226 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004227 if (B == Op0) { // B&(A^B) -> B&(B^A)
4228 cast<BinaryOperator>(Op1)->swapOperands();
4229 std::swap(A, B);
4230 }
4231 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohmancdff2122009-08-12 16:23:25 +00004232 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004233 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004234 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235 }
4236 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004237
4238 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004239 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4240 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004241 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004242 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4243 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004244 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 }
4246
4247 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4248 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004249 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004250 return R;
4251
Chris Lattner0631ea72008-11-16 05:06:21 +00004252 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4253 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4254 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255 }
4256
4257 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4258 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4259 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4260 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4261 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004262 if (SrcTy == Op1C->getOperand(0)->getType() &&
4263 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004264 // Only do this if the casts both really cause code to be generated.
4265 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4266 I.getType(), TD) &&
4267 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4268 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004269 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004270 Op1C->getOperand(0),
4271 I.getName());
4272 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004273 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004274 }
4275 }
4276
4277 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4278 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4279 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4280 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4281 SI0->getOperand(1) == SI1->getOperand(1) &&
4282 (SI0->hasOneUse() || SI1->hasOneUse())) {
4283 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004284 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004285 SI1->getOperand(0),
4286 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004287 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004288 SI1->getOperand(1));
4289 }
4290 }
4291
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004292 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004293 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004294 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4295 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4296 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004297 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004298
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004299 return Changed ? &I : 0;
4300}
4301
Chris Lattner567f5112008-10-05 02:13:19 +00004302/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4303/// capable of providing pieces of a bswap. The subexpression provides pieces
4304/// of a bswap if it is proven that each of the non-zero bytes in the output of
4305/// the expression came from the corresponding "byte swapped" byte in some other
4306/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4307/// we know that the expression deposits the low byte of %X into the high byte
4308/// of the bswap result and that all other bytes are zero. This expression is
4309/// accepted, the high byte of ByteValues is set to X to indicate a correct
4310/// match.
4311///
4312/// This function returns true if the match was unsuccessful and false if so.
4313/// On entry to the function the "OverallLeftShift" is a signed integer value
4314/// indicating the number of bytes that the subexpression is later shifted. For
4315/// example, if the expression is later right shifted by 16 bits, the
4316/// OverallLeftShift value would be -2 on entry. This is used to specify which
4317/// byte of ByteValues is actually being set.
4318///
4319/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4320/// byte is masked to zero by a user. For example, in (X & 255), X will be
4321/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4322/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4323/// always in the local (OverallLeftShift) coordinate space.
4324///
4325static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4326 SmallVector<Value*, 8> &ByteValues) {
4327 if (Instruction *I = dyn_cast<Instruction>(V)) {
4328 // If this is an or instruction, it may be an inner node of the bswap.
4329 if (I->getOpcode() == Instruction::Or) {
4330 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4331 ByteValues) ||
4332 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4333 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004334 }
Chris Lattner567f5112008-10-05 02:13:19 +00004335
4336 // If this is a logical shift by a constant multiple of 8, recurse with
4337 // OverallLeftShift and ByteMask adjusted.
4338 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4339 unsigned ShAmt =
4340 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4341 // Ensure the shift amount is defined and of a byte value.
4342 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4343 return true;
4344
4345 unsigned ByteShift = ShAmt >> 3;
4346 if (I->getOpcode() == Instruction::Shl) {
4347 // X << 2 -> collect(X, +2)
4348 OverallLeftShift += ByteShift;
4349 ByteMask >>= ByteShift;
4350 } else {
4351 // X >>u 2 -> collect(X, -2)
4352 OverallLeftShift -= ByteShift;
4353 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004354 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004355 }
4356
4357 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4358 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4359
4360 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4361 ByteValues);
4362 }
4363
4364 // If this is a logical 'and' with a mask that clears bytes, clear the
4365 // corresponding bytes in ByteMask.
4366 if (I->getOpcode() == Instruction::And &&
4367 isa<ConstantInt>(I->getOperand(1))) {
4368 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4369 unsigned NumBytes = ByteValues.size();
4370 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4371 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4372
4373 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4374 // If this byte is masked out by a later operation, we don't care what
4375 // the and mask is.
4376 if ((ByteMask & (1 << i)) == 0)
4377 continue;
4378
4379 // If the AndMask is all zeros for this byte, clear the bit.
4380 APInt MaskB = AndMask & Byte;
4381 if (MaskB == 0) {
4382 ByteMask &= ~(1U << i);
4383 continue;
4384 }
4385
4386 // If the AndMask is not all ones for this byte, it's not a bytezap.
4387 if (MaskB != Byte)
4388 return true;
4389
4390 // Otherwise, this byte is kept.
4391 }
4392
4393 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4394 ByteValues);
4395 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004396 }
4397
Chris Lattner567f5112008-10-05 02:13:19 +00004398 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4399 // the input value to the bswap. Some observations: 1) if more than one byte
4400 // is demanded from this input, then it could not be successfully assembled
4401 // into a byteswap. At least one of the two bytes would not be aligned with
4402 // their ultimate destination.
4403 if (!isPowerOf2_32(ByteMask)) return true;
4404 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004405
Chris Lattner567f5112008-10-05 02:13:19 +00004406 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4407 // is demanded, it needs to go into byte 0 of the result. This means that the
4408 // byte needs to be shifted until it lands in the right byte bucket. The
4409 // shift amount depends on the position: if the byte is coming from the high
4410 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4411 // low part, it must be shifted left.
4412 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4413 if (InputByteNo < ByteValues.size()/2) {
4414 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4415 return true;
4416 } else {
4417 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4418 return true;
4419 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004420
4421 // If the destination byte value is already defined, the values are or'd
4422 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004423 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004424 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004425 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 return false;
4427}
4428
4429/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4430/// If so, insert the new bswap intrinsic and return it.
4431Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4432 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004433 if (!ITy || ITy->getBitWidth() % 16 ||
4434 // ByteMask only allows up to 32-byte values.
4435 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4437
4438 /// ByteValues - For each byte of the result, we keep track of which value
4439 /// defines each byte.
4440 SmallVector<Value*, 8> ByteValues;
4441 ByteValues.resize(ITy->getBitWidth()/8);
4442
4443 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004444 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4445 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004446 return 0;
4447
4448 // Check to see if all of the bytes come from the same value.
4449 Value *V = ByteValues[0];
4450 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4451
4452 // Check to make sure that all of the bytes come from the same value.
4453 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4454 if (ByteValues[i] != V)
4455 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004456 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004457 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004458 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004459 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004460}
4461
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004462/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4463/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4464/// we can simplify this expression to "cond ? C : D or B".
4465static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004466 Value *C, Value *D,
4467 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004468 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004469 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004470 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004471 return 0;
4472
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004473 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004474 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004475 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004476 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004477 return SelectInst::Create(Cond, C, B);
4478 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004479 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004480 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004481 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004482 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004483 return 0;
4484}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004485
Chris Lattner0c678e52008-11-16 05:20:07 +00004486/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4487Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4488 ICmpInst *LHS, ICmpInst *RHS) {
4489 Value *Val, *Val2;
4490 ConstantInt *LHSCst, *RHSCst;
4491 ICmpInst::Predicate LHSCC, RHSCC;
4492
4493 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004494 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004495 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004496 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004497 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004498 return 0;
4499
4500 // From here on, we only handle:
4501 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4502 if (Val != Val2) return 0;
4503
4504 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4505 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4506 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4507 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4508 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4509 return 0;
4510
4511 // We can't fold (ugt x, C) | (sgt x, C2).
4512 if (!PredicatesFoldable(LHSCC, RHSCC))
4513 return 0;
4514
4515 // Ensure that the larger constant is on the RHS.
4516 bool ShouldSwap;
4517 if (ICmpInst::isSignedPredicate(LHSCC) ||
4518 (ICmpInst::isEquality(LHSCC) &&
4519 ICmpInst::isSignedPredicate(RHSCC)))
4520 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4521 else
4522 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4523
4524 if (ShouldSwap) {
4525 std::swap(LHS, RHS);
4526 std::swap(LHSCst, RHSCst);
4527 std::swap(LHSCC, RHSCC);
4528 }
4529
4530 // At this point, we know we have have two icmp instructions
4531 // comparing a value against two constants and or'ing the result
4532 // together. Because of the above check, we know that we only have
4533 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4534 // FoldICmpLogical check above), that the two constants are not
4535 // equal.
4536 assert(LHSCst != RHSCst && "Compares not folded above?");
4537
4538 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004539 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004540 case ICmpInst::ICMP_EQ:
4541 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004542 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004543 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004544 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004545 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004546 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004547 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4548 Val->getName()+".off");
4549 InsertNewInstBefore(Add, I);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004550 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Owen Anderson6601fcd2009-07-09 23:48:35 +00004551 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004552 }
4553 break; // (X == 13 | X == 15) -> no change
4554 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4555 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4556 break;
4557 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4558 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4559 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4560 return ReplaceInstUsesWith(I, RHS);
4561 }
4562 break;
4563 case ICmpInst::ICMP_NE:
4564 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004565 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004566 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4567 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4568 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4569 return ReplaceInstUsesWith(I, LHS);
4570 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4571 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4572 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004573 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004574 }
4575 break;
4576 case ICmpInst::ICMP_ULT:
4577 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004578 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004579 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4580 break;
4581 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4582 // If RHSCst is [us]MAXINT, it is always false. Not handling
4583 // this can cause overflow.
4584 if (RHSCst->isMaxValue(false))
4585 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004586 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004587 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004588 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4589 break;
4590 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4591 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4592 return ReplaceInstUsesWith(I, RHS);
4593 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4594 break;
4595 }
4596 break;
4597 case ICmpInst::ICMP_SLT:
4598 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004599 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004600 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4601 break;
4602 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4603 // If RHSCst is [us]MAXINT, it is always false. Not handling
4604 // this can cause overflow.
4605 if (RHSCst->isMaxValue(true))
4606 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004607 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004608 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004609 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4610 break;
4611 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4612 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4613 return ReplaceInstUsesWith(I, RHS);
4614 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4615 break;
4616 }
4617 break;
4618 case ICmpInst::ICMP_UGT:
4619 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004620 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004621 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4622 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4623 return ReplaceInstUsesWith(I, LHS);
4624 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4625 break;
4626 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4627 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004628 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004629 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4630 break;
4631 }
4632 break;
4633 case ICmpInst::ICMP_SGT:
4634 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004635 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004636 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4637 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4638 return ReplaceInstUsesWith(I, LHS);
4639 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4640 break;
4641 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4642 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004643 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004644 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4645 break;
4646 }
4647 break;
4648 }
4649 return 0;
4650}
4651
Chris Lattner57e66fa2009-07-23 05:46:22 +00004652Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4653 FCmpInst *RHS) {
4654 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4655 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4656 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4657 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4658 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4659 // If either of the constants are nans, then the whole thing returns
4660 // true.
4661 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004663
4664 // Otherwise, no need to compare the two constants, compare the
4665 // rest.
4666 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4667 LHS->getOperand(0), RHS->getOperand(0));
4668 }
4669
4670 // Handle vector zeros. This occurs because the canonical form of
4671 // "fcmp uno x,x" is "fcmp uno x, 0".
4672 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4673 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4674 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4675 LHS->getOperand(0), RHS->getOperand(0));
4676
4677 return 0;
4678 }
4679
4680 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4681 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4682 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4683
4684 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4685 // Swap RHS operands to match LHS.
4686 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4687 std::swap(Op1LHS, Op1RHS);
4688 }
4689 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4690 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4691 if (Op0CC == Op1CC)
4692 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4693 Op0LHS, Op0RHS);
4694 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004695 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004696 if (Op0CC == FCmpInst::FCMP_FALSE)
4697 return ReplaceInstUsesWith(I, RHS);
4698 if (Op1CC == FCmpInst::FCMP_FALSE)
4699 return ReplaceInstUsesWith(I, LHS);
4700 bool Op0Ordered;
4701 bool Op1Ordered;
4702 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4703 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4704 if (Op0Ordered == Op1Ordered) {
4705 // If both are ordered or unordered, return a new fcmp with
4706 // or'ed predicates.
4707 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4708 Op0LHS, Op0RHS, Context);
4709 if (Instruction *I = dyn_cast<Instruction>(RV))
4710 return I;
4711 // Otherwise, it's a constant boolean value...
4712 return ReplaceInstUsesWith(I, RV);
4713 }
4714 }
4715 return 0;
4716}
4717
Bill Wendlingdae376a2008-12-01 08:23:25 +00004718/// FoldOrWithConstants - This helper function folds:
4719///
Bill Wendling236a1192008-12-02 05:09:00 +00004720/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004721///
4722/// into:
4723///
Bill Wendling236a1192008-12-02 05:09:00 +00004724/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004725///
Bill Wendling236a1192008-12-02 05:09:00 +00004726/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004727Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004728 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004729 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4730 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004731
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004732 Value *V1 = 0;
4733 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004734 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004735
Bill Wendling86ee3162008-12-02 06:18:11 +00004736 APInt Xor = CI1->getValue() ^ CI2->getValue();
4737 if (!Xor.isAllOnesValue()) return 0;
4738
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004739 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004740 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004741 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4742 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004743 }
4744
4745 return 0;
4746}
4747
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004748Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4749 bool Changed = SimplifyCommutative(I);
4750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4751
4752 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004753 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004754
4755 // or X, X = X
4756 if (Op0 == Op1)
4757 return ReplaceInstUsesWith(I, Op0);
4758
4759 // See if we can simplify any instructions used by the instruction whose sole
4760 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004761 if (SimplifyDemandedInstructionBits(I))
4762 return &I;
4763 if (isa<VectorType>(I.getType())) {
4764 if (isa<ConstantAggregateZero>(Op1)) {
4765 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4766 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4767 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4768 return ReplaceInstUsesWith(I, I.getOperand(1));
4769 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004771
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772 // or X, -1 == -1
4773 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4774 ConstantInt *C1 = 0; Value *X = 0;
4775 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004776 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004777 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004778 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004779 InsertNewInstBefore(Or, I);
4780 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004781 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004782 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004783 }
4784
4785 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004786 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004787 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004788 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004789 InsertNewInstBefore(Or, I);
4790 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004791 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004792 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004793 }
4794
4795 // Try to fold constant and into select arguments.
4796 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4797 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4798 return R;
4799 if (isa<PHINode>(Op0))
4800 if (Instruction *NV = FoldOpIntoPhi(I))
4801 return NV;
4802 }
4803
4804 Value *A = 0, *B = 0;
4805 ConstantInt *C1 = 0, *C2 = 0;
4806
Dan Gohmancdff2122009-08-12 16:23:25 +00004807 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004808 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4809 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004810 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004811 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4812 return ReplaceInstUsesWith(I, Op0);
4813
4814 // (A | B) | C and A | (B | C) -> bswap if possible.
4815 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004816 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4817 match(Op1, m_Or(m_Value(), m_Value())) ||
4818 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4819 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004820 if (Instruction *BSwap = MatchBSwap(I))
4821 return BSwap;
4822 }
4823
4824 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004825 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004826 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004827 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004828 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004829 InsertNewInstBefore(NOr, I);
4830 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004831 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004832 }
4833
4834 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004835 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004836 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004837 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004838 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004839 InsertNewInstBefore(NOr, I);
4840 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004841 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004842 }
4843
4844 // (A & C)|(B & D)
4845 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004846 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4847 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004848 Value *V1 = 0, *V2 = 0, *V3 = 0;
4849 C1 = dyn_cast<ConstantInt>(C);
4850 C2 = dyn_cast<ConstantInt>(D);
4851 if (C1 && C2) { // (A & C1)|(B & C2)
4852 // If we have: ((V + N) & C1) | (V & C2)
4853 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4854 // replace with V+N.
4855 if (C1->getValue() == ~C2->getValue()) {
4856 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00004857 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004858 // Add commutes, try both ways.
4859 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4860 return ReplaceInstUsesWith(I, A);
4861 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4862 return ReplaceInstUsesWith(I, A);
4863 }
4864 // Or commutes, try both ways.
4865 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004866 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004867 // Add commutes, try both ways.
4868 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4869 return ReplaceInstUsesWith(I, B);
4870 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4871 return ReplaceInstUsesWith(I, B);
4872 }
4873 }
4874 V1 = 0; V2 = 0; V3 = 0;
4875 }
4876
4877 // Check to see if we have any common things being and'ed. If so, find the
4878 // terms for V1 & (V2|V3).
4879 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4880 if (A == B) // (A & C)|(A & D) == A & (C|D)
4881 V1 = A, V2 = C, V3 = D;
4882 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4883 V1 = A, V2 = B, V3 = C;
4884 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4885 V1 = C, V2 = A, V3 = D;
4886 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4887 V1 = C, V2 = A, V3 = B;
4888
4889 if (V1) {
4890 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004891 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4892 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004893 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004894 }
Dan Gohman279952c2008-10-28 22:38:57 +00004895
Dan Gohman35b76162008-10-30 20:40:10 +00004896 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004897 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004898 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004899 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004900 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004901 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004902 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004903 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004904 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004905
Bill Wendling22ca8352008-11-30 13:52:49 +00004906 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004907 if ((match(C, m_Not(m_Specific(D))) &&
4908 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004909 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004910 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004911 if ((match(A, m_Not(m_Specific(D))) &&
4912 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004913 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004914 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004915 if ((match(C, m_Not(m_Specific(B))) &&
4916 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004917 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004918 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004919 if ((match(A, m_Not(m_Specific(B))) &&
4920 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004921 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004922 }
4923
4924 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4925 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4926 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4927 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4928 SI0->getOperand(1) == SI1->getOperand(1) &&
4929 (SI0->hasOneUse() || SI1->hasOneUse())) {
4930 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004931 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004932 SI1->getOperand(0),
4933 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004934 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004935 SI1->getOperand(1));
4936 }
4937 }
4938
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004939 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004940 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4941 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004942 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004943 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004944 }
4945 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004946 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4947 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004948 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004949 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004950 }
4951
Dan Gohmancdff2122009-08-12 16:23:25 +00004952 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004953 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004954 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004955 } else {
4956 A = 0;
4957 }
4958 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004959 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004960 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004961 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004962
4963 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4964 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004965 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004966 I.getName()+".demorgan"), I);
Dan Gohmancdff2122009-08-12 16:23:25 +00004967 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004968 }
4969 }
4970
4971 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4972 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004973 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004974 return R;
4975
Chris Lattner0c678e52008-11-16 05:20:07 +00004976 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4977 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4978 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004979 }
4980
4981 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004982 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004983 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4984 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004985 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4986 !isa<ICmpInst>(Op1C->getOperand(0))) {
4987 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004988 if (SrcTy == Op1C->getOperand(0)->getType() &&
4989 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004990 // Only do this if the casts both really cause code to be
4991 // generated.
4992 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4993 I.getType(), TD) &&
4994 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4995 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004996 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004997 Op1C->getOperand(0),
4998 I.getName());
4999 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005000 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005001 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005002 }
5003 }
Chris Lattner91882432007-10-24 05:38:08 +00005004 }
5005
5006
5007 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5008 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005009 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5010 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5011 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005012 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005013
5014 return Changed ? &I : 0;
5015}
5016
Dan Gohman089efff2008-05-13 00:00:25 +00005017namespace {
5018
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005019// XorSelf - Implements: X ^ X --> 0
5020struct XorSelf {
5021 Value *RHS;
5022 XorSelf(Value *rhs) : RHS(rhs) {}
5023 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5024 Instruction *apply(BinaryOperator &Xor) const {
5025 return &Xor;
5026 }
5027};
5028
Dan Gohman089efff2008-05-13 00:00:25 +00005029}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005030
5031Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5032 bool Changed = SimplifyCommutative(I);
5033 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5034
Evan Chenge5cd8032008-03-25 20:07:13 +00005035 if (isa<UndefValue>(Op1)) {
5036 if (isa<UndefValue>(Op0))
5037 // Handle undef ^ undef -> 0 special case. This is a common
5038 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005039 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005040 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005041 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005042
5043 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005044 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005045 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005046 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005047 }
5048
5049 // See if we can simplify any instructions used by the instruction whose sole
5050 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005051 if (SimplifyDemandedInstructionBits(I))
5052 return &I;
5053 if (isa<VectorType>(I.getType()))
5054 if (isa<ConstantAggregateZero>(Op1))
5055 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005056
5057 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005058 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005059 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5060 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5061 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5062 if (Op0I->getOpcode() == Instruction::And ||
5063 Op0I->getOpcode() == Instruction::Or) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005064 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5065 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005066 Instruction *NotY =
Dan Gohmancdff2122009-08-12 16:23:25 +00005067 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005068 Op0I->getOperand(1)->getName()+".not");
5069 InsertNewInstBefore(NotY, I);
5070 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005071 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005072 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005073 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005074 }
5075 }
5076 }
5077 }
5078
5079
5080 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00005081 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005082 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005083 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005084 return new ICmpInst(*Context, ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005085 ICI->getOperand(0), ICI->getOperand(1));
5086
Nick Lewycky1405e922007-08-06 20:04:16 +00005087 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005088 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005089 FCI->getOperand(0), FCI->getOperand(1));
5090 }
5091
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005092 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5093 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5094 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5095 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5096 Instruction::CastOps Opcode = Op0C->getOpcode();
5097 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005098 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson4f720fa2009-07-31 17:39:07 +00005099 ConstantInt::getTrue(*Context),
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005100 Op0C->getDestTy())) {
5101 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson6601fcd2009-07-09 23:48:35 +00005102 *Context,
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005103 CI->getOpcode(), CI->getInversePredicate(),
5104 CI->getOperand(0), CI->getOperand(1)), I);
5105 NewCI->takeName(CI);
5106 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5107 }
5108 }
5109 }
5110 }
5111 }
5112
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005113 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5114 // ~(c-X) == X-c-1 == X+(-c-1)
5115 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5116 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005117 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5118 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005119 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005120 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005121 }
5122
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005123 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005124 if (Op0I->getOpcode() == Instruction::Add) {
5125 // ~(X-c) --> (-c-1)-X
5126 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005127 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005128 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005129 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005130 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005131 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005132 } else if (RHS->getValue().isSignBit()) {
5133 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005134 Constant *C = ConstantInt::get(*Context,
5135 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005136 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005137
5138 }
5139 } else if (Op0I->getOpcode() == Instruction::Or) {
5140 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5141 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005142 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005143 // Anything in both C1 and C2 is known to be zero, remove it from
5144 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005145 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5146 NewRHS = ConstantExpr::getAnd(NewRHS,
5147 ConstantExpr::getNot(CommonBits));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005148 AddToWorkList(Op0I);
5149 I.setOperand(0, Op0I->getOperand(0));
5150 I.setOperand(1, NewRHS);
5151 return &I;
5152 }
5153 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005154 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005155 }
5156
5157 // Try to fold constant and into select arguments.
5158 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5159 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5160 return R;
5161 if (isa<PHINode>(Op0))
5162 if (Instruction *NV = FoldOpIntoPhi(I))
5163 return NV;
5164 }
5165
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005166 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005167 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005168 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005169
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005170 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005172 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005173
5174
5175 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5176 if (Op1I) {
5177 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005178 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005179 if (A == Op0) { // B^(B|A) == (A|B)^B
5180 Op1I->swapOperands();
5181 I.swapOperands();
5182 std::swap(Op0, Op1);
5183 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5184 I.swapOperands(); // Simplified below.
5185 std::swap(Op0, Op1);
5186 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005187 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005188 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005189 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005190 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005191 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005192 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005193 if (A == Op0) { // A^(A&B) -> A^(B&A)
5194 Op1I->swapOperands();
5195 std::swap(A, B);
5196 }
5197 if (B == Op0) { // A^(B&A) -> (B&A)^A
5198 I.swapOperands(); // Simplified below.
5199 std::swap(Op0, Op1);
5200 }
5201 }
5202 }
5203
5204 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5205 if (Op0I) {
5206 Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00005207 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005208 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209 if (A == Op1) // (B|A)^B == (A|B)^B
5210 std::swap(A, B);
5211 if (B == Op1) { // (A|B)^B == A & ~B
5212 Instruction *NotB =
Dan Gohmancdff2122009-08-12 16:23:25 +00005213 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005214 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005215 }
Dan Gohmancdff2122009-08-12 16:23:25 +00005216 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005217 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005218 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattner3b874082008-11-16 05:38:51 +00005219 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmancdff2122009-08-12 16:23:25 +00005220 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005221 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005222 if (A == Op1) // (A&B)^A -> (B&A)^A
5223 std::swap(A, B);
5224 if (B == Op1 && // (B&A)^A == ~B & A
5225 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5226 Instruction *N =
Dan Gohmancdff2122009-08-12 16:23:25 +00005227 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005228 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005229 }
5230 }
5231 }
5232
5233 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5234 if (Op0I && Op1I && Op0I->isShift() &&
5235 Op0I->getOpcode() == Op1I->getOpcode() &&
5236 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5237 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5238 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005239 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005240 Op1I->getOperand(0),
5241 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005242 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005243 Op1I->getOperand(1));
5244 }
5245
5246 if (Op0I && Op1I) {
5247 Value *A, *B, *C, *D;
5248 // (A & B)^(A | B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005249 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5250 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005251 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005252 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005253 }
5254 // (A | B)^(A & B) -> A ^ B
Dan Gohmancdff2122009-08-12 16:23:25 +00005255 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5256 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005257 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005258 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005259 }
5260
5261 // (A & B)^(C & D)
5262 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00005263 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5264 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005265 // (X & Y)^(X & Y) -> (Y^Z) & X
5266 Value *X = 0, *Y = 0, *Z = 0;
5267 if (A == C)
5268 X = A, Y = B, Z = D;
5269 else if (A == D)
5270 X = A, Y = B, Z = C;
5271 else if (B == C)
5272 X = B, Y = A, Z = D;
5273 else if (B == D)
5274 X = B, Y = A, Z = C;
5275
5276 if (X) {
5277 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005278 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5279 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005280 }
5281 }
5282 }
5283
5284 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5285 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005286 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005287 return R;
5288
5289 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005290 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005291 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5292 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5293 const Type *SrcTy = Op0C->getOperand(0)->getType();
5294 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5295 // Only do this if the casts both really cause code to be generated.
5296 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5297 I.getType(), TD) &&
5298 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5299 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005300 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005301 Op1C->getOperand(0),
5302 I.getName());
5303 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005304 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005305 }
5306 }
Chris Lattner91882432007-10-24 05:38:08 +00005307 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005308
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005309 return Changed ? &I : 0;
5310}
5311
Owen Anderson24be4c12009-07-03 00:17:18 +00005312static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005313 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005314 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005315}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005316
Dan Gohman8fd520a2009-06-15 22:12:54 +00005317static bool HasAddOverflow(ConstantInt *Result,
5318 ConstantInt *In1, ConstantInt *In2,
5319 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005320 if (IsSigned)
5321 if (In2->getValue().isNegative())
5322 return Result->getValue().sgt(In1->getValue());
5323 else
5324 return Result->getValue().slt(In1->getValue());
5325 else
5326 return Result->getValue().ult(In1->getValue());
5327}
5328
Dan Gohman8fd520a2009-06-15 22:12:54 +00005329/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005330/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005331static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005332 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005333 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005334 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005335
Dan Gohman8fd520a2009-06-15 22:12:54 +00005336 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5337 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005338 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005339 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5340 ExtractElement(In1, Idx, Context),
5341 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005342 IsSigned))
5343 return true;
5344 }
5345 return false;
5346 }
5347
5348 return HasAddOverflow(cast<ConstantInt>(Result),
5349 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5350 IsSigned);
5351}
5352
5353static bool HasSubOverflow(ConstantInt *Result,
5354 ConstantInt *In1, ConstantInt *In2,
5355 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005356 if (IsSigned)
5357 if (In2->getValue().isNegative())
5358 return Result->getValue().slt(In1->getValue());
5359 else
5360 return Result->getValue().sgt(In1->getValue());
5361 else
5362 return Result->getValue().ugt(In1->getValue());
5363}
5364
Dan Gohman8fd520a2009-06-15 22:12:54 +00005365/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5366/// overflowed for this type.
5367static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005368 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005369 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005370 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005371
5372 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5373 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005374 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005375 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5376 ExtractElement(In1, Idx, Context),
5377 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005378 IsSigned))
5379 return true;
5380 }
5381 return false;
5382 }
5383
5384 return HasSubOverflow(cast<ConstantInt>(Result),
5385 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5386 IsSigned);
5387}
5388
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005389/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5390/// code necessary to compute the offset from the base pointer (without adding
5391/// in the base pointer). Return the result as a signed integer of intptr size.
5392static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005393 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005394 gep_type_iterator GTI = gep_type_begin(GEP);
5395 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson5349f052009-07-06 23:00:19 +00005396 LLVMContext *Context = IC.getContext();
Owen Andersonaac28372009-07-31 20:28:14 +00005397 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005398
5399 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005400 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005401 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5402
Gabor Greif17396002008-06-12 21:37:33 +00005403 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5404 ++i, ++GTI) {
5405 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005406 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005407 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5408 if (OpC->isZero()) continue;
5409
5410 // Handle a struct index, which adds its field offset to the pointer.
5411 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5412 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5413
5414 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005415 Result =
Owen Andersoneacb44d2009-07-24 23:12:02 +00005416 ConstantInt::get(*Context,
5417 RC->getValue() + APInt(IntPtrWidth, Size));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005418 else
5419 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005420 BinaryOperator::CreateAdd(Result,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005421 ConstantInt::get(IntPtrTy, Size),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005422 GEP->getName()+".offs"), I);
5423 continue;
5424 }
5425
Owen Andersoneacb44d2009-07-24 23:12:02 +00005426 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005427 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005428 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5429 Scale = ConstantExpr::getMul(OC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005430 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00005431 Result = ConstantExpr::getAdd(RC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005432 else {
5433 // Emit an add instruction.
5434 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005435 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005436 GEP->getName()+".offs"), I);
5437 }
5438 continue;
5439 }
5440 // Convert to correct type.
5441 if (Op->getType() != IntPtrTy) {
5442 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson02b48c32009-07-29 18:55:55 +00005443 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005444 else
Chris Lattner2941a652009-04-07 05:03:34 +00005445 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5446 true,
5447 Op->getName()+".c"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005448 }
5449 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005450 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005451 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson02b48c32009-07-29 18:55:55 +00005452 Op = ConstantExpr::getMul(OpC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005453 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005454 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005455 GEP->getName()+".idx"), I);
5456 }
5457
5458 // Emit an add instruction.
5459 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00005460 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005461 cast<Constant>(Result));
5462 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005463 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005464 GEP->getName()+".offs"), I);
5465 }
5466 return Result;
5467}
5468
Chris Lattnereba75862008-04-22 02:53:33 +00005469
Dan Gohmanff9b4732009-07-17 22:16:21 +00005470/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5471/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5472/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5473/// be complex, and scales are involved. The above expression would also be
5474/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5475/// This later form is less amenable to optimization though, and we are allowed
5476/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005477///
5478/// If we can't emit an optimized form for this expression, this returns null.
5479///
5480static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5481 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005482 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005483 gep_type_iterator GTI = gep_type_begin(GEP);
5484
5485 // Check to see if this gep only has a single variable index. If so, and if
5486 // any constant indices are a multiple of its scale, then we can compute this
5487 // in terms of the scale of the variable index. For example, if the GEP
5488 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5489 // because the expression will cross zero at the same point.
5490 unsigned i, e = GEP->getNumOperands();
5491 int64_t Offset = 0;
5492 for (i = 1; i != e; ++i, ++GTI) {
5493 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5494 // Compute the aggregate offset of constant indices.
5495 if (CI->isZero()) continue;
5496
5497 // Handle a struct index, which adds its field offset to the pointer.
5498 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5499 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5500 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005501 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005502 Offset += Size*CI->getSExtValue();
5503 }
5504 } else {
5505 // Found our variable index.
5506 break;
5507 }
5508 }
5509
5510 // If there are no variable indices, we must have a constant offset, just
5511 // evaluate it the general way.
5512 if (i == e) return 0;
5513
5514 Value *VariableIdx = GEP->getOperand(i);
5515 // Determine the scale factor of the variable element. For example, this is
5516 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005517 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005518
5519 // Verify that there are no other variable indices. If so, emit the hard way.
5520 for (++i, ++GTI; i != e; ++i, ++GTI) {
5521 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5522 if (!CI) return 0;
5523
5524 // Compute the aggregate offset of constant indices.
5525 if (CI->isZero()) continue;
5526
5527 // Handle a struct index, which adds its field offset to the pointer.
5528 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5529 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5530 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005531 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005532 Offset += Size*CI->getSExtValue();
5533 }
5534 }
5535
5536 // Okay, we know we have a single variable index, which must be a
5537 // pointer/array/vector index. If there is no offset, life is simple, return
5538 // the index.
5539 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5540 if (Offset == 0) {
5541 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5542 // we don't need to bother extending: the extension won't affect where the
5543 // computation crosses zero.
5544 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5545 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005546 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005547 return VariableIdx;
5548 }
5549
5550 // Otherwise, there is an index. The computation we will do will be modulo
5551 // the pointer size, so get it.
5552 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5553
5554 Offset &= PtrSizeMask;
5555 VariableScale &= PtrSizeMask;
5556
5557 // To do this transformation, any constant index must be a multiple of the
5558 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5559 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5560 // multiple of the variable scale.
5561 int64_t NewOffs = Offset / (int64_t)VariableScale;
5562 if (Offset != NewOffs*(int64_t)VariableScale)
5563 return 0;
5564
5565 // Okay, we can do this evaluation. Start by converting the index to intptr.
5566 const Type *IntPtrTy = TD.getIntPtrType();
5567 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005568 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005569 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005570 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005571 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005572 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005573}
5574
5575
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005576/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5577/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005578Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005579 ICmpInst::Predicate Cond,
5580 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005581 // Look through bitcasts.
5582 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5583 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005584
5585 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005586 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005587 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005588 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005589 // know pointers can't overflow since the gep is inbounds. See if we can
5590 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005591 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5592
5593 // If not, synthesize the offset the hard way.
5594 if (Offset == 0)
5595 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005596 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005597 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005598 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005599 // If the base pointers are different, but the indices are the same, just
5600 // compare the base pointer.
5601 if (PtrBase != GEPRHS->getOperand(0)) {
5602 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5603 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5604 GEPRHS->getOperand(0)->getType();
5605 if (IndicesTheSame)
5606 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5607 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5608 IndicesTheSame = false;
5609 break;
5610 }
5611
5612 // If all indices are the same, just compare the base pointers.
5613 if (IndicesTheSame)
Owen Anderson6601fcd2009-07-09 23:48:35 +00005614 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005615 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5616
5617 // Otherwise, the base pointers are different and the indices are
5618 // different, bail out.
5619 return 0;
5620 }
5621
5622 // If one of the GEPs has all zero indices, recurse.
5623 bool AllZeros = true;
5624 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5625 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5626 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5627 AllZeros = false;
5628 break;
5629 }
5630 if (AllZeros)
5631 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5632 ICmpInst::getSwappedPredicate(Cond), I);
5633
5634 // If the other GEP has all zero indices, recurse.
5635 AllZeros = true;
5636 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5637 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5638 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5639 AllZeros = false;
5640 break;
5641 }
5642 if (AllZeros)
5643 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5644
5645 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5646 // If the GEPs only differ by one index, compare it.
5647 unsigned NumDifferences = 0; // Keep track of # differences.
5648 unsigned DiffOperand = 0; // The operand that differs.
5649 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5650 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5651 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5652 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5653 // Irreconcilable differences.
5654 NumDifferences = 2;
5655 break;
5656 } else {
5657 if (NumDifferences++) break;
5658 DiffOperand = i;
5659 }
5660 }
5661
5662 if (NumDifferences == 0) // SAME GEP?
5663 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneacb44d2009-07-24 23:12:02 +00005664 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005665 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005666
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005667 else if (NumDifferences == 1) {
5668 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5669 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5670 // Make sure we do a signed comparison here.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005671 return new ICmpInst(*Context,
5672 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005673 }
5674 }
5675
5676 // Only lower this if the icmp is the only user of the GEP or if we expect
5677 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005678 if (TD &&
5679 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005680 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5681 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5682 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5683 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005684 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005685 }
5686 }
5687 return 0;
5688}
5689
Chris Lattnere6b62d92008-05-19 20:18:56 +00005690/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5691///
5692Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5693 Instruction *LHSI,
5694 Constant *RHSC) {
5695 if (!isa<ConstantFP>(RHSC)) return 0;
5696 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5697
5698 // Get the width of the mantissa. We don't want to hack on conversions that
5699 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005700 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005701 if (MantissaWidth == -1) return 0; // Unknown.
5702
5703 // Check to see that the input is converted from an integer type that is small
5704 // enough that preserves all bits. TODO: check here for "known" sign bits.
5705 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005706 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005707
5708 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005709 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5710 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005711 ++InputSize;
5712
5713 // If the conversion would lose info, don't hack on this.
5714 if ((int)InputSize > MantissaWidth)
5715 return 0;
5716
5717 // Otherwise, we can potentially simplify the comparison. We know that it
5718 // will always come through as an integer value and we know the constant is
5719 // not a NAN (it would have been previously simplified).
5720 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5721
5722 ICmpInst::Predicate Pred;
5723 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005724 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005725 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005726 case FCmpInst::FCMP_OEQ:
5727 Pred = ICmpInst::ICMP_EQ;
5728 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005729 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005730 case FCmpInst::FCMP_OGT:
5731 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5732 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005733 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005734 case FCmpInst::FCMP_OGE:
5735 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5736 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005737 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005738 case FCmpInst::FCMP_OLT:
5739 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5740 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005741 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005742 case FCmpInst::FCMP_OLE:
5743 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5744 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005745 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005746 case FCmpInst::FCMP_ONE:
5747 Pred = ICmpInst::ICMP_NE;
5748 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005749 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005750 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005751 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005752 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005753 }
5754
5755 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5756
5757 // Now we know that the APFloat is a normal number, zero or inf.
5758
Chris Lattnerf13ff492008-05-20 03:50:52 +00005759 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005760 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005761 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005762
Bill Wendling20636df2008-11-09 04:26:50 +00005763 if (!LHSUnsigned) {
5764 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5765 // and large values.
5766 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5767 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5768 APFloat::rmNearestTiesToEven);
5769 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5770 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5771 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005772 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5773 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005774 }
5775 } else {
5776 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5777 // +INF and large values.
5778 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5779 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5780 APFloat::rmNearestTiesToEven);
5781 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5782 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5783 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005784 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5785 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005786 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005787 }
5788
Bill Wendling20636df2008-11-09 04:26:50 +00005789 if (!LHSUnsigned) {
5790 // See if the RHS value is < SignedMin.
5791 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5792 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5793 APFloat::rmNearestTiesToEven);
5794 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5795 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5796 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005797 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5798 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005799 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005800 }
5801
Bill Wendling20636df2008-11-09 04:26:50 +00005802 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5803 // [0, UMAX], but it may still be fractional. See if it is fractional by
5804 // casting the FP value to the integer value and back, checking for equality.
5805 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005806 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005807 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5808 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005809 if (!RHS.isZero()) {
5810 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005811 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5812 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005813 if (!Equal) {
5814 // If we had a comparison against a fractional value, we have to adjust
5815 // the compare predicate and sometimes the value. RHSC is rounded towards
5816 // zero at this point.
5817 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005818 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005819 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005820 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005821 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005822 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005823 case ICmpInst::ICMP_ULE:
5824 // (float)int <= 4.4 --> int <= 4
5825 // (float)int <= -4.4 --> false
5826 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005827 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005828 break;
5829 case ICmpInst::ICMP_SLE:
5830 // (float)int <= 4.4 --> int <= 4
5831 // (float)int <= -4.4 --> int < -4
5832 if (RHS.isNegative())
5833 Pred = ICmpInst::ICMP_SLT;
5834 break;
5835 case ICmpInst::ICMP_ULT:
5836 // (float)int < -4.4 --> false
5837 // (float)int < 4.4 --> int <= 4
5838 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005840 Pred = ICmpInst::ICMP_ULE;
5841 break;
5842 case ICmpInst::ICMP_SLT:
5843 // (float)int < -4.4 --> int < -4
5844 // (float)int < 4.4 --> int <= 4
5845 if (!RHS.isNegative())
5846 Pred = ICmpInst::ICMP_SLE;
5847 break;
5848 case ICmpInst::ICMP_UGT:
5849 // (float)int > 4.4 --> int > 4
5850 // (float)int > -4.4 --> true
5851 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005852 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005853 break;
5854 case ICmpInst::ICMP_SGT:
5855 // (float)int > 4.4 --> int > 4
5856 // (float)int > -4.4 --> int >= -4
5857 if (RHS.isNegative())
5858 Pred = ICmpInst::ICMP_SGE;
5859 break;
5860 case ICmpInst::ICMP_UGE:
5861 // (float)int >= -4.4 --> true
5862 // (float)int >= 4.4 --> int > 4
5863 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005864 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005865 Pred = ICmpInst::ICMP_UGT;
5866 break;
5867 case ICmpInst::ICMP_SGE:
5868 // (float)int >= -4.4 --> int >= -4
5869 // (float)int >= 4.4 --> int > 4
5870 if (!RHS.isNegative())
5871 Pred = ICmpInst::ICMP_SGT;
5872 break;
5873 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005874 }
5875 }
5876
5877 // Lower this FP comparison into an appropriate integer version of the
5878 // comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005879 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005880}
5881
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005882Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5883 bool Changed = SimplifyCompare(I);
5884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5885
5886 // Fold trivial predicates.
5887 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005889 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005890 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005891
5892 // Simplify 'fcmp pred X, X'
5893 if (Op0 == Op1) {
5894 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005895 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005896 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5897 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5898 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson4f720fa2009-07-31 17:39:07 +00005899 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005900 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5901 case FCmpInst::FCMP_OLT: // True if ordered and less than
5902 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson4f720fa2009-07-31 17:39:07 +00005903 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005904
5905 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5906 case FCmpInst::FCMP_ULT: // True if unordered or less than
5907 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5908 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5909 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5910 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005911 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005912 return &I;
5913
5914 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5915 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5916 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5917 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5918 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5919 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005920 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005921 return &I;
5922 }
5923 }
5924
5925 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersonb99ecca2009-07-30 23:03:37 +00005926 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005927
5928 // Handle fcmp with constant RHS
5929 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005930 // If the constant is a nan, see if we can fold the comparison based on it.
5931 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5932 if (CFP->getValueAPF().isNaN()) {
5933 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005934 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005935 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5936 "Comparison must be either ordered or unordered!");
5937 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005938 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005939 }
5940 }
5941
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005942 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5943 switch (LHSI->getOpcode()) {
5944 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005945 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5946 // block. If in the same block, we're encouraging jump threading. If
5947 // not, we are just pessimizing the code by making an i1 phi.
5948 if (LHSI->getParent() == I.getParent())
5949 if (Instruction *NV = FoldOpIntoPhi(I))
5950 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005951 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005952 case Instruction::SIToFP:
5953 case Instruction::UIToFP:
5954 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5955 return NV;
5956 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005957 case Instruction::Select:
5958 // If either operand of the select is a constant, we can fold the
5959 // comparison into the select arms, which will cause one to be
5960 // constant folded and the select turned into a bitwise or.
5961 Value *Op1 = 0, *Op2 = 0;
5962 if (LHSI->hasOneUse()) {
5963 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5964 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005965 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005966 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005967 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005968 LHSI->getOperand(2), RHSC,
5969 I.getName()), I);
5970 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5971 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005972 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005973 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005974 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005975 LHSI->getOperand(1), RHSC,
5976 I.getName()), I);
5977 }
5978 }
5979
5980 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005981 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005982 break;
5983 }
5984 }
5985
5986 return Changed ? &I : 0;
5987}
5988
5989Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5990 bool Changed = SimplifyCompare(I);
5991 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5992 const Type *Ty = Op0->getType();
5993
5994 // icmp X, X
5995 if (Op0 == Op1)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005996 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005997 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005998
5999 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersonb99ecca2009-07-30 23:03:37 +00006000 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00006001
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006002 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6003 // addresses never equal each other! We already know that Op0 != Op1.
6004 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6005 isa<ConstantPointerNull>(Op0)) &&
6006 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6007 isa<ConstantPointerNull>(Op1)))
Owen Andersoneacb44d2009-07-24 23:12:02 +00006008 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006009 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006010
6011 // icmp's with boolean values can always be turned into bitwise operations
6012 if (Ty == Type::Int1Ty) {
6013 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006014 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006015 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00006016 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006017 InsertNewInstBefore(Xor, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00006018 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006019 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006020 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006021 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006022
6023 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006024 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006025 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006026 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Dan Gohmancdff2122009-08-12 16:23:25 +00006027 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006028 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006029 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006030 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006031 case ICmpInst::ICMP_SGT:
6032 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006033 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006034 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Dan Gohmancdff2122009-08-12 16:23:25 +00006035 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006036 InsertNewInstBefore(Not, I);
6037 return BinaryOperator::CreateAnd(Not, Op0);
6038 }
6039 case ICmpInst::ICMP_UGE:
6040 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6041 // FALL THROUGH
6042 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Dan Gohmancdff2122009-08-12 16:23:25 +00006043 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006044 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006045 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006046 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006047 case ICmpInst::ICMP_SGE:
6048 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6049 // FALL THROUGH
6050 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Dan Gohmancdff2122009-08-12 16:23:25 +00006051 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006052 InsertNewInstBefore(Not, I);
6053 return BinaryOperator::CreateOr(Not, Op0);
6054 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006055 }
6056 }
6057
Dan Gohman7934d592009-04-25 17:12:48 +00006058 unsigned BitWidth = 0;
6059 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006060 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6061 else if (Ty->isIntOrIntVector())
6062 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006063
6064 bool isSignBit = false;
6065
Dan Gohman58c09632008-09-16 18:46:06 +00006066 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006068 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006069
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006070 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6071 if (I.isEquality() && CI->isNullValue() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006072 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006073 // (icmp cond A B) if cond is equality
Owen Anderson6601fcd2009-07-09 23:48:35 +00006074 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006075 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006076
Dan Gohman58c09632008-09-16 18:46:06 +00006077 // If we have an icmp le or icmp ge instruction, turn it into the
6078 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6079 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006080 switch (I.getPredicate()) {
6081 default: break;
6082 case ICmpInst::ICMP_ULE:
6083 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006084 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006085 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006086 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006087 case ICmpInst::ICMP_SLE:
6088 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006089 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006090 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006091 AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006092 case ICmpInst::ICMP_UGE:
6093 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006094 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006095 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006096 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006097 case ICmpInst::ICMP_SGE:
6098 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006099 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006100 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006101 SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00006102 }
6103
Chris Lattnera1308652008-07-11 05:40:05 +00006104 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006105 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006106 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006107 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6108 }
6109
6110 // See if we can fold the comparison based on range information we can get
6111 // by checking whether bits are known to be zero or one in the input.
6112 if (BitWidth != 0) {
6113 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6114 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6115
6116 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006117 isSignBit ? APInt::getSignBit(BitWidth)
6118 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006119 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006120 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006121 if (SimplifyDemandedBits(I.getOperandUse(1),
6122 APInt::getAllOnesValue(BitWidth),
6123 Op1KnownZero, Op1KnownOne, 0))
6124 return &I;
6125
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006126 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006127 // in. Compute the Min, Max and RHS values based on the known bits. For the
6128 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006129 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6130 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6131 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6132 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6133 Op0Min, Op0Max);
6134 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6135 Op1Min, Op1Max);
6136 } else {
6137 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6138 Op0Min, Op0Max);
6139 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6140 Op1Min, Op1Max);
6141 }
6142
Chris Lattnera1308652008-07-11 05:40:05 +00006143 // If Min and Max are known to be the same, then SimplifyDemandedBits
6144 // figured out that the LHS is a constant. Just constant fold this now so
6145 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006146 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006147 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006148 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006149 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006150 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006151 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006152
Chris Lattnera1308652008-07-11 05:40:05 +00006153 // Based on the range information we know about the LHS, see if we can
6154 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006155 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006156 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006157 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006158 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006159 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006160 break;
6161 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006162 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006163 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006164 break;
6165 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006166 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006167 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006168 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006169 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006170 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006171 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006172 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6173 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006174 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006175 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006176
6177 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6178 if (CI->isMinValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006179 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006180 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006181 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006182 break;
6183 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006184 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006185 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006186 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006187 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006188
6189 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006190 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006191 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6192 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006193 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006194 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006195
6196 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6197 if (CI->isMaxValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006198 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006199 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006200 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006201 break;
6202 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006203 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006204 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006205 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006206 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006207 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006208 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006209 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6210 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006211 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006212 SubOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006213 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006214 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006215 case ICmpInst::ICMP_SGT:
6216 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006217 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006218 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006219 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006220
6221 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006222 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006223 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6224 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006225 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006226 AddOne(CI));
Dan Gohman7934d592009-04-25 17:12:48 +00006227 }
6228 break;
6229 case ICmpInst::ICMP_SGE:
6230 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6231 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006232 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006233 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006234 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006235 break;
6236 case ICmpInst::ICMP_SLE:
6237 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6238 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006239 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006240 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006241 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006242 break;
6243 case ICmpInst::ICMP_UGE:
6244 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6245 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006246 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006247 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006248 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006249 break;
6250 case ICmpInst::ICMP_ULE:
6251 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6252 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006253 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006254 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006255 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006256 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006257 }
Dan Gohman7934d592009-04-25 17:12:48 +00006258
6259 // Turn a signed comparison into an unsigned one if both operands
6260 // are known to have the same sign.
6261 if (I.isSignedPredicate() &&
6262 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6263 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006264 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006265 }
6266
6267 // Test if the ICmpInst instruction is used exclusively by a select as
6268 // part of a minimum or maximum operation. If so, refrain from doing
6269 // any other folding. This helps out other analyses which understand
6270 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6271 // and CodeGen. And in this case, at least one of the comparison
6272 // operands has at least one user besides the compare (the select),
6273 // which would often largely negate the benefit of folding anyway.
6274 if (I.hasOneUse())
6275 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6276 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6277 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6278 return 0;
6279
6280 // See if we are doing a comparison between a constant and an instruction that
6281 // can be folded into the comparison.
6282 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006283 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6284 // instruction, see if that instruction also has constants so that the
6285 // instruction can be folded into the icmp
6286 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6288 return Res;
6289 }
6290
6291 // Handle icmp with constant (but not simple integer constant) RHS
6292 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6293 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6294 switch (LHSI->getOpcode()) {
6295 case Instruction::GetElementPtr:
6296 if (RHSC->isNullValue()) {
6297 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6298 bool isAllZeros = true;
6299 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6300 if (!isa<Constant>(LHSI->getOperand(i)) ||
6301 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6302 isAllZeros = false;
6303 break;
6304 }
6305 if (isAllZeros)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006306 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006307 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006308 }
6309 break;
6310
6311 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006312 // Only fold icmp into the PHI if the phi and fcmp are in the same
6313 // block. If in the same block, we're encouraging jump threading. If
6314 // not, we are just pessimizing the code by making an i1 phi.
6315 if (LHSI->getParent() == I.getParent())
6316 if (Instruction *NV = FoldOpIntoPhi(I))
6317 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006318 break;
6319 case Instruction::Select: {
6320 // If either operand of the select is a constant, we can fold the
6321 // comparison into the select arms, which will cause one to be
6322 // constant folded and the select turned into a bitwise or.
6323 Value *Op1 = 0, *Op2 = 0;
6324 if (LHSI->hasOneUse()) {
6325 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6326 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006327 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006328 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006329 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006330 LHSI->getOperand(2), RHSC,
6331 I.getName()), I);
6332 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6333 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006334 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006335 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006336 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006337 LHSI->getOperand(1), RHSC,
6338 I.getName()), I);
6339 }
6340 }
6341
6342 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006343 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006344 break;
6345 }
6346 case Instruction::Malloc:
6347 // If we have (malloc != null), and if the malloc has a single use, we
6348 // can assume it is successful and remove the malloc.
6349 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6350 AddToWorkList(LHSI);
Owen Andersoneacb44d2009-07-24 23:12:02 +00006351 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006352 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006353 }
6354 break;
6355 }
6356 }
6357
6358 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006359 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006360 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6361 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006362 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006363 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6364 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6365 return NI;
6366
6367 // Test to see if the operands of the icmp are casted versions of other
6368 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6369 // now.
6370 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6371 if (isa<PointerType>(Op0->getType()) &&
6372 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6373 // We keep moving the cast from the left operand over to the right
6374 // operand, where it can often be eliminated completely.
6375 Op0 = CI->getOperand(0);
6376
6377 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6378 // so eliminate it as well.
6379 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6380 Op1 = CI2->getOperand(0);
6381
6382 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006383 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006384 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006385 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006386 } else {
6387 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006388 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006389 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006390 }
Owen Anderson6601fcd2009-07-09 23:48:35 +00006391 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006392 }
6393 }
6394
6395 if (isa<CastInst>(Op0)) {
6396 // Handle the special case of: icmp (cast bool to X), <cst>
6397 // This comes up when you have code like
6398 // int X = A < B;
6399 // if (X) ...
6400 // For generality, we handle any zero-extension of any operand comparison
6401 // with a constant or another cast from the same type.
6402 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6403 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6404 return R;
6405 }
6406
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006407 // See if it's the same type of instruction on the left and right.
6408 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6409 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006410 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006411 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006412 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006413 default: break;
6414 case Instruction::Add:
6415 case Instruction::Sub:
6416 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006417 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson6601fcd2009-07-09 23:48:35 +00006418 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006419 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006420 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6421 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6422 if (CI->getValue().isSignBit()) {
6423 ICmpInst::Predicate Pred = I.isSignedPredicate()
6424 ? I.getUnsignedPredicate()
6425 : I.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006426 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006427 Op1I->getOperand(0));
6428 }
6429
6430 if (CI->getValue().isMaxSignedValue()) {
6431 ICmpInst::Predicate Pred = I.isSignedPredicate()
6432 ? I.getUnsignedPredicate()
6433 : I.getSignedPredicate();
6434 Pred = I.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006435 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006436 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006437 }
6438 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006439 break;
6440 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006441 if (!I.isEquality())
6442 break;
6443
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006444 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6445 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6446 // Mask = -1 >> count-trailing-zeros(Cst).
6447 if (!CI->isZero() && !CI->isOne()) {
6448 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006449 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006450 APInt::getLowBitsSet(AP.getBitWidth(),
6451 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006452 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006453 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6454 Mask);
6455 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6456 Mask);
6457 InsertNewInstBefore(And1, I);
6458 InsertNewInstBefore(And2, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006459 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006460 }
6461 }
6462 break;
6463 }
6464 }
6465 }
6466 }
6467
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006468 // ~x < ~y --> y < x
6469 { Value *A, *B;
Dan Gohmancdff2122009-08-12 16:23:25 +00006470 if (match(Op0, m_Not(m_Value(A))) &&
6471 match(Op1, m_Not(m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006472 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006473 }
6474
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006475 if (I.isEquality()) {
6476 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006477
6478 // -x == -y --> x == y
Dan Gohmancdff2122009-08-12 16:23:25 +00006479 if (match(Op0, m_Neg(m_Value(A))) &&
6480 match(Op1, m_Neg(m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006481 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006482
Dan Gohmancdff2122009-08-12 16:23:25 +00006483 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006484 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6485 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006486 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006487 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006488 }
6489
Dan Gohmancdff2122009-08-12 16:23:25 +00006490 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006491 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006492 ConstantInt *C1, *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00006493 if (match(B, m_ConstantInt(C1)) &&
6494 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006495 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006496 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner3b874082008-11-16 05:38:51 +00006497 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson6601fcd2009-07-09 23:48:35 +00006498 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattner3b874082008-11-16 05:38:51 +00006499 InsertNewInstBefore(Xor, I));
6500 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006501
6502 // A^B == A^D -> B == D
Owen Anderson6601fcd2009-07-09 23:48:35 +00006503 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6504 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6505 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6506 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006507 }
6508 }
6509
Dan Gohmancdff2122009-08-12 16:23:25 +00006510 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006511 (A == Op0 || B == Op0)) {
6512 // A == (A^B) -> B == 0
6513 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006514 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006515 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006516 }
Chris Lattner3b874082008-11-16 05:38:51 +00006517
6518 // (A-B) == A -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006519 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006520 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006521 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006522
6523 // A == (A-B) -> B == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00006524 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006525 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006526 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006527
6528 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6529 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00006530 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6531 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006532 Value *X = 0, *Y = 0, *Z = 0;
6533
6534 if (A == C) {
6535 X = B; Y = D; Z = A;
6536 } else if (A == D) {
6537 X = B; Y = C; Z = A;
6538 } else if (B == C) {
6539 X = A; Y = D; Z = B;
6540 } else if (B == D) {
6541 X = A; Y = C; Z = B;
6542 }
6543
6544 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006545 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6546 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006547 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006548 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006549 return &I;
6550 }
6551 }
6552 }
6553 return Changed ? &I : 0;
6554}
6555
6556
6557/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6558/// and CmpRHS are both known to be integer constants.
6559Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6560 ConstantInt *DivRHS) {
6561 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6562 const APInt &CmpRHSV = CmpRHS->getValue();
6563
6564 // FIXME: If the operand types don't match the type of the divide
6565 // then don't attempt this transform. The code below doesn't have the
6566 // logic to deal with a signed divide and an unsigned compare (and
6567 // vice versa). This is because (x /s C1) <s C2 produces different
6568 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6569 // (x /u C1) <u C2. Simply casting the operands and result won't
6570 // work. :( The if statement below tests that condition and bails
6571 // if it finds it.
6572 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6573 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6574 return 0;
6575 if (DivRHS->isZero())
6576 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006577 if (DivIsSigned && DivRHS->isAllOnesValue())
6578 return 0; // The overflow computation also screws up here
6579 if (DivRHS->isOne())
6580 return 0; // Not worth bothering, and eliminates some funny cases
6581 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006582
6583 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6584 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6585 // C2 (CI). By solving for X we can turn this into a range check
6586 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006587 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006588
6589 // Determine if the product overflows by seeing if the product is
6590 // not equal to the divide. Make sure we do the same kind of divide
6591 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006592 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6593 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006594
6595 // Get the ICmp opcode
6596 ICmpInst::Predicate Pred = ICI.getPredicate();
6597
6598 // Figure out the interval that is being checked. For example, a comparison
6599 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6600 // Compute this interval based on the constants involved and the signedness of
6601 // the compare/divide. This computes a half-open interval, keeping track of
6602 // whether either value in the interval overflows. After analysis each
6603 // overflow variable is set to 0 if it's corresponding bound variable is valid
6604 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6605 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006606 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006607
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006608 if (!DivIsSigned) { // udiv
6609 // e.g. X/5 op 3 --> [15, 20)
6610 LoBound = Prod;
6611 HiOverflow = LoOverflow = ProdOV;
6612 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006613 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006614 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006615 if (CmpRHSV == 0) { // (X / pos) op 0
6616 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006617 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006619 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006620 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6621 HiOverflow = LoOverflow = ProdOV;
6622 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006623 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006624 } else { // (X / pos) op neg
6625 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006626 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006627 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6628 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006629 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006630 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006631 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006632 true) ? -1 : 0;
6633 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006635 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006636 if (CmpRHSV == 0) { // (X / neg) op 0
6637 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006638 LoBound = AddOne(DivRHS);
Owen Anderson02b48c32009-07-29 18:55:55 +00006639 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006640 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6641 HiOverflow = 1; // [INTMIN+1, overflow)
6642 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6643 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006644 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006645 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006646 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006647 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6648 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006649 LoOverflow = AddWithOverflow(LoBound, HiBound,
6650 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006651 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006652 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6653 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006654 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006655 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006656 }
6657
6658 // Dividing by a negative swaps the condition. LT <-> GT
6659 Pred = ICmpInst::getSwappedPredicate(Pred);
6660 }
6661
6662 Value *X = DivI->getOperand(0);
6663 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006664 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006665 case ICmpInst::ICMP_EQ:
6666 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006667 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006668 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006669 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670 ICmpInst::ICMP_UGE, X, LoBound);
6671 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006672 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006673 ICmpInst::ICMP_ULT, X, HiBound);
6674 else
6675 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6676 case ICmpInst::ICMP_NE:
6677 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006678 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006679 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006680 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006681 ICmpInst::ICMP_ULT, X, LoBound);
6682 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006683 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006684 ICmpInst::ICMP_UGE, X, HiBound);
6685 else
6686 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6687 case ICmpInst::ICMP_ULT:
6688 case ICmpInst::ICMP_SLT:
6689 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006690 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006691 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006692 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006693 return new ICmpInst(*Context, Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006694 case ICmpInst::ICMP_UGT:
6695 case ICmpInst::ICMP_SGT:
6696 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006697 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006698 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006699 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006700 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006701 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006702 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006703 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006704 }
6705}
6706
6707
6708/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6709///
6710Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6711 Instruction *LHSI,
6712 ConstantInt *RHS) {
6713 const APInt &RHSV = RHS->getValue();
6714
6715 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006716 case Instruction::Trunc:
6717 if (ICI.isEquality() && LHSI->hasOneUse()) {
6718 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6719 // of the high bits truncated out of x are known.
6720 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6721 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6722 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6723 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6724 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6725
6726 // If all the high bits are known, we can do this xform.
6727 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6728 // Pull in the high bits from known-ones set.
6729 APInt NewRHS(RHS->getValue());
6730 NewRHS.zext(SrcBits);
6731 NewRHS |= KnownOne;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006732 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006733 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006734 }
6735 }
6736 break;
6737
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006738 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6739 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6740 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6741 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006742 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6743 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006744 Value *CompareVal = LHSI->getOperand(0);
6745
6746 // If the sign bit of the XorCST is not set, there is no change to
6747 // the operation, just stop using the Xor.
6748 if (!XorCST->getValue().isNegative()) {
6749 ICI.setOperand(0, CompareVal);
6750 AddToWorkList(LHSI);
6751 return &ICI;
6752 }
6753
6754 // Was the old condition true if the operand is positive?
6755 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6756
6757 // If so, the new one isn't.
6758 isTrueIfPositive ^= true;
6759
6760 if (isTrueIfPositive)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006761 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006762 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006763 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006764 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006765 AddOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006766 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006767
6768 if (LHSI->hasOneUse()) {
6769 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6770 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6771 const APInt &SignBit = XorCST->getValue();
6772 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6773 ? ICI.getUnsignedPredicate()
6774 : ICI.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006775 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006776 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006777 }
6778
6779 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006780 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006781 const APInt &NotSignBit = XorCST->getValue();
6782 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6783 ? ICI.getUnsignedPredicate()
6784 : ICI.getSignedPredicate();
6785 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006786 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006787 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006788 }
6789 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006790 }
6791 break;
6792 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6793 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6794 LHSI->getOperand(0)->hasOneUse()) {
6795 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6796
6797 // If the LHS is an AND of a truncating cast, we can widen the
6798 // and/compare to be the input width without changing the value
6799 // produced, eliminating a cast.
6800 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6801 // We can do this transformation if either the AND constant does not
6802 // have its sign bit set or if it is an equality comparison.
6803 // Extending a relational comparison when we're checking the sign
6804 // bit would not work.
6805 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006806 (ICI.isEquality() ||
6807 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006808 uint32_t BitWidth =
6809 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6810 APInt NewCST = AndCST->getValue();
6811 NewCST.zext(BitWidth);
6812 APInt NewCI = RHSV;
6813 NewCI.zext(BitWidth);
6814 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006815 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006816 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006817 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006818 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006819 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006820 }
6821 }
6822
6823 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6824 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6825 // happens a LOT in code produced by the C front-end, for bitfield
6826 // access.
6827 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6828 if (Shift && !Shift->isShift())
6829 Shift = 0;
6830
6831 ConstantInt *ShAmt;
6832 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6833 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6834 const Type *AndTy = AndCST->getType(); // Type of the and.
6835
6836 // We can fold this as long as we can't shift unknown bits
6837 // into the mask. This can only happen with signed shift
6838 // rights, as they sign-extend.
6839 if (ShAmt) {
6840 bool CanFold = Shift->isLogicalShift();
6841 if (!CanFold) {
6842 // To test for the bad case of the signed shr, see if any
6843 // of the bits shifted in could be tested after the mask.
6844 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6845 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6846
6847 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6848 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6849 AndCST->getValue()) == 0)
6850 CanFold = true;
6851 }
6852
6853 if (CanFold) {
6854 Constant *NewCst;
6855 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006856 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006857 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006858 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006859
6860 // Check to see if we are shifting out any of the bits being
6861 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006862 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006863 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006864 // If we shifted bits out, the fold is not going to work out.
6865 // As a special case, check to see if this means that the
6866 // result is always true or false now.
6867 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006868 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006869 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006870 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006871 } else {
6872 ICI.setOperand(1, NewCst);
6873 Constant *NewAndCST;
6874 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006875 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006876 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006877 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006878 LHSI->setOperand(1, NewAndCST);
6879 LHSI->setOperand(0, Shift->getOperand(0));
6880 AddToWorkList(Shift); // Shift is dead.
6881 AddUsesToWorkList(ICI);
6882 return &ICI;
6883 }
6884 }
6885 }
6886
6887 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6888 // preferable because it allows the C<<Y expression to be hoisted out
6889 // of a loop if Y is invariant and X is not.
6890 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006891 ICI.isEquality() && !Shift->isArithmeticShift() &&
6892 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006893 // Compute C << Y.
6894 Value *NS;
6895 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006896 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006897 Shift->getOperand(1), "tmp");
6898 } else {
6899 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006900 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006901 Shift->getOperand(1), "tmp");
6902 }
6903 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6904
6905 // Compute X & (C << Y).
6906 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006907 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006908 InsertNewInstBefore(NewAnd, ICI);
6909
6910 ICI.setOperand(0, NewAnd);
6911 return &ICI;
6912 }
6913 }
6914 break;
6915
6916 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6917 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6918 if (!ShAmt) break;
6919
6920 uint32_t TypeBits = RHSV.getBitWidth();
6921
6922 // Check that the shift amount is in range. If not, don't perform
6923 // undefined shifts. When the shift is visited it will be
6924 // simplified.
6925 if (ShAmt->uge(TypeBits))
6926 break;
6927
6928 if (ICI.isEquality()) {
6929 // If we are comparing against bits always shifted out, the
6930 // comparison cannot succeed.
6931 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006932 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006933 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006934 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6935 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneacb44d2009-07-24 23:12:02 +00006936 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006937 return ReplaceInstUsesWith(ICI, Cst);
6938 }
6939
6940 if (LHSI->hasOneUse()) {
6941 // Otherwise strength reduce the shift into an and.
6942 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6943 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006944 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006945 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006946
6947 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006948 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949 Mask, LHSI->getName()+".mask");
6950 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006951 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006952 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006953 }
6954 }
6955
6956 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6957 bool TrueIfSigned = false;
6958 if (LHSI->hasOneUse() &&
6959 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6960 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006961 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006962 (TypeBits-ShAmt->getZExtValue()-1));
6963 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006964 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006965 Mask, LHSI->getName()+".mask");
6966 Value *And = InsertNewInstBefore(AndI, ICI);
6967
Owen Anderson6601fcd2009-07-09 23:48:35 +00006968 return new ICmpInst(*Context,
6969 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006970 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006971 }
6972 break;
6973 }
6974
6975 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6976 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006977 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006978 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006979 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006980
Chris Lattner5ee84f82008-03-21 05:19:58 +00006981 // Check that the shift amount is in range. If not, don't perform
6982 // undefined shifts. When the shift is visited it will be
6983 // simplified.
6984 uint32_t TypeBits = RHSV.getBitWidth();
6985 if (ShAmt->uge(TypeBits))
6986 break;
6987
6988 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006989
Chris Lattner5ee84f82008-03-21 05:19:58 +00006990 // If we are comparing against bits always shifted out, the
6991 // comparison cannot succeed.
6992 APInt Comp = RHSV << ShAmtVal;
6993 if (LHSI->getOpcode() == Instruction::LShr)
6994 Comp = Comp.lshr(ShAmtVal);
6995 else
6996 Comp = Comp.ashr(ShAmtVal);
6997
6998 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6999 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneacb44d2009-07-24 23:12:02 +00007000 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00007001 return ReplaceInstUsesWith(ICI, Cst);
7002 }
7003
7004 // Otherwise, check to see if the bits shifted out are known to be zero.
7005 // If so, we can compare against the unshifted value:
7006 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007007 if (LHSI->hasOneUse() &&
7008 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007009 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007010 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007011 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007012 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007013
Evan Chengfb9292a2008-04-23 00:38:06 +00007014 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007015 // Otherwise strength reduce the shift into an and.
7016 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007017 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007018
Chris Lattner5ee84f82008-03-21 05:19:58 +00007019 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00007020 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007021 Mask, LHSI->getName()+".mask");
7022 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007023 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007024 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007025 }
7026 break;
7027 }
7028
7029 case Instruction::SDiv:
7030 case Instruction::UDiv:
7031 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7032 // Fold this div into the comparison, producing a range check.
7033 // Determine, based on the divide type, what the range is being
7034 // checked. If there is an overflow on the low or high side, remember
7035 // it, otherwise compute the range [low, hi) bounding the new value.
7036 // See: InsertRangeTest above for the kinds of replacements possible.
7037 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7038 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7039 DivRHS))
7040 return R;
7041 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007042
7043 case Instruction::Add:
7044 // Fold: icmp pred (add, X, C1), C2
7045
7046 if (!ICI.isEquality()) {
7047 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7048 if (!LHSC) break;
7049 const APInt &LHSV = LHSC->getValue();
7050
7051 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7052 .subtract(LHSV);
7053
7054 if (ICI.isSignedPredicate()) {
7055 if (CR.getLower().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007056 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007057 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007058 } else if (CR.getUpper().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007059 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007060 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007061 }
7062 } else {
7063 if (CR.getLower().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007064 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007065 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007066 } else if (CR.getUpper().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007067 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007068 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007069 }
7070 }
7071 }
7072 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007073 }
7074
7075 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7076 if (ICI.isEquality()) {
7077 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7078
7079 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7080 // the second operand is a constant, simplify a bit.
7081 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7082 switch (BO->getOpcode()) {
7083 case Instruction::SRem:
7084 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7085 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7086 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7087 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7088 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00007089 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007090 BO->getName());
7091 InsertNewInstBefore(NewRem, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007092 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007093 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007094 }
7095 }
7096 break;
7097 case Instruction::Add:
7098 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7099 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7100 if (BO->hasOneUse())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007101 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007102 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007103 } else if (RHSV == 0) {
7104 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7105 // efficiently invertible, or if the add has just this one use.
7106 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7107
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007108 if (Value *NegVal = dyn_castNegVal(BOp1))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007109 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007110 else if (Value *NegVal = dyn_castNegVal(BOp0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007111 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007112 else if (BO->hasOneUse()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00007113 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007114 InsertNewInstBefore(Neg, ICI);
7115 Neg->takeName(BO);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007116 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007117 }
7118 }
7119 break;
7120 case Instruction::Xor:
7121 // For the xor case, we can xor two constants together, eliminating
7122 // the explicit xor.
7123 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007124 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007125 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007126
7127 // FALLTHROUGH
7128 case Instruction::Sub:
7129 // Replace (([sub|xor] A, B) != 0) with (A != B)
7130 if (RHSV == 0)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007131 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007132 BO->getOperand(1));
7133 break;
7134
7135 case Instruction::Or:
7136 // If bits are being or'd in that are not present in the constant we
7137 // are comparing against, then the comparison could never succeed!
7138 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007139 Constant *NotCI = ConstantExpr::getNot(RHS);
7140 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007141 return ReplaceInstUsesWith(ICI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007142 ConstantInt::get(Type::Int1Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007143 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144 }
7145 break;
7146
7147 case Instruction::And:
7148 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7149 // If bits are being compared against that are and'd out, then the
7150 // comparison can never succeed!
7151 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007152 return ReplaceInstUsesWith(ICI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007153 ConstantInt::get(Type::Int1Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007154 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007155
7156 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7157 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007158 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007159 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007160 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007161
7162 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007163 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007164 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007165 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007166 ICmpInst::Predicate pred = isICMP_NE ?
7167 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007168 return new ICmpInst(*Context, pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007169 }
7170
7171 // ((X & ~7) == 0) --> X < 8
7172 if (RHSV == 0 && isHighOnes(BOC)) {
7173 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007174 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007175 ICmpInst::Predicate pred = isICMP_NE ?
7176 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007177 return new ICmpInst(*Context, pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007178 }
7179 }
7180 default: break;
7181 }
7182 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7183 // Handle icmp {eq|ne} <intrinsic>, intcst.
7184 if (II->getIntrinsicID() == Intrinsic::bswap) {
7185 AddToWorkList(II);
7186 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007187 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007188 return &ICI;
7189 }
7190 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007191 }
7192 return 0;
7193}
7194
7195/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7196/// We only handle extending casts so far.
7197///
7198Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7199 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7200 Value *LHSCIOp = LHSCI->getOperand(0);
7201 const Type *SrcTy = LHSCIOp->getType();
7202 const Type *DestTy = LHSCI->getType();
7203 Value *RHSCIOp;
7204
7205 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7206 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007207 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7208 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007209 cast<IntegerType>(DestTy)->getBitWidth()) {
7210 Value *RHSOp = 0;
7211 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007212 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007213 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7214 RHSOp = RHSC->getOperand(0);
7215 // If the pointer types don't match, insert a bitcast.
7216 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007217 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007218 }
7219
7220 if (RHSOp)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007221 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007222 }
7223
7224 // The code below only handles extension cast instructions, so far.
7225 // Enforce this.
7226 if (LHSCI->getOpcode() != Instruction::ZExt &&
7227 LHSCI->getOpcode() != Instruction::SExt)
7228 return 0;
7229
7230 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7231 bool isSignedCmp = ICI.isSignedPredicate();
7232
7233 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7234 // Not an extension from the same type?
7235 RHSCIOp = CI->getOperand(0);
7236 if (RHSCIOp->getType() != LHSCIOp->getType())
7237 return 0;
7238
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007239 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007240 // and the other is a zext), then we can't handle this.
7241 if (CI->getOpcode() != LHSCI->getOpcode())
7242 return 0;
7243
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007244 // Deal with equality cases early.
7245 if (ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007246 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007247
7248 // A signed comparison of sign extended values simplifies into a
7249 // signed comparison.
7250 if (isSignedCmp && isSignedExt)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007251 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007252
7253 // The other three cases all fold into an unsigned comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00007254 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007255 }
7256
7257 // If we aren't dealing with a constant on the RHS, exit early
7258 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7259 if (!CI)
7260 return 0;
7261
7262 // Compute the constant that would happen if we truncated to SrcTy then
7263 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007264 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7265 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007266 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007267
7268 // If the re-extended constant didn't change...
7269 if (Res2 == CI) {
7270 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7271 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007272 // %A = sext i16 %X to i32
7273 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007274 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007275 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007276 // because %A may have negative value.
7277 //
Chris Lattner3d816532008-07-11 04:09:09 +00007278 // However, we allow this when the compare is EQ/NE, because they are
7279 // signless.
7280 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007281 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007282 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007283 }
7284
7285 // The re-extended constant changed so the constant cannot be represented
7286 // in the shorter type. Consequently, we cannot emit a simple comparison.
7287
7288 // First, handle some easy cases. We know the result cannot be equal at this
7289 // point so handle the ICI.isEquality() cases
7290 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007291 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007292 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007293 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007294
7295 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7296 // should have been folded away previously and not enter in here.
7297 Value *Result;
7298 if (isSignedCmp) {
7299 // We're performing a signed comparison.
7300 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007301 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007302 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007303 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007304 } else {
7305 // We're performing an unsigned comparison.
7306 if (isSignedExt) {
7307 // We're performing an unsigned comp with a sign extended value.
7308 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007309 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007310 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7311 LHSCIOp, NegOne, ICI.getName()), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007312 } else {
7313 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007314 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007315 }
7316 }
7317
7318 // Finally, return the value computed.
7319 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007320 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007321 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007322
7323 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7324 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7325 "ICmp should be folded!");
7326 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007327 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007328 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007329}
7330
7331Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7332 return commonShiftTransforms(I);
7333}
7334
7335Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7336 return commonShiftTransforms(I);
7337}
7338
7339Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007340 if (Instruction *R = commonShiftTransforms(I))
7341 return R;
7342
7343 Value *Op0 = I.getOperand(0);
7344
7345 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7346 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7347 if (CSI->isAllOnesValue())
7348 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007349
Dan Gohman2526aea2009-06-16 19:55:29 +00007350 // See if we can turn a signed shr into an unsigned shr.
7351 if (MaskedValueIsZero(Op0,
7352 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7353 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7354
7355 // Arithmetic shifting an all-sign-bit value is a no-op.
7356 unsigned NumSignBits = ComputeNumSignBits(Op0);
7357 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7358 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007359
Chris Lattnere3c504f2007-12-06 01:59:46 +00007360 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007361}
7362
7363Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7364 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7365 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7366
7367 // shl X, 0 == X and shr X, 0 == X
7368 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007369 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7370 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007371 return ReplaceInstUsesWith(I, Op0);
7372
7373 if (isa<UndefValue>(Op0)) {
7374 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7375 return ReplaceInstUsesWith(I, Op0);
7376 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007377 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007378 }
7379 if (isa<UndefValue>(Op1)) {
7380 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7381 return ReplaceInstUsesWith(I, Op0);
7382 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007383 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007384 }
7385
Dan Gohman2bc21562009-05-21 02:28:33 +00007386 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007387 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007388 return &I;
7389
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390 // Try to fold constant and into select arguments.
7391 if (isa<Constant>(Op0))
7392 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7393 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7394 return R;
7395
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007396 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7397 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7398 return Res;
7399 return 0;
7400}
7401
7402Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7403 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007404 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007405
7406 // See if we can simplify any instructions used by the instruction whose sole
7407 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007408 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007409
Dan Gohman9e1657f2009-06-14 23:30:43 +00007410 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7411 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007412 //
7413 if (Op1->uge(TypeBits)) {
7414 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007415 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007416 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007417 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007418 return &I;
7419 }
7420 }
7421
7422 // ((X*C1) << C2) == (X * (C1 << C2))
7423 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7424 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7425 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007426 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007427 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007428
7429 // Try to fold constant and into select arguments.
7430 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7431 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7432 return R;
7433 if (isa<PHINode>(Op0))
7434 if (Instruction *NV = FoldOpIntoPhi(I))
7435 return NV;
7436
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007437 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7438 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7439 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7440 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7441 // place. Don't try to do this transformation in this case. Also, we
7442 // require that the input operand is a shift-by-constant so that we have
7443 // confidence that the shifts will get folded together. We could do this
7444 // xform in more cases, but it is unlikely to be profitable.
7445 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7446 isa<ConstantInt>(TrOp->getOperand(1))) {
7447 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007448 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007449 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007450 I.getName());
7451 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7452
7453 // For logical shifts, the truncation has the effect of making the high
7454 // part of the register be zeros. Emulate this by inserting an AND to
7455 // clear the top bits as needed. This 'and' will usually be zapped by
7456 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007457 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7458 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007459 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7460
7461 // The mask we constructed says what the trunc would do if occurring
7462 // between the shifts. We want to know the effect *after* the second
7463 // shift. We know that it is a logical shift by a constant, so adjust the
7464 // mask as appropriate.
7465 if (I.getOpcode() == Instruction::Shl)
7466 MaskV <<= Op1->getZExtValue();
7467 else {
7468 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7469 MaskV = MaskV.lshr(Op1->getZExtValue());
7470 }
7471
Owen Anderson24be4c12009-07-03 00:17:18 +00007472 Instruction *And =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007473 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Anderson24be4c12009-07-03 00:17:18 +00007474 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007475 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7476
7477 // Return the value truncated to the interesting size.
7478 return new TruncInst(And, I.getType());
7479 }
7480 }
7481
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007482 if (Op0->hasOneUse()) {
7483 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7484 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7485 Value *V1, *V2;
7486 ConstantInt *CC;
7487 switch (Op0BO->getOpcode()) {
7488 default: break;
7489 case Instruction::Add:
7490 case Instruction::And:
7491 case Instruction::Or:
7492 case Instruction::Xor: {
7493 // These operators commute.
7494 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7495 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007496 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007497 m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007498 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007499 Op0BO->getOperand(0), Op1,
7500 Op0BO->getName());
7501 InsertNewInstBefore(YS, I); // (Y << C)
7502 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007503 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007504 Op0BO->getOperand(1)->getName());
7505 InsertNewInstBefore(X, I); // (X + (Y << C))
7506 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007507 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007508 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7509 }
7510
7511 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7512 Value *Op0BOOp1 = Op0BO->getOperand(1);
7513 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7514 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007515 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007516 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007517 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007518 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007519 Op0BO->getOperand(0), Op1,
7520 Op0BO->getName());
7521 InsertNewInstBefore(YS, I); // (Y << C)
7522 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007523 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007524 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007525 V1->getName()+".mask");
7526 InsertNewInstBefore(XM, I); // X & (CC << C)
7527
Gabor Greifa645dd32008-05-16 19:29:10 +00007528 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007529 }
7530 }
7531
7532 // FALL THROUGH.
7533 case Instruction::Sub: {
7534 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7535 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007536 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007537 m_Specific(Op1)))) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007538 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007539 Op0BO->getOperand(1), Op1,
7540 Op0BO->getName());
7541 InsertNewInstBefore(YS, I); // (Y << C)
7542 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007543 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007544 Op0BO->getOperand(0)->getName());
7545 InsertNewInstBefore(X, I); // (X + (Y << C))
7546 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007547 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007548 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7549 }
7550
7551 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7552 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7553 match(Op0BO->getOperand(0),
7554 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007555 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007556 cast<BinaryOperator>(Op0BO->getOperand(0))
7557 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007558 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007559 Op0BO->getOperand(1), Op1,
7560 Op0BO->getName());
7561 InsertNewInstBefore(YS, I); // (Y << C)
7562 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007563 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007564 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007565 V1->getName()+".mask");
7566 InsertNewInstBefore(XM, I); // X & (CC << C)
7567
Gabor Greifa645dd32008-05-16 19:29:10 +00007568 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007569 }
7570
7571 break;
7572 }
7573 }
7574
7575
7576 // If the operand is an bitwise operator with a constant RHS, and the
7577 // shift is the only use, we can pull it out of the shift.
7578 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7579 bool isValid = true; // Valid only for And, Or, Xor
7580 bool highBitSet = false; // Transform if high bit of constant set?
7581
7582 switch (Op0BO->getOpcode()) {
7583 default: isValid = false; break; // Do not perform transform!
7584 case Instruction::Add:
7585 isValid = isLeftShift;
7586 break;
7587 case Instruction::Or:
7588 case Instruction::Xor:
7589 highBitSet = false;
7590 break;
7591 case Instruction::And:
7592 highBitSet = true;
7593 break;
7594 }
7595
7596 // If this is a signed shift right, and the high bit is modified
7597 // by the logical operation, do not perform the transformation.
7598 // The highBitSet boolean indicates the value of the high bit of
7599 // the constant which would cause it to be modified for this
7600 // operation.
7601 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007602 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007604
7605 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007606 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007607
7608 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007609 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007610 InsertNewInstBefore(NewShift, I);
7611 NewShift->takeName(Op0BO);
7612
Gabor Greifa645dd32008-05-16 19:29:10 +00007613 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007614 NewRHS);
7615 }
7616 }
7617 }
7618 }
7619
7620 // Find out if this is a shift of a shift by a constant.
7621 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7622 if (ShiftOp && !ShiftOp->isShift())
7623 ShiftOp = 0;
7624
7625 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7626 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7627 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7628 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7629 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7630 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7631 Value *X = ShiftOp->getOperand(0);
7632
7633 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007634
7635 const IntegerType *Ty = cast<IntegerType>(I.getType());
7636
7637 // Check for (X << c1) << c2 and (X >> c1) >> c2
7638 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007639 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7640 // saturates.
7641 if (AmtSum >= TypeBits) {
7642 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007643 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007644 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7645 }
7646
Gabor Greifa645dd32008-05-16 19:29:10 +00007647 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007648 ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007649 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7650 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007651 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007652 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007653
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007654 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007655 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007656 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7657 I.getOpcode() == Instruction::LShr) {
7658 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007659 if (AmtSum >= TypeBits)
7660 AmtSum = TypeBits-1;
7661
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007662 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007663 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007664 InsertNewInstBefore(Shift, I);
7665
7666 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007667 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007668 }
7669
7670 // Okay, if we get here, one shift must be left, and the other shift must be
7671 // right. See if the amounts are equal.
7672 if (ShiftAmt1 == ShiftAmt2) {
7673 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7674 if (I.getOpcode() == Instruction::Shl) {
7675 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007676 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007677 }
7678 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7679 if (I.getOpcode() == Instruction::LShr) {
7680 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007681 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007682 }
7683 // We can simplify ((X << C) >>s C) into a trunc + sext.
7684 // NOTE: we could do this for any C, but that would make 'unusual' integer
7685 // types. For now, just stick to ones well-supported by the code
7686 // generators.
7687 const Type *SExtType = 0;
7688 switch (Ty->getBitWidth() - ShiftAmt1) {
7689 case 1 :
7690 case 8 :
7691 case 16 :
7692 case 32 :
7693 case 64 :
7694 case 128:
Owen Anderson6b6e2d92009-07-29 22:17:13 +00007695 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007696 break;
7697 default: break;
7698 }
7699 if (SExtType) {
7700 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7701 InsertNewInstBefore(NewTrunc, I);
7702 return new SExtInst(NewTrunc, Ty);
7703 }
7704 // Otherwise, we can't handle it yet.
7705 } else if (ShiftAmt1 < ShiftAmt2) {
7706 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7707
7708 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7709 if (I.getOpcode() == Instruction::Shl) {
7710 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7711 ShiftOp->getOpcode() == Instruction::AShr);
7712 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007713 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007714 InsertNewInstBefore(Shift, I);
7715
7716 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007717 return BinaryOperator::CreateAnd(Shift,
7718 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007719 }
7720
7721 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7722 if (I.getOpcode() == Instruction::LShr) {
7723 assert(ShiftOp->getOpcode() == Instruction::Shl);
7724 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007725 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007726 InsertNewInstBefore(Shift, I);
7727
7728 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007729 return BinaryOperator::CreateAnd(Shift,
7730 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007731 }
7732
7733 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7734 } else {
7735 assert(ShiftAmt2 < ShiftAmt1);
7736 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7737
7738 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7739 if (I.getOpcode() == Instruction::Shl) {
7740 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7741 ShiftOp->getOpcode() == Instruction::AShr);
7742 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007743 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007744 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007745 InsertNewInstBefore(Shift, I);
7746
7747 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007748 return BinaryOperator::CreateAnd(Shift,
7749 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007750 }
7751
7752 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7753 if (I.getOpcode() == Instruction::LShr) {
7754 assert(ShiftOp->getOpcode() == Instruction::Shl);
7755 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007756 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007757 InsertNewInstBefore(Shift, I);
7758
7759 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007760 return BinaryOperator::CreateAnd(Shift,
7761 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007762 }
7763
7764 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7765 }
7766 }
7767 return 0;
7768}
7769
7770
7771/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7772/// expression. If so, decompose it, returning some value X, such that Val is
7773/// X*Scale+Offset.
7774///
7775static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007776 int &Offset, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007777 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7778 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7779 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007780 Scale = 0;
Owen Andersoneacb44d2009-07-24 23:12:02 +00007781 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007782 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7783 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7784 if (I->getOpcode() == Instruction::Shl) {
7785 // This is a value scaled by '1 << the shift amt'.
7786 Scale = 1U << RHS->getZExtValue();
7787 Offset = 0;
7788 return I->getOperand(0);
7789 } else if (I->getOpcode() == Instruction::Mul) {
7790 // This value is scaled by 'RHS'.
7791 Scale = RHS->getZExtValue();
7792 Offset = 0;
7793 return I->getOperand(0);
7794 } else if (I->getOpcode() == Instruction::Add) {
7795 // We have X+C. Check to see if we really have (X*C2)+C1,
7796 // where C1 is divisible by C2.
7797 unsigned SubScale;
7798 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007799 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7800 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007801 Offset += RHS->getZExtValue();
7802 Scale = SubScale;
7803 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007804 }
7805 }
7806 }
7807
7808 // Otherwise, we can't look past this.
7809 Scale = 1;
7810 Offset = 0;
7811 return Val;
7812}
7813
7814
7815/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7816/// try to eliminate the cast by moving the type information into the alloc.
7817Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7818 AllocationInst &AI) {
7819 const PointerType *PTy = cast<PointerType>(CI.getType());
7820
7821 // Remove any uses of AI that are dead.
7822 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7823
7824 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7825 Instruction *User = cast<Instruction>(*UI++);
7826 if (isInstructionTriviallyDead(User)) {
7827 while (UI != E && *UI == User)
7828 ++UI; // If this instruction uses AI more than once, don't break UI.
7829
7830 ++NumDeadInst;
Dan Gohman3fa885b2009-08-12 16:28:31 +00007831 DOUT << "IC: DCE: " << *User << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007832 EraseInstFromFunction(*User);
7833 }
7834 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007835
7836 // This requires TargetData to get the alloca alignment and size information.
7837 if (!TD) return 0;
7838
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007839 // Get the type really allocated and the type casted to.
7840 const Type *AllocElTy = AI.getAllocatedType();
7841 const Type *CastElTy = PTy->getElementType();
7842 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7843
7844 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7845 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7846 if (CastElTyAlign < AllocElTyAlign) return 0;
7847
7848 // If the allocation has multiple uses, only promote it if we are strictly
7849 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007850 // same, we open the door to infinite loops of various kinds. (A reference
7851 // from a dbg.declare doesn't count as a use for this purpose.)
7852 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7853 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007854
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007855 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7856 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007857 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7858
7859 // See if we can satisfy the modulus by pulling a scale out of the array
7860 // size argument.
7861 unsigned ArraySizeScale;
7862 int ArrayOffset;
7863 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007864 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7865 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007866
7867 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7868 // do the xform.
7869 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7870 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7871
7872 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7873 Value *Amt = 0;
7874 if (Scale == 1) {
7875 Amt = NumElements;
7876 } else {
7877 // If the allocation size is constant, form a constant mul expression
Owen Andersoneacb44d2009-07-24 23:12:02 +00007878 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007879 if (isa<ConstantInt>(NumElements))
Owen Anderson02b48c32009-07-29 18:55:55 +00007880 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman8fd520a2009-06-15 22:12:54 +00007881 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007882 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007883 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007884 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007885 Amt = InsertNewInstBefore(Tmp, AI);
7886 }
7887 }
7888
7889 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007890 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007891 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007892 Amt = InsertNewInstBefore(Tmp, AI);
7893 }
7894
7895 AllocationInst *New;
7896 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +00007897 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007898 else
Owen Anderson140166d2009-07-15 23:53:25 +00007899 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007900 InsertNewInstBefore(New, AI);
7901 New->takeName(&AI);
7902
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007903 // If the allocation has one real use plus a dbg.declare, just remove the
7904 // declare.
7905 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7906 EraseInstFromFunction(*DI);
7907 }
7908 // If the allocation has multiple real uses, insert a cast and change all
7909 // things that used it to use the new cast. This will also hack on CI, but it
7910 // will die soon.
7911 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007912 AddUsesToWorkList(AI);
7913 // New is the allocation instruction, pointer typed. AI is the original
7914 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7915 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7916 InsertNewInstBefore(NewCast, AI);
7917 AI.replaceAllUsesWith(NewCast);
7918 }
7919 return ReplaceInstUsesWith(CI, New);
7920}
7921
7922/// CanEvaluateInDifferentType - Return true if we can take the specified value
7923/// and return it as type Ty without inserting any new casts and without
7924/// changing the computed value. This is used by code that tries to decide
7925/// whether promoting or shrinking integer operations to wider or smaller types
7926/// will allow us to eliminate a truncate or extend.
7927///
7928/// This is a truncation operation if Ty is smaller than V->getType(), or an
7929/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007930///
7931/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7932/// should return true if trunc(V) can be computed by computing V in the smaller
7933/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7934/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7935/// efficiently truncated.
7936///
7937/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7938/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7939/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007940bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007941 unsigned CastOpc,
7942 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007943 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007944 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007945 return true;
7946
7947 Instruction *I = dyn_cast<Instruction>(V);
7948 if (!I) return false;
7949
Dan Gohman8fd520a2009-06-15 22:12:54 +00007950 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007951
Chris Lattneref70bb82007-08-02 06:11:14 +00007952 // If this is an extension or truncate, we can often eliminate it.
7953 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7954 // If this is a cast from the destination type, we can trivially eliminate
7955 // it, and this will remove a cast overall.
7956 if (I->getOperand(0)->getType() == Ty) {
7957 // If the first operand is itself a cast, and is eliminable, do not count
7958 // this as an eliminable cast. We would prefer to eliminate those two
7959 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007960 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007961 ++NumCastsRemoved;
7962 return true;
7963 }
7964 }
7965
7966 // We can't extend or shrink something that has multiple uses: doing so would
7967 // require duplicating the instruction in general, which isn't profitable.
7968 if (!I->hasOneUse()) return false;
7969
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007970 unsigned Opc = I->getOpcode();
7971 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007972 case Instruction::Add:
7973 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007974 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007975 case Instruction::And:
7976 case Instruction::Or:
7977 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007978 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007979 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007980 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007981 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007982 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007983
Eli Friedman08c45bc2009-07-13 22:46:01 +00007984 case Instruction::UDiv:
7985 case Instruction::URem: {
7986 // UDiv and URem can be truncated if all the truncated bits are zero.
7987 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7988 uint32_t BitWidth = Ty->getScalarSizeInBits();
7989 if (BitWidth < OrigBitWidth) {
7990 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7991 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7992 MaskedValueIsZero(I->getOperand(1), Mask)) {
7993 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7994 NumCastsRemoved) &&
7995 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7996 NumCastsRemoved);
7997 }
7998 }
7999 break;
8000 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008001 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008002 // If we are truncating the result of this SHL, and if it's a shift of a
8003 // constant amount, we can always perform a SHL in a smaller type.
8004 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008005 uint32_t BitWidth = Ty->getScalarSizeInBits();
8006 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008007 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00008008 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008009 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008010 }
8011 break;
8012 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008013 // If this is a truncate of a logical shr, we can truncate it to a smaller
8014 // lshr iff we know that the bits we would otherwise be shifting in are
8015 // already zeros.
8016 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008017 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8018 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008019 if (BitWidth < OrigBitWidth &&
8020 MaskedValueIsZero(I->getOperand(0),
8021 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8022 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008023 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008024 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008025 }
8026 }
8027 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008028 case Instruction::ZExt:
8029 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008030 case Instruction::Trunc:
8031 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008032 // can safely replace it. Note that replacing it does not reduce the number
8033 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008034 if (Opc == CastOpc)
8035 return true;
8036
8037 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008038 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008039 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008040 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008041 case Instruction::Select: {
8042 SelectInst *SI = cast<SelectInst>(I);
8043 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008044 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008045 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008046 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008047 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008048 case Instruction::PHI: {
8049 // We can change a phi if we can change all operands.
8050 PHINode *PN = cast<PHINode>(I);
8051 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8052 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008053 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008054 return false;
8055 return true;
8056 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008057 default:
8058 // TODO: Can handle more cases here.
8059 break;
8060 }
8061
8062 return false;
8063}
8064
8065/// EvaluateInDifferentType - Given an expression that
8066/// CanEvaluateInDifferentType returns true for, actually insert the code to
8067/// evaluate the expression.
8068Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8069 bool isSigned) {
8070 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00008071 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00008072 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008073
8074 // Otherwise, it must be an instruction.
8075 Instruction *I = cast<Instruction>(V);
8076 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008077 unsigned Opc = I->getOpcode();
8078 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008079 case Instruction::Add:
8080 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008081 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008082 case Instruction::And:
8083 case Instruction::Or:
8084 case Instruction::Xor:
8085 case Instruction::AShr:
8086 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008087 case Instruction::Shl:
8088 case Instruction::UDiv:
8089 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008090 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8091 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008092 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008093 break;
8094 }
8095 case Instruction::Trunc:
8096 case Instruction::ZExt:
8097 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008098 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008099 // just return the source. There's no need to insert it because it is not
8100 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008101 if (I->getOperand(0)->getType() == Ty)
8102 return I->getOperand(0);
8103
Chris Lattner4200c2062008-06-18 04:00:49 +00008104 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008105 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008106 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008107 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008108 case Instruction::Select: {
8109 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8110 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8111 Res = SelectInst::Create(I->getOperand(0), True, False);
8112 break;
8113 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008114 case Instruction::PHI: {
8115 PHINode *OPN = cast<PHINode>(I);
8116 PHINode *NPN = PHINode::Create(Ty);
8117 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8118 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8119 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8120 }
8121 Res = NPN;
8122 break;
8123 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008124 default:
8125 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008126 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008127 break;
8128 }
8129
Chris Lattner4200c2062008-06-18 04:00:49 +00008130 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008131 return InsertNewInstBefore(Res, *I);
8132}
8133
8134/// @brief Implement the transforms common to all CastInst visitors.
8135Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8136 Value *Src = CI.getOperand(0);
8137
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008138 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8139 // eliminate it now.
8140 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8141 if (Instruction::CastOps opc =
8142 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8143 // The first cast (CSrc) is eliminable so we need to fix up or replace
8144 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008145 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008146 }
8147 }
8148
8149 // If we are casting a select then fold the cast into the select
8150 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8151 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8152 return NV;
8153
8154 // If we are casting a PHI then fold the cast into the PHI
8155 if (isa<PHINode>(Src))
8156 if (Instruction *NV = FoldOpIntoPhi(CI))
8157 return NV;
8158
8159 return 0;
8160}
8161
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008162/// FindElementAtOffset - Given a type and a constant offset, determine whether
8163/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008164/// the specified offset. If so, fill them into NewIndices and return the
8165/// resultant element type, otherwise return null.
8166static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8167 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008168 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008169 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008170 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008171 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008172
8173 // Start with the index over the outer type. Note that the type size
8174 // might be zero (even if the offset isn't zero) if the indexed type
8175 // is something like [0 x {int, int}]
8176 const Type *IntPtrTy = TD->getIntPtrType();
8177 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008178 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008179 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008180 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008181
Chris Lattnerce48c462009-01-11 20:15:20 +00008182 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008183 if (Offset < 0) {
8184 --FirstIdx;
8185 Offset += TySize;
8186 assert(Offset >= 0);
8187 }
8188 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8189 }
8190
Owen Andersoneacb44d2009-07-24 23:12:02 +00008191 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008192
8193 // Index into the types. If we fail, set OrigBase to null.
8194 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008195 // Indexing into tail padding between struct/array elements.
8196 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008197 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008198
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008199 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8200 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008201 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8202 "Offset must stay within the indexed type");
8203
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008204 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008205 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008206
8207 Offset -= SL->getElementOffset(Elt);
8208 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008209 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008210 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008211 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008212 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008213 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008214 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008215 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008216 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008217 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008218 }
8219 }
8220
Chris Lattner54dddc72009-01-24 01:00:13 +00008221 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008222}
8223
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008224/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8225Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8226 Value *Src = CI.getOperand(0);
8227
8228 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8229 // If casting the result of a getelementptr instruction with no offset, turn
8230 // this into a cast of the original pointer!
8231 if (GEP->hasAllZeroIndices()) {
8232 // Changing the cast operand is usually not a good idea but it is safe
8233 // here because the pointer operand is being replaced with another
8234 // pointer operand so the opcode doesn't need to change.
8235 AddToWorkList(GEP);
8236 CI.setOperand(0, GEP->getOperand(0));
8237 return &CI;
8238 }
8239
8240 // If the GEP has a single use, and the base pointer is a bitcast, and the
8241 // GEP computes a constant offset, see if we can convert these three
8242 // instructions into fewer. This typically happens with unions and other
8243 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008244 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008245 if (GEP->hasAllConstantIndices()) {
8246 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008247 ConstantInt *OffsetV =
8248 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008249 int64_t Offset = OffsetV->getSExtValue();
8250
8251 // Get the base pointer input of the bitcast, and the type it points to.
8252 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8253 const Type *GEPIdxTy =
8254 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008255 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008256 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008257 // If we were able to index down into an element, create the GEP
8258 // and bitcast the result. This eliminates one bitcast, potentially
8259 // two.
8260 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8261 NewIndices.begin(),
8262 NewIndices.end(), "");
8263 InsertNewInstBefore(NGEP, CI);
8264 NGEP->takeName(GEP);
Dan Gohman17f46f72009-07-28 01:40:03 +00008265 if (cast<GEPOperator>(GEP)->isInBounds())
8266 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008267
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008268 if (isa<BitCastInst>(CI))
8269 return new BitCastInst(NGEP, CI.getType());
8270 assert(isa<PtrToIntInst>(CI));
8271 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008272 }
8273 }
8274 }
8275 }
8276
8277 return commonCastTransforms(CI);
8278}
8279
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008280/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8281/// type like i42. We don't want to introduce operations on random non-legal
8282/// integer types where they don't already exist in the code. In the future,
8283/// we should consider making this based off target-data, so that 32-bit targets
8284/// won't get i64 operations etc.
8285static bool isSafeIntegerType(const Type *Ty) {
8286 switch (Ty->getPrimitiveSizeInBits()) {
8287 case 8:
8288 case 16:
8289 case 32:
8290 case 64:
8291 return true;
8292 default:
8293 return false;
8294 }
8295}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008296
Eli Friedman827e37a2009-07-13 20:58:59 +00008297/// commonIntCastTransforms - This function implements the common transforms
8298/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008299Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8300 if (Instruction *Result = commonCastTransforms(CI))
8301 return Result;
8302
8303 Value *Src = CI.getOperand(0);
8304 const Type *SrcTy = Src->getType();
8305 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008306 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8307 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008308
8309 // See if we can simplify any instructions used by the LHS whose sole
8310 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008311 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008312 return &CI;
8313
8314 // If the source isn't an instruction or has more than one use then we
8315 // can't do anything more.
8316 Instruction *SrcI = dyn_cast<Instruction>(Src);
8317 if (!SrcI || !Src->hasOneUse())
8318 return 0;
8319
8320 // Attempt to propagate the cast into the instruction for int->int casts.
8321 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008322 // Only do this if the dest type is a simple type, don't convert the
8323 // expression tree to something weird like i93 unless the source is also
8324 // strange.
8325 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008326 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8327 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008328 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008329 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008330 // eliminates the cast, so it is always a win. If this is a zero-extension,
8331 // we need to do an AND to maintain the clear top-part of the computation,
8332 // so we require that the input have eliminated at least one cast. If this
8333 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008334 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008335 bool DoXForm = false;
8336 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008337 switch (CI.getOpcode()) {
8338 default:
8339 // All the others use floating point so we shouldn't actually
8340 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008341 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008342 case Instruction::Trunc:
8343 DoXForm = true;
8344 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008345 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008346 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008347 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008348 // If it's unnecessary to issue an AND to clear the high bits, it's
8349 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008350 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008351 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8352 if (MaskedValueIsZero(TryRes, Mask))
8353 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008354
8355 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008356 if (TryI->use_empty())
8357 EraseInstFromFunction(*TryI);
8358 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008359 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008360 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008361 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008362 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008363 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008364 // If we do not have to emit the truncate + sext pair, then it's always
8365 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008366 //
8367 // It's not safe to eliminate the trunc + sext pair if one of the
8368 // eliminated cast is a truncate. e.g.
8369 // t2 = trunc i32 t1 to i16
8370 // t3 = sext i16 t2 to i32
8371 // !=
8372 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008373 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008374 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8375 if (NumSignBits > (DestBitSize - SrcBitSize))
8376 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008377
8378 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008379 if (TryI->use_empty())
8380 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008381 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008382 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008383 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008384 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008385
8386 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008387 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8388 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008389 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8390 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008391 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008392 // Just replace this cast with the result.
8393 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008395 assert(Res->getType() == DestTy);
8396 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008397 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008398 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008399 // Just replace this cast with the result.
8400 return ReplaceInstUsesWith(CI, Res);
8401 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008402 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008403
8404 // If the high bits are already zero, just replace this cast with the
8405 // result.
8406 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8407 if (MaskedValueIsZero(Res, Mask))
8408 return ReplaceInstUsesWith(CI, Res);
8409
8410 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008411 Constant *C = ConstantInt::get(*Context,
8412 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008413 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008414 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008415 case Instruction::SExt: {
8416 // If the high bits are already filled with sign bit, just replace this
8417 // cast with the result.
8418 unsigned NumSignBits = ComputeNumSignBits(Res);
8419 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008420 return ReplaceInstUsesWith(CI, Res);
8421
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008422 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008423 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008424 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8425 CI), DestTy);
8426 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008427 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008428 }
8429 }
8430
8431 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8432 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8433
8434 switch (SrcI->getOpcode()) {
8435 case Instruction::Add:
8436 case Instruction::Mul:
8437 case Instruction::And:
8438 case Instruction::Or:
8439 case Instruction::Xor:
8440 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008441 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8442 // Don't insert two casts unless at least one can be eliminated.
8443 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008444 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008445 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8446 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008447 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008448 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8449 }
8450 }
8451
8452 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8453 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8454 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008455 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008456 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008457 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008458 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008459 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008460 }
8461 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008462
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008463 case Instruction::Shl: {
8464 // Canonicalize trunc inside shl, if we can.
8465 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8466 if (CI && DestBitSize < SrcBitSize &&
8467 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8468 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8469 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008470 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008471 }
8472 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008473 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008474 }
8475 return 0;
8476}
8477
8478Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8479 if (Instruction *Result = commonIntCastTransforms(CI))
8480 return Result;
8481
8482 Value *Src = CI.getOperand(0);
8483 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008484 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8485 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008486
8487 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008488 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008489 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner32177f82009-03-24 18:15:30 +00008490 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersonaac28372009-07-31 20:28:14 +00008491 Value *Zero = Constant::getNullValue(Src->getType());
Owen Anderson6601fcd2009-07-09 23:48:35 +00008492 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008493 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008494
Chris Lattner32177f82009-03-24 18:15:30 +00008495 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8496 ConstantInt *ShAmtV = 0;
8497 Value *ShiftOp = 0;
8498 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008499 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008500 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8501
8502 // Get a mask for the bits shifting in.
8503 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8504 if (MaskedValueIsZero(ShiftOp, Mask)) {
8505 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008506 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008507
8508 // Okay, we can shrink this. Truncate the input, then return a new
8509 // shift.
8510 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Anderson02b48c32009-07-29 18:55:55 +00008511 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008512 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008513 }
8514 }
8515
8516 return 0;
8517}
8518
Evan Chenge3779cf2008-03-24 00:21:34 +00008519/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8520/// in order to eliminate the icmp.
8521Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8522 bool DoXform) {
8523 // If we are just checking for a icmp eq of a single bit and zext'ing it
8524 // to an integer, then shift the bit to the appropriate place and then
8525 // cast to integer to avoid the comparison.
8526 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8527 const APInt &Op1CV = Op1C->getValue();
8528
8529 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8530 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8531 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8532 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8533 if (!DoXform) return ICI;
8534
8535 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008536 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008537 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008538 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008539 In->getName()+".lobit"),
8540 CI);
8541 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008542 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008543 false/*ZExt*/, "tmp", &CI);
8544
8545 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008546 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008547 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008548 In->getName()+".not"),
8549 CI);
8550 }
8551
8552 return ReplaceInstUsesWith(CI, In);
8553 }
8554
8555
8556
8557 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8558 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8559 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8560 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8561 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8562 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8563 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8564 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8565 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8566 // This only works for EQ and NE
8567 ICI->isEquality()) {
8568 // If Op1C some other power of two, convert:
8569 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8570 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8571 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8572 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8573
8574 APInt KnownZeroMask(~KnownZero);
8575 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8576 if (!DoXform) return ICI;
8577
8578 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8579 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8580 // (X&4) == 2 --> false
8581 // (X&4) != 2 --> true
Owen Andersoneacb44d2009-07-24 23:12:02 +00008582 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008583 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008584 return ReplaceInstUsesWith(CI, Res);
8585 }
8586
8587 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8588 Value *In = ICI->getOperand(0);
8589 if (ShiftAmt) {
8590 // Perform a logical shr by shiftamt.
8591 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008592 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008593 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chenge3779cf2008-03-24 00:21:34 +00008594 In->getName()+".lobit"), CI);
8595 }
8596
8597 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008598 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008599 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008600 InsertNewInstBefore(cast<Instruction>(In), CI);
8601 }
8602
8603 if (CI.getType() == In->getType())
8604 return ReplaceInstUsesWith(CI, In);
8605 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008606 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008607 }
8608 }
8609 }
8610
8611 return 0;
8612}
8613
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008614Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8615 // If one of the common conversion will work ..
8616 if (Instruction *Result = commonIntCastTransforms(CI))
8617 return Result;
8618
8619 Value *Src = CI.getOperand(0);
8620
Chris Lattner215d56e2009-02-17 20:47:23 +00008621 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8622 // types and if the sizes are just right we can convert this into a logical
8623 // 'and' which will be much cheaper than the pair of casts.
8624 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8625 // Get the sizes of the types involved. We know that the intermediate type
8626 // will be smaller than A or C, but don't know the relation between A and C.
8627 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008628 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8629 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8630 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008631 // If we're actually extending zero bits, then if
8632 // SrcSize < DstSize: zext(a & mask)
8633 // SrcSize == DstSize: a & mask
8634 // SrcSize > DstSize: trunc(a) & mask
8635 if (SrcSize < DstSize) {
8636 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008637 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008638 Instruction *And =
8639 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8640 InsertNewInstBefore(And, CI);
8641 return new ZExtInst(And, CI.getType());
8642 } else if (SrcSize == DstSize) {
8643 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008644 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008645 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008646 } else if (SrcSize > DstSize) {
8647 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8648 InsertNewInstBefore(Trunc, CI);
8649 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008650 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008651 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008652 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008653 }
8654 }
8655
Evan Chenge3779cf2008-03-24 00:21:34 +00008656 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8657 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008658
Evan Chenge3779cf2008-03-24 00:21:34 +00008659 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8660 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8661 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8662 // of the (zext icmp) will be transformed.
8663 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8664 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8665 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8666 (transformZExtICmp(LHS, CI, false) ||
8667 transformZExtICmp(RHS, CI, false))) {
8668 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8669 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008670 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008671 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008672 }
8673
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008674 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008675 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8676 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8677 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8678 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008679 if (TI0->getType() == CI.getType())
8680 return
8681 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008682 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008683 }
8684
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008685 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8686 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8687 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8688 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8689 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8690 And->getOperand(1) == C)
8691 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8692 Value *TI0 = TI->getOperand(0);
8693 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008694 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008695 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8696 InsertNewInstBefore(NewAnd, *And);
8697 return BinaryOperator::CreateXor(NewAnd, ZC);
8698 }
8699 }
8700
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008701 return 0;
8702}
8703
8704Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8705 if (Instruction *I = commonIntCastTransforms(CI))
8706 return I;
8707
8708 Value *Src = CI.getOperand(0);
8709
Dan Gohman35b76162008-10-30 20:40:10 +00008710 // Canonicalize sign-extend from i1 to a select.
8711 if (Src->getType() == Type::Int1Ty)
8712 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008713 Constant::getAllOnesValue(CI.getType()),
8714 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008715
8716 // See if the value being truncated is already sign extended. If so, just
8717 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008718 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008719 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008720 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8721 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8722 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008723 unsigned NumSignBits = ComputeNumSignBits(Op);
8724
8725 if (OpBits == DestBits) {
8726 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8727 // bits, it is already ready.
8728 if (NumSignBits > DestBits-MidBits)
8729 return ReplaceInstUsesWith(CI, Op);
8730 } else if (OpBits < DestBits) {
8731 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8732 // bits, just sext from i32.
8733 if (NumSignBits > OpBits-MidBits)
8734 return new SExtInst(Op, CI.getType(), "tmp");
8735 } else {
8736 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8737 // bits, just truncate to i32.
8738 if (NumSignBits > OpBits-MidBits)
8739 return new TruncInst(Op, CI.getType(), "tmp");
8740 }
8741 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008742
8743 // If the input is a shl/ashr pair of a same constant, then this is a sign
8744 // extension from a smaller value. If we could trust arbitrary bitwidth
8745 // integers, we could turn this into a truncate to the smaller bit and then
8746 // use a sext for the whole extension. Since we don't, look deeper and check
8747 // for a truncate. If the source and dest are the same type, eliminate the
8748 // trunc and extend and just do shifts. For example, turn:
8749 // %a = trunc i32 %i to i8
8750 // %b = shl i8 %a, 6
8751 // %c = ashr i8 %b, 6
8752 // %d = sext i8 %c to i32
8753 // into:
8754 // %a = shl i32 %i, 30
8755 // %d = ashr i32 %a, 30
8756 Value *A = 0;
8757 ConstantInt *BA = 0, *CA = 0;
8758 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008759 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008760 BA == CA && isa<TruncInst>(A)) {
8761 Value *I = cast<TruncInst>(A)->getOperand(0);
8762 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008763 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8764 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008765 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008766 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner8a2d0592008-08-06 07:35:52 +00008767 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8768 CI.getName()), CI);
8769 return BinaryOperator::CreateAShr(I, ShAmtV);
8770 }
8771 }
8772
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008773 return 0;
8774}
8775
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008776/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8777/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008778static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008779 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008780 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008781 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008782 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8783 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008784 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008785 return 0;
8786}
8787
8788/// LookThroughFPExtensions - If this is an fp extension instruction, look
8789/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008790static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008791 if (Instruction *I = dyn_cast<Instruction>(V))
8792 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008793 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008794
8795 // If this value is a constant, return the constant in the smallest FP type
8796 // that can accurately represent it. This allows us to turn
8797 // (float)((double)X+2.0) into x+2.0f.
8798 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8799 if (CFP->getType() == Type::PPC_FP128Ty)
8800 return V; // No constant folding of this.
8801 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008802 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008803 return V;
8804 if (CFP->getType() == Type::DoubleTy)
8805 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008806 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008807 return V;
8808 // Don't try to shrink to various long double types.
8809 }
8810
8811 return V;
8812}
8813
8814Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8815 if (Instruction *I = commonCastTransforms(CI))
8816 return I;
8817
Dan Gohman7ce405e2009-06-04 22:49:04 +00008818 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008819 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008820 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008821 // many builtins (sqrt, etc).
8822 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8823 if (OpI && OpI->hasOneUse()) {
8824 switch (OpI->getOpcode()) {
8825 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008826 case Instruction::FAdd:
8827 case Instruction::FSub:
8828 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008829 case Instruction::FDiv:
8830 case Instruction::FRem:
8831 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008832 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8833 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008834 if (LHSTrunc->getType() != SrcTy &&
8835 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008836 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008837 // If the source types were both smaller than the destination type of
8838 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008839 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8840 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008841 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8842 CI.getType(), CI);
8843 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8844 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008845 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008846 }
8847 }
8848 break;
8849 }
8850 }
8851 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008852}
8853
8854Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8855 return commonCastTransforms(CI);
8856}
8857
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008858Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008859 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8860 if (OpI == 0)
8861 return commonCastTransforms(FI);
8862
8863 // fptoui(uitofp(X)) --> X
8864 // fptoui(sitofp(X)) --> X
8865 // This is safe if the intermediate type has enough bits in its mantissa to
8866 // accurately represent all values of X. For example, do not do this with
8867 // i64->float->i64. This is also safe for sitofp case, because any negative
8868 // 'X' value would cause an undefined result for the fptoui.
8869 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8870 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008871 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008872 OpI->getType()->getFPMantissaWidth())
8873 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008874
8875 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008876}
8877
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008878Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008879 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8880 if (OpI == 0)
8881 return commonCastTransforms(FI);
8882
8883 // fptosi(sitofp(X)) --> X
8884 // fptosi(uitofp(X)) --> X
8885 // This is safe if the intermediate type has enough bits in its mantissa to
8886 // accurately represent all values of X. For example, do not do this with
8887 // i64->float->i64. This is also safe for sitofp case, because any negative
8888 // 'X' value would cause an undefined result for the fptoui.
8889 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8890 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008891 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008892 OpI->getType()->getFPMantissaWidth())
8893 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008894
8895 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008896}
8897
8898Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8899 return commonCastTransforms(CI);
8900}
8901
8902Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8903 return commonCastTransforms(CI);
8904}
8905
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008906Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8907 // If the destination integer type is smaller than the intptr_t type for
8908 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8909 // trunc to be exposed to other transforms. Don't do this for extending
8910 // ptrtoint's, because we don't know if the target sign or zero extends its
8911 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008912 if (TD &&
8913 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008914 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8915 TD->getIntPtrType(),
8916 "tmp"), CI);
8917 return new TruncInst(P, CI.getType());
8918 }
8919
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008920 return commonPointerCastTransforms(CI);
8921}
8922
Chris Lattner7c1626482008-01-08 07:23:51 +00008923Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008924 // If the source integer type is larger than the intptr_t type for
8925 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8926 // allows the trunc to be exposed to other transforms. Don't do this for
8927 // extending inttoptr's, because we don't know if the target sign or zero
8928 // extends to pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008929 if (TD &&
8930 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008931 TD->getPointerSizeInBits()) {
8932 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8933 TD->getIntPtrType(),
8934 "tmp"), CI);
8935 return new IntToPtrInst(P, CI.getType());
8936 }
8937
Chris Lattner7c1626482008-01-08 07:23:51 +00008938 if (Instruction *I = commonCastTransforms(CI))
8939 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008940
Chris Lattner7c1626482008-01-08 07:23:51 +00008941 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008942}
8943
8944Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8945 // If the operands are integer typed then apply the integer transforms,
8946 // otherwise just apply the common ones.
8947 Value *Src = CI.getOperand(0);
8948 const Type *SrcTy = Src->getType();
8949 const Type *DestTy = CI.getType();
8950
Eli Friedman5013d3f2009-07-13 20:53:00 +00008951 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008952 if (Instruction *I = commonPointerCastTransforms(CI))
8953 return I;
8954 } else {
8955 if (Instruction *Result = commonCastTransforms(CI))
8956 return Result;
8957 }
8958
8959
8960 // Get rid of casts from one type to the same type. These are useless and can
8961 // be replaced by the operand.
8962 if (DestTy == Src->getType())
8963 return ReplaceInstUsesWith(CI, Src);
8964
8965 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8966 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8967 const Type *DstElTy = DstPTy->getElementType();
8968 const Type *SrcElTy = SrcPTy->getElementType();
8969
Nate Begemandf5b3612008-03-31 00:22:16 +00008970 // If the address spaces don't match, don't eliminate the bitcast, which is
8971 // required for changing types.
8972 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8973 return 0;
8974
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008975 // If we are casting a malloc or alloca to a pointer to a type of the same
8976 // size, rewrite the allocation instruction to allocate the "right" type.
8977 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8978 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8979 return V;
8980
8981 // If the source and destination are pointers, and this cast is equivalent
8982 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8983 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersonaac28372009-07-31 20:28:14 +00008984 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008985 unsigned NumZeros = 0;
8986 while (SrcElTy != DstElTy &&
8987 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8988 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8989 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8990 ++NumZeros;
8991 }
8992
8993 // If we found a path from the src to dest, create the getelementptr now.
8994 if (SrcElTy == DstElTy) {
8995 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohman17f46f72009-07-28 01:40:03 +00008996 Instruction *GEP = GetElementPtrInst::Create(Src,
8997 Idxs.begin(), Idxs.end(), "",
8998 ((Instruction*) NULL));
8999 cast<GEPOperator>(GEP)->setIsInBounds(true);
9000 return GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009001 }
9002 }
9003
Eli Friedman1d31dee2009-07-18 23:06:53 +00009004 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9005 if (DestVTy->getNumElements() == 1) {
9006 if (!isa<VectorType>(SrcTy)) {
9007 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9008 DestVTy->getElementType(), CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00009009 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Andersonaac28372009-07-31 20:28:14 +00009010 Constant::getNullValue(Type::Int32Ty));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009011 }
9012 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9013 }
9014 }
9015
9016 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9017 if (SrcVTy->getNumElements() == 1) {
9018 if (!isa<VectorType>(DestTy)) {
9019 Instruction *Elem =
Owen Andersonaac28372009-07-31 20:28:14 +00009020 ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009021 InsertNewInstBefore(Elem, CI);
9022 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9023 }
9024 }
9025 }
9026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009027 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9028 if (SVI->hasOneUse()) {
9029 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9030 // a bitconvert to a vector with the same # elts.
9031 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009032 cast<VectorType>(DestTy)->getNumElements() ==
9033 SVI->getType()->getNumElements() &&
9034 SVI->getType()->getNumElements() ==
9035 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009036 CastInst *Tmp;
9037 // If either of the operands is a cast from CI.getType(), then
9038 // evaluating the shuffle in the casted destination's type will allow
9039 // us to eliminate at least one cast.
9040 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9041 Tmp->getOperand(0)->getType() == DestTy) ||
9042 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9043 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00009044 Value *LHS = InsertCastBefore(Instruction::BitCast,
9045 SVI->getOperand(0), DestTy, CI);
9046 Value *RHS = InsertCastBefore(Instruction::BitCast,
9047 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009048 // Return a new shuffle vector. Use the same element ID's, as we
9049 // know the vector types match #elts.
9050 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9051 }
9052 }
9053 }
9054 }
9055 return 0;
9056}
9057
9058/// GetSelectFoldableOperands - We want to turn code that looks like this:
9059/// %C = or %A, %B
9060/// %D = select %cond, %C, %A
9061/// into:
9062/// %C = select %cond, %B, 0
9063/// %D = or %A, %C
9064///
9065/// Assuming that the specified instruction is an operand to the select, return
9066/// a bitmask indicating which operands of this instruction are foldable if they
9067/// equal the other incoming value of the select.
9068///
9069static unsigned GetSelectFoldableOperands(Instruction *I) {
9070 switch (I->getOpcode()) {
9071 case Instruction::Add:
9072 case Instruction::Mul:
9073 case Instruction::And:
9074 case Instruction::Or:
9075 case Instruction::Xor:
9076 return 3; // Can fold through either operand.
9077 case Instruction::Sub: // Can only fold on the amount subtracted.
9078 case Instruction::Shl: // Can only fold on the shift amount.
9079 case Instruction::LShr:
9080 case Instruction::AShr:
9081 return 1;
9082 default:
9083 return 0; // Cannot fold
9084 }
9085}
9086
9087/// GetSelectFoldableConstant - For the same transformation as the previous
9088/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009089static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009090 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009091 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009092 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009093 case Instruction::Add:
9094 case Instruction::Sub:
9095 case Instruction::Or:
9096 case Instruction::Xor:
9097 case Instruction::Shl:
9098 case Instruction::LShr:
9099 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009100 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009101 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009102 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009103 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009104 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009105 }
9106}
9107
9108/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9109/// have the same opcode and only one use each. Try to simplify this.
9110Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9111 Instruction *FI) {
9112 if (TI->getNumOperands() == 1) {
9113 // If this is a non-volatile load or a cast from the same type,
9114 // merge.
9115 if (TI->isCast()) {
9116 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9117 return 0;
9118 } else {
9119 return 0; // unknown unary op.
9120 }
9121
9122 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009123 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009124 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009125 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009126 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009127 TI->getType());
9128 }
9129
9130 // Only handle binary operators here.
9131 if (!isa<BinaryOperator>(TI))
9132 return 0;
9133
9134 // Figure out if the operations have any operands in common.
9135 Value *MatchOp, *OtherOpT, *OtherOpF;
9136 bool MatchIsOpZero;
9137 if (TI->getOperand(0) == FI->getOperand(0)) {
9138 MatchOp = TI->getOperand(0);
9139 OtherOpT = TI->getOperand(1);
9140 OtherOpF = FI->getOperand(1);
9141 MatchIsOpZero = true;
9142 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9143 MatchOp = TI->getOperand(1);
9144 OtherOpT = TI->getOperand(0);
9145 OtherOpF = FI->getOperand(0);
9146 MatchIsOpZero = false;
9147 } else if (!TI->isCommutative()) {
9148 return 0;
9149 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9150 MatchOp = TI->getOperand(0);
9151 OtherOpT = TI->getOperand(1);
9152 OtherOpF = FI->getOperand(0);
9153 MatchIsOpZero = true;
9154 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9155 MatchOp = TI->getOperand(1);
9156 OtherOpT = TI->getOperand(0);
9157 OtherOpF = FI->getOperand(1);
9158 MatchIsOpZero = true;
9159 } else {
9160 return 0;
9161 }
9162
9163 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009164 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9165 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009166 InsertNewInstBefore(NewSI, SI);
9167
9168 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9169 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009170 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009171 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009172 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009173 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009174 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009175 return 0;
9176}
9177
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009178static bool isSelect01(Constant *C1, Constant *C2) {
9179 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9180 if (!C1I)
9181 return false;
9182 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9183 if (!C2I)
9184 return false;
9185 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9186}
9187
9188/// FoldSelectIntoOp - Try fold the select into one of the operands to
9189/// facilitate further optimization.
9190Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9191 Value *FalseVal) {
9192 // See the comment above GetSelectFoldableOperands for a description of the
9193 // transformation we are doing here.
9194 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9195 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9196 !isa<Constant>(FalseVal)) {
9197 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9198 unsigned OpToFold = 0;
9199 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9200 OpToFold = 1;
9201 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9202 OpToFold = 2;
9203 }
9204
9205 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009206 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009207 Value *OOp = TVI->getOperand(2-OpToFold);
9208 // Avoid creating select between 2 constants unless it's selecting
9209 // between 0 and 1.
9210 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9211 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9212 InsertNewInstBefore(NewSel, SI);
9213 NewSel->takeName(TVI);
9214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9215 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009216 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009217 }
9218 }
9219 }
9220 }
9221 }
9222
9223 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9224 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9225 !isa<Constant>(TrueVal)) {
9226 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9227 unsigned OpToFold = 0;
9228 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9229 OpToFold = 1;
9230 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9231 OpToFold = 2;
9232 }
9233
9234 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009235 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009236 Value *OOp = FVI->getOperand(2-OpToFold);
9237 // Avoid creating select between 2 constants unless it's selecting
9238 // between 0 and 1.
9239 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9240 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9241 InsertNewInstBefore(NewSel, SI);
9242 NewSel->takeName(FVI);
9243 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9244 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009245 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009246 }
9247 }
9248 }
9249 }
9250 }
9251
9252 return 0;
9253}
9254
Dan Gohman58c09632008-09-16 18:46:06 +00009255/// visitSelectInstWithICmp - Visit a SelectInst that has an
9256/// ICmpInst as its first operand.
9257///
9258Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9259 ICmpInst *ICI) {
9260 bool Changed = false;
9261 ICmpInst::Predicate Pred = ICI->getPredicate();
9262 Value *CmpLHS = ICI->getOperand(0);
9263 Value *CmpRHS = ICI->getOperand(1);
9264 Value *TrueVal = SI.getTrueValue();
9265 Value *FalseVal = SI.getFalseValue();
9266
9267 // Check cases where the comparison is with a constant that
9268 // can be adjusted to fit the min/max idiom. We may edit ICI in
9269 // place here, so make sure the select is the only user.
9270 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009271 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009272 switch (Pred) {
9273 default: break;
9274 case ICmpInst::ICMP_ULT:
9275 case ICmpInst::ICMP_SLT: {
9276 // X < MIN ? T : F --> F
9277 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9278 return ReplaceInstUsesWith(SI, FalseVal);
9279 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009280 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009281 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9282 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9283 Pred = ICmpInst::getSwappedPredicate(Pred);
9284 CmpRHS = AdjustedRHS;
9285 std::swap(FalseVal, TrueVal);
9286 ICI->setPredicate(Pred);
9287 ICI->setOperand(1, CmpRHS);
9288 SI.setOperand(1, TrueVal);
9289 SI.setOperand(2, FalseVal);
9290 Changed = true;
9291 }
9292 break;
9293 }
9294 case ICmpInst::ICMP_UGT:
9295 case ICmpInst::ICMP_SGT: {
9296 // X > MAX ? T : F --> F
9297 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9298 return ReplaceInstUsesWith(SI, FalseVal);
9299 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009300 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009301 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9302 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9303 Pred = ICmpInst::getSwappedPredicate(Pred);
9304 CmpRHS = AdjustedRHS;
9305 std::swap(FalseVal, TrueVal);
9306 ICI->setPredicate(Pred);
9307 ICI->setOperand(1, CmpRHS);
9308 SI.setOperand(1, TrueVal);
9309 SI.setOperand(2, FalseVal);
9310 Changed = true;
9311 }
9312 break;
9313 }
9314 }
9315
Dan Gohman35b76162008-10-30 20:40:10 +00009316 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9317 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009318 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009319 if (match(TrueVal, m_ConstantInt<-1>()) &&
9320 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009321 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009322 else if (match(TrueVal, m_ConstantInt<0>()) &&
9323 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009324 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9325
Dan Gohman35b76162008-10-30 20:40:10 +00009326 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9327 // If we are just checking for a icmp eq of a single bit and zext'ing it
9328 // to an integer, then shift the bit to the appropriate place and then
9329 // cast to integer to avoid the comparison.
9330 const APInt &Op1CV = CI->getValue();
9331
9332 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9333 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9334 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009335 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009336 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009337 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009338 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009339 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009340 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009341 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009342 if (In->getType() != SI.getType())
9343 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009344 true/*SExt*/, "tmp", ICI);
9345
9346 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009347 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009348 In->getName()+".not"), *ICI);
9349
9350 return ReplaceInstUsesWith(SI, In);
9351 }
9352 }
9353 }
9354
Dan Gohman58c09632008-09-16 18:46:06 +00009355 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9356 // Transform (X == Y) ? X : Y -> Y
9357 if (Pred == ICmpInst::ICMP_EQ)
9358 return ReplaceInstUsesWith(SI, FalseVal);
9359 // Transform (X != Y) ? X : Y -> X
9360 if (Pred == ICmpInst::ICMP_NE)
9361 return ReplaceInstUsesWith(SI, TrueVal);
9362 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9363
9364 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9365 // Transform (X == Y) ? Y : X -> X
9366 if (Pred == ICmpInst::ICMP_EQ)
9367 return ReplaceInstUsesWith(SI, FalseVal);
9368 // Transform (X != Y) ? Y : X -> Y
9369 if (Pred == ICmpInst::ICMP_NE)
9370 return ReplaceInstUsesWith(SI, TrueVal);
9371 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9372 }
9373
9374 /// NOTE: if we wanted to, this is where to detect integer ABS
9375
9376 return Changed ? &SI : 0;
9377}
9378
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009379Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9380 Value *CondVal = SI.getCondition();
9381 Value *TrueVal = SI.getTrueValue();
9382 Value *FalseVal = SI.getFalseValue();
9383
9384 // select true, X, Y -> X
9385 // select false, X, Y -> Y
9386 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9387 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9388
9389 // select C, X, X -> X
9390 if (TrueVal == FalseVal)
9391 return ReplaceInstUsesWith(SI, TrueVal);
9392
9393 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9394 return ReplaceInstUsesWith(SI, FalseVal);
9395 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9396 return ReplaceInstUsesWith(SI, TrueVal);
9397 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9398 if (isa<Constant>(TrueVal))
9399 return ReplaceInstUsesWith(SI, TrueVal);
9400 else
9401 return ReplaceInstUsesWith(SI, FalseVal);
9402 }
9403
9404 if (SI.getType() == Type::Int1Ty) {
9405 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9406 if (C->getZExtValue()) {
9407 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009408 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009409 } else {
9410 // Change: A = select B, false, C --> A = and !B, C
9411 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009412 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009413 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009414 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009415 }
9416 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9417 if (C->getZExtValue() == false) {
9418 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009419 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009420 } else {
9421 // Change: A = select B, C, true --> A = or !B, C
9422 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009423 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009424 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009425 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009426 }
9427 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009428
9429 // select a, b, a -> a&b
9430 // select a, a, b -> a|b
9431 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009432 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009433 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009434 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435 }
9436
9437 // Selecting between two integer constants?
9438 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9439 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9440 // select C, 1, 0 -> zext C to int
9441 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009442 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009443 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9444 // select C, 0, 1 -> zext !C to int
9445 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009446 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009447 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009448 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009450
9451 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009452 // If one of the constants is zero (we know they can't both be) and we
9453 // have an icmp instruction with zero, and we have an 'and' with the
9454 // non-constant value, eliminate this whole mess. This corresponds to
9455 // cases like this: ((X & 27) ? 27 : 0)
9456 if (TrueValC->isZero() || FalseValC->isZero())
9457 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9458 cast<Constant>(IC->getOperand(1))->isNullValue())
9459 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9460 if (ICA->getOpcode() == Instruction::And &&
9461 isa<ConstantInt>(ICA->getOperand(1)) &&
9462 (ICA->getOperand(1) == TrueValC ||
9463 ICA->getOperand(1) == FalseValC) &&
9464 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9465 // Okay, now we know that everything is set up, we just don't
9466 // know whether we have a icmp_ne or icmp_eq and whether the
9467 // true or false val is the zero.
9468 bool ShouldNotVal = !TrueValC->isZero();
9469 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9470 Value *V = ICA;
9471 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009472 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009473 Instruction::Xor, V, ICA->getOperand(1)), SI);
9474 return ReplaceInstUsesWith(SI, V);
9475 }
9476 }
9477 }
9478
9479 // See if we are selecting two values based on a comparison of the two values.
9480 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9481 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9482 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009483 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9484 // This is not safe in general for floating point:
9485 // consider X== -0, Y== +0.
9486 // It becomes safe if either operand is a nonzero constant.
9487 ConstantFP *CFPt, *CFPf;
9488 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9489 !CFPt->getValueAPF().isZero()) ||
9490 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9491 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009492 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009493 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009494 // Transform (X != Y) ? X : Y -> X
9495 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9496 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009497 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009498
9499 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9500 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009501 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9502 // This is not safe in general for floating point:
9503 // consider X== -0, Y== +0.
9504 // It becomes safe if either operand is a nonzero constant.
9505 ConstantFP *CFPt, *CFPf;
9506 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9507 !CFPt->getValueAPF().isZero()) ||
9508 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9509 !CFPf->getValueAPF().isZero()))
9510 return ReplaceInstUsesWith(SI, FalseVal);
9511 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009512 // Transform (X != Y) ? Y : X -> Y
9513 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9514 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009515 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009516 }
Dan Gohman58c09632008-09-16 18:46:06 +00009517 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009518 }
9519
9520 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009521 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9522 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9523 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009524
9525 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9526 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9527 if (TI->hasOneUse() && FI->hasOneUse()) {
9528 Instruction *AddOp = 0, *SubOp = 0;
9529
9530 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9531 if (TI->getOpcode() == FI->getOpcode())
9532 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9533 return IV;
9534
9535 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9536 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009537 if ((TI->getOpcode() == Instruction::Sub &&
9538 FI->getOpcode() == Instruction::Add) ||
9539 (TI->getOpcode() == Instruction::FSub &&
9540 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009541 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009542 } else if ((FI->getOpcode() == Instruction::Sub &&
9543 TI->getOpcode() == Instruction::Add) ||
9544 (FI->getOpcode() == Instruction::FSub &&
9545 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009546 AddOp = TI; SubOp = FI;
9547 }
9548
9549 if (AddOp) {
9550 Value *OtherAddOp = 0;
9551 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9552 OtherAddOp = AddOp->getOperand(1);
9553 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9554 OtherAddOp = AddOp->getOperand(0);
9555 }
9556
9557 if (OtherAddOp) {
9558 // So at this point we know we have (Y -> OtherAddOp):
9559 // select C, (add X, Y), (sub X, Z)
9560 Value *NegVal; // Compute -Z
9561 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009562 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009563 } else {
9564 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009565 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009566 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009567 }
9568
9569 Value *NewTrueOp = OtherAddOp;
9570 Value *NewFalseOp = NegVal;
9571 if (AddOp != TI)
9572 std::swap(NewTrueOp, NewFalseOp);
9573 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009574 SelectInst::Create(CondVal, NewTrueOp,
9575 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009576
9577 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009578 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009579 }
9580 }
9581 }
9582
9583 // See if we can fold the select into one of our operands.
9584 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009585 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9586 if (FoldI)
9587 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009588 }
9589
9590 if (BinaryOperator::isNot(CondVal)) {
9591 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9592 SI.setOperand(1, FalseVal);
9593 SI.setOperand(2, TrueVal);
9594 return &SI;
9595 }
9596
9597 return 0;
9598}
9599
Dan Gohman2d648bb2008-04-10 18:43:06 +00009600/// EnforceKnownAlignment - If the specified pointer points to an object that
9601/// we control, modify the object's alignment to PrefAlign. This isn't
9602/// often possible though. If alignment is important, a more reliable approach
9603/// is to simply align all global variables and allocation instructions to
9604/// their preferred alignment from the beginning.
9605///
9606static unsigned EnforceKnownAlignment(Value *V,
9607 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009608
Dan Gohman2d648bb2008-04-10 18:43:06 +00009609 User *U = dyn_cast<User>(V);
9610 if (!U) return Align;
9611
Dan Gohman9545fb02009-07-17 20:47:02 +00009612 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009613 default: break;
9614 case Instruction::BitCast:
9615 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9616 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009617 // If all indexes are zero, it is just the alignment of the base pointer.
9618 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009619 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009620 if (!isa<Constant>(*i) ||
9621 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009622 AllZeroOperands = false;
9623 break;
9624 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009625
9626 if (AllZeroOperands) {
9627 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009628 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009629 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009630 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009631 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009632 }
9633
9634 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9635 // If there is a large requested alignment and we can, bump up the alignment
9636 // of the global.
9637 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009638 if (GV->getAlignment() >= PrefAlign)
9639 Align = GV->getAlignment();
9640 else {
9641 GV->setAlignment(PrefAlign);
9642 Align = PrefAlign;
9643 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009644 }
9645 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9646 // If there is a requested alignment and if this is an alloca, round up. We
9647 // don't do this for malloc, because some systems can't respect the request.
9648 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009649 if (AI->getAlignment() >= PrefAlign)
9650 Align = AI->getAlignment();
9651 else {
9652 AI->setAlignment(PrefAlign);
9653 Align = PrefAlign;
9654 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009655 }
9656 }
9657
9658 return Align;
9659}
9660
9661/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9662/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9663/// and it is more than the alignment of the ultimate object, see if we can
9664/// increase the alignment of the ultimate object, making this check succeed.
9665unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9666 unsigned PrefAlign) {
9667 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9668 sizeof(PrefAlign) * CHAR_BIT;
9669 APInt Mask = APInt::getAllOnesValue(BitWidth);
9670 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9671 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9672 unsigned TrailZ = KnownZero.countTrailingOnes();
9673 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9674
9675 if (PrefAlign > Align)
9676 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9677
9678 // We don't need to make any adjustment.
9679 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009680}
9681
Chris Lattner00ae5132008-01-13 23:50:23 +00009682Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009683 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009684 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009685 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009686 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009687
9688 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009689 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009690 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009691 return MI;
9692 }
9693
9694 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9695 // load/store.
9696 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9697 if (MemOpLength == 0) return 0;
9698
Chris Lattnerc669fb62008-01-14 00:28:35 +00009699 // Source and destination pointer types are always "i8*" for intrinsic. See
9700 // if the size is something we can handle with a single primitive load/store.
9701 // A single load+store correctly handles overlapping memory in the memmove
9702 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009703 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009704 if (Size == 0) return MI; // Delete this mem transfer.
9705
9706 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009707 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009708
Chris Lattnerc669fb62008-01-14 00:28:35 +00009709 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009710 Type *NewPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009711 PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009712
9713 // Memcpy forces the use of i8* for the source and destination. That means
9714 // that if you're using memcpy to move one double around, you'll get a cast
9715 // from double* to i8*. We'd much rather use a double load+store rather than
9716 // an i64 load+store, here because this improves the odds that the source or
9717 // dest address will be promotable. See if we can find a better type than the
9718 // integer datatype.
9719 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9720 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009721 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009722 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9723 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009724 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009725 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9726 if (STy->getNumElements() == 1)
9727 SrcETy = STy->getElementType(0);
9728 else
9729 break;
9730 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9731 if (ATy->getNumElements() == 1)
9732 SrcETy = ATy->getElementType();
9733 else
9734 break;
9735 } else
9736 break;
9737 }
9738
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009739 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009740 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009741 }
9742 }
9743
9744
Chris Lattner00ae5132008-01-13 23:50:23 +00009745 // If the memcpy/memmove provides better alignment info than we can
9746 // infer, use it.
9747 SrcAlign = std::max(SrcAlign, CopyAlign);
9748 DstAlign = std::max(DstAlign, CopyAlign);
9749
9750 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9751 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009752 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9753 InsertNewInstBefore(L, *MI);
9754 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9755
9756 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009757 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009758 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009759}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009760
Chris Lattner5af8a912008-04-30 06:39:11 +00009761Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9762 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009763 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009764 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009765 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009766 return MI;
9767 }
9768
9769 // Extract the length and alignment and fill if they are constant.
9770 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9771 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9772 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9773 return 0;
9774 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009775 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009776
9777 // If the length is zero, this is a no-op
9778 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9779
9780 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9781 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009782 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009783
9784 Value *Dest = MI->getDest();
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009785 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009786
9787 // Alignment 0 is identity for alignment 1 for memset, but not store.
9788 if (Alignment == 0) Alignment = 1;
9789
9790 // Extract the fill value and store.
9791 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009792 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009793 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009794
9795 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009796 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009797 return MI;
9798 }
9799
9800 return 0;
9801}
9802
9803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009804/// visitCallInst - CallInst simplification. This mostly only handles folding
9805/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9806/// the heavy lifting.
9807///
9808Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009809 // If the caller function is nounwind, mark the call as nounwind, even if the
9810 // callee isn't.
9811 if (CI.getParent()->getParent()->doesNotThrow() &&
9812 !CI.doesNotThrow()) {
9813 CI.setDoesNotThrow();
9814 return &CI;
9815 }
9816
9817
9818
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009819 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9820 if (!II) return visitCallSite(&CI);
9821
9822 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9823 // visitCallSite.
9824 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9825 bool Changed = false;
9826
9827 // memmove/cpy/set of zero bytes is a noop.
9828 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9829 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9830
9831 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9832 if (CI->getZExtValue() == 1) {
9833 // Replace the instruction with just byte operations. We would
9834 // transform other cases to loads/stores, but we don't know if
9835 // alignment is sufficient.
9836 }
9837 }
9838
9839 // If we have a memmove and the source operation is a constant global,
9840 // then the source and dest pointers can't alias, so we can change this
9841 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009842 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009843 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9844 if (GVSrc->isConstant()) {
9845 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009846 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9847 const Type *Tys[1];
9848 Tys[0] = CI.getOperand(3)->getType();
9849 CI.setOperand(0,
9850 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009851 Changed = true;
9852 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009853
9854 // memmove(x,x,size) -> noop.
9855 if (MMI->getSource() == MMI->getDest())
9856 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009857 }
9858
9859 // If we can determine a pointer alignment that is bigger than currently
9860 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009861 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009862 if (Instruction *I = SimplifyMemTransfer(MI))
9863 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009864 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9865 if (Instruction *I = SimplifyMemSet(MSI))
9866 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009867 }
9868
9869 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009870 }
9871
9872 switch (II->getIntrinsicID()) {
9873 default: break;
9874 case Intrinsic::bswap:
9875 // bswap(bswap(x)) -> x
9876 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9877 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9878 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9879 break;
9880 case Intrinsic::ppc_altivec_lvx:
9881 case Intrinsic::ppc_altivec_lvxl:
9882 case Intrinsic::x86_sse_loadu_ps:
9883 case Intrinsic::x86_sse2_loadu_pd:
9884 case Intrinsic::x86_sse2_loadu_dq:
9885 // Turn PPC lvx -> load if the pointer is known aligned.
9886 // Turn X86 loadups -> load if the pointer is known aligned.
9887 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9888 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009889 PointerType::getUnqual(II->getType()),
Chris Lattner989ba312008-06-18 04:33:20 +00009890 CI);
9891 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009892 }
Chris Lattner989ba312008-06-18 04:33:20 +00009893 break;
9894 case Intrinsic::ppc_altivec_stvx:
9895 case Intrinsic::ppc_altivec_stvxl:
9896 // Turn stvx -> store if the pointer is known aligned.
9897 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9898 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009899 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009900 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9901 return new StoreInst(II->getOperand(1), Ptr);
9902 }
9903 break;
9904 case Intrinsic::x86_sse_storeu_ps:
9905 case Intrinsic::x86_sse2_storeu_pd:
9906 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009907 // Turn X86 storeu -> store if the pointer is known aligned.
9908 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9909 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009910 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009911 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9912 return new StoreInst(II->getOperand(2), Ptr);
9913 }
9914 break;
9915
9916 case Intrinsic::x86_sse_cvttss2si: {
9917 // These intrinsics only demands the 0th element of its input vector. If
9918 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009919 unsigned VWidth =
9920 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9921 APInt DemandedElts(VWidth, 1);
9922 APInt UndefElts(VWidth, 0);
9923 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009924 UndefElts)) {
9925 II->setOperand(1, V);
9926 return II;
9927 }
9928 break;
9929 }
9930
9931 case Intrinsic::ppc_altivec_vperm:
9932 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9933 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9934 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009935
Chris Lattner989ba312008-06-18 04:33:20 +00009936 // Check that all of the elements are integer constants or undefs.
9937 bool AllEltsOk = true;
9938 for (unsigned i = 0; i != 16; ++i) {
9939 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9940 !isa<UndefValue>(Mask->getOperand(i))) {
9941 AllEltsOk = false;
9942 break;
9943 }
9944 }
9945
9946 if (AllEltsOk) {
9947 // Cast the input vectors to byte vectors.
9948 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9949 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00009950 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009951
Chris Lattner989ba312008-06-18 04:33:20 +00009952 // Only extract each element once.
9953 Value *ExtractedElts[32];
9954 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9955
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009956 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009957 if (isa<UndefValue>(Mask->getOperand(i)))
9958 continue;
9959 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9960 Idx &= 31; // Match the hardware behavior.
9961
9962 if (ExtractedElts[Idx] == 0) {
9963 Instruction *Elt =
Eric Christopher1ba36872009-07-25 02:28:41 +00009964 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Andersoneacb44d2009-07-24 23:12:02 +00009965 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009966 InsertNewInstBefore(Elt, CI);
9967 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009968 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009969
Chris Lattner989ba312008-06-18 04:33:20 +00009970 // Insert this value into the result vector.
9971 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneacb44d2009-07-24 23:12:02 +00009972 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00009973 "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009974 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009975 }
Chris Lattner989ba312008-06-18 04:33:20 +00009976 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009977 }
Chris Lattner989ba312008-06-18 04:33:20 +00009978 }
9979 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009980
Chris Lattner989ba312008-06-18 04:33:20 +00009981 case Intrinsic::stackrestore: {
9982 // If the save is right next to the restore, remove the restore. This can
9983 // happen when variable allocas are DCE'd.
9984 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9985 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9986 BasicBlock::iterator BI = SS;
9987 if (&*++BI == II)
9988 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009989 }
Chris Lattner989ba312008-06-18 04:33:20 +00009990 }
9991
9992 // Scan down this block to see if there is another stack restore in the
9993 // same block without an intervening call/alloca.
9994 BasicBlock::iterator BI = II;
9995 TerminatorInst *TI = II->getParent()->getTerminator();
9996 bool CannotRemove = false;
9997 for (++BI; &*BI != TI; ++BI) {
9998 if (isa<AllocaInst>(BI)) {
9999 CannotRemove = true;
10000 break;
10001 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010002 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10003 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10004 // If there is a stackrestore below this one, remove this one.
10005 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10006 return EraseInstFromFunction(CI);
10007 // Otherwise, ignore the intrinsic.
10008 } else {
10009 // If we found a non-intrinsic call, we can't remove the stack
10010 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010011 CannotRemove = true;
10012 break;
10013 }
Chris Lattner989ba312008-06-18 04:33:20 +000010014 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010015 }
Chris Lattner989ba312008-06-18 04:33:20 +000010016
10017 // If the stack restore is in a return/unwind block and if there are no
10018 // allocas or calls between the restore and the return, nuke the restore.
10019 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10020 return EraseInstFromFunction(CI);
10021 break;
10022 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010023 }
10024
10025 return visitCallSite(II);
10026}
10027
10028// InvokeInst simplification
10029//
10030Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10031 return visitCallSite(&II);
10032}
10033
Dale Johannesen96021832008-04-25 21:16:07 +000010034/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10035/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010036static bool isSafeToEliminateVarargsCast(const CallSite CS,
10037 const CastInst * const CI,
10038 const TargetData * const TD,
10039 const int ix) {
10040 if (!CI->isLosslessCast())
10041 return false;
10042
10043 // The size of ByVal arguments is derived from the type, so we
10044 // can't change to a type with a different size. If the size were
10045 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010046 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010047 return true;
10048
10049 const Type* SrcTy =
10050 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10051 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10052 if (!SrcTy->isSized() || !DstTy->isSized())
10053 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010054 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010055 return false;
10056 return true;
10057}
10058
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010059// visitCallSite - Improvements for call and invoke instructions.
10060//
10061Instruction *InstCombiner::visitCallSite(CallSite CS) {
10062 bool Changed = false;
10063
10064 // If the callee is a constexpr cast of a function, attempt to move the cast
10065 // to the arguments of the call/invoke.
10066 if (transformConstExprCastCall(CS)) return 0;
10067
10068 Value *Callee = CS.getCalledValue();
10069
10070 if (Function *CalleeF = dyn_cast<Function>(Callee))
10071 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10072 Instruction *OldCall = CS.getInstruction();
10073 // If the call and callee calling conventions don't match, this call must
10074 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010075 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000010076 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010077 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010078 if (!OldCall->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000010079 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010080 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10081 return EraseInstFromFunction(*OldCall);
10082 return 0;
10083 }
10084
10085 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10086 // This instruction is not reachable, just remove it. We insert a store to
10087 // undef so that we know that this code is not reachable, despite the fact
10088 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010089 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000010090 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010091 CS.getInstruction());
10092
10093 if (!CS.getInstruction()->use_empty())
10094 CS.getInstruction()->
Owen Andersonb99ecca2009-07-30 23:03:37 +000010095 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010096
10097 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10098 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010099 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010100 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010101 }
10102 return EraseInstFromFunction(*CS.getInstruction());
10103 }
10104
Duncan Sands74833f22007-09-17 10:26:40 +000010105 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10106 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10107 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10108 return transformCallThroughTrampoline(CS);
10109
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010110 const PointerType *PTy = cast<PointerType>(Callee->getType());
10111 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10112 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010113 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010114 // See if we can optimize any arguments passed through the varargs area of
10115 // the call.
10116 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010117 E = CS.arg_end(); I != E; ++I, ++ix) {
10118 CastInst *CI = dyn_cast<CastInst>(*I);
10119 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10120 *I = CI->getOperand(0);
10121 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010122 }
Dale Johannesen35615462008-04-23 18:34:37 +000010123 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010124 }
10125
Duncan Sands2937e352007-12-19 21:13:37 +000010126 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010127 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010128 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010129 Changed = true;
10130 }
10131
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010132 return Changed ? CS.getInstruction() : 0;
10133}
10134
10135// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10136// attempt to move the cast to the arguments of the call/invoke.
10137//
10138bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10139 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10140 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10141 if (CE->getOpcode() != Instruction::BitCast ||
10142 !isa<Function>(CE->getOperand(0)))
10143 return false;
10144 Function *Callee = cast<Function>(CE->getOperand(0));
10145 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010146 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010147
10148 // Okay, this is a cast from a function to a different type. Unless doing so
10149 // would cause a type conversion of one of our arguments, change this call to
10150 // be a direct call with arguments casted to the appropriate types.
10151 //
10152 const FunctionType *FT = Callee->getFunctionType();
10153 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010154 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010155
Duncan Sands7901ce12008-06-01 07:38:42 +000010156 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010157 return false; // TODO: Handle multiple return values.
10158
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010159 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010160 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010161 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010162 // Conversion is ok if changing from one pointer type to another or from
10163 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010164 !((isa<PointerType>(OldRetTy) || !TD ||
10165 OldRetTy == TD->getIntPtrType()) &&
10166 (isa<PointerType>(NewRetTy) || !TD ||
10167 NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010168 return false; // Cannot transform this return value.
10169
Duncan Sands5c489582008-01-06 10:12:28 +000010170 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010171 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +000010172 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010173 return false; // Cannot transform this return value.
10174
Chris Lattner1c8733e2008-03-12 17:45:29 +000010175 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010176 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010177 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010178 return false; // Attribute not compatible with transformed value.
10179 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010180
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010181 // If the callsite is an invoke instruction, and the return value is used by
10182 // a PHI node in a successor, we cannot change the return type of the call
10183 // because there is no place to put the cast instruction (without breaking
10184 // the critical edge). Bail out in this case.
10185 if (!Caller->use_empty())
10186 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10187 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10188 UI != E; ++UI)
10189 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10190 if (PN->getParent() == II->getNormalDest() ||
10191 PN->getParent() == II->getUnwindDest())
10192 return false;
10193 }
10194
10195 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10196 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10197
10198 CallSite::arg_iterator AI = CS.arg_begin();
10199 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10200 const Type *ParamTy = FT->getParamType(i);
10201 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010202
10203 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010204 return false; // Cannot transform this parameter value.
10205
Devang Patelf2a4a922008-09-26 22:53:05 +000010206 if (CallerPAL.getParamAttributes(i + 1)
10207 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010208 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010209
Duncan Sands7901ce12008-06-01 07:38:42 +000010210 // Converting from one pointer type to another or between a pointer and an
10211 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010212 bool isConvertible = ActTy == ParamTy ||
Dan Gohmana80e2712009-07-21 23:21:54 +000010213 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10214 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010215 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010216 }
10217
10218 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10219 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010220 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010221
Chris Lattner1c8733e2008-03-12 17:45:29 +000010222 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10223 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010224 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010225 // won't be dropping them. Check that these extra arguments have attributes
10226 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010227 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10228 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010229 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010230 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010231 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010232 return false;
10233 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010234
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010235 // Okay, we decided that this is a safe thing to do: go ahead and start
10236 // inserting cast instructions as necessary...
10237 std::vector<Value*> Args;
10238 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010239 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010240 attrVec.reserve(NumCommonArgs);
10241
10242 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010243 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010244
10245 // If the return value is not being used, the type may not be compatible
10246 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010247 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010248
10249 // Add the new return attributes.
10250 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010251 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010252
10253 AI = CS.arg_begin();
10254 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10255 const Type *ParamTy = FT->getParamType(i);
10256 if ((*AI)->getType() == ParamTy) {
10257 Args.push_back(*AI);
10258 } else {
10259 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10260 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010261 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010262 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10263 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010264
10265 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010266 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010267 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010268 }
10269
10270 // If the function takes more arguments than the call was taking, add them
10271 // now...
10272 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010273 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010274
10275 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010276 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010277 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010278 errs() << "WARNING: While resolving call to function '"
10279 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010280 } else {
10281 // Add all of the arguments in their promoted form to the arg list...
10282 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10283 const Type *PTy = getPromotedType((*AI)->getType());
10284 if (PTy != (*AI)->getType()) {
10285 // Must promote to pass through va_arg area!
10286 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10287 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010288 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010289 InsertNewInstBefore(Cast, *Caller);
10290 Args.push_back(Cast);
10291 } else {
10292 Args.push_back(*AI);
10293 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010294
Duncan Sands4ced1f82008-01-13 08:02:44 +000010295 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010296 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010297 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010298 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010299 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010300 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010301
Devang Patelf2a4a922008-09-26 22:53:05 +000010302 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10303 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10304
Duncan Sands7901ce12008-06-01 07:38:42 +000010305 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010306 Caller->setName(""); // Void type should not have a name.
10307
Eric Christopher3e7381f2009-07-25 02:45:27 +000010308 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10309 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010310
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010311 Instruction *NC;
10312 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010313 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010314 Args.begin(), Args.end(),
10315 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010316 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010317 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010318 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010319 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10320 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010321 CallInst *CI = cast<CallInst>(Caller);
10322 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010323 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010324 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010325 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010326 }
10327
10328 // Insert a cast of the return type as necessary.
10329 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010330 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010331 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010332 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010333 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010334 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010335
10336 // If this is an invoke instruction, we should insert it after the first
10337 // non-phi, instruction in the normal successor block.
10338 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010339 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010340 InsertNewInstBefore(NC, *I);
10341 } else {
10342 // Otherwise, it's a call, just insert cast right after the call instr
10343 InsertNewInstBefore(NC, *Caller);
10344 }
10345 AddUsersToWorkList(*Caller);
10346 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010347 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010348 }
10349 }
10350
10351 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10352 Caller->replaceAllUsesWith(NV);
10353 Caller->eraseFromParent();
10354 RemoveFromWorkList(Caller);
10355 return true;
10356}
10357
Duncan Sands74833f22007-09-17 10:26:40 +000010358// transformCallThroughTrampoline - Turn a call to a function created by the
10359// init_trampoline intrinsic into a direct call to the underlying function.
10360//
10361Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10362 Value *Callee = CS.getCalledValue();
10363 const PointerType *PTy = cast<PointerType>(Callee->getType());
10364 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010365 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010366
10367 // If the call already has the 'nest' attribute somewhere then give up -
10368 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010369 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010370 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010371
10372 IntrinsicInst *Tramp =
10373 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10374
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010375 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010376 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10377 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10378
Devang Pateld222f862008-09-25 21:00:45 +000010379 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010380 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010381 unsigned NestIdx = 1;
10382 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010383 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010384
10385 // Look for a parameter marked with the 'nest' attribute.
10386 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10387 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010388 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010389 // Record the parameter type and any other attributes.
10390 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010391 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010392 break;
10393 }
10394
10395 if (NestTy) {
10396 Instruction *Caller = CS.getInstruction();
10397 std::vector<Value*> NewArgs;
10398 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10399
Devang Pateld222f862008-09-25 21:00:45 +000010400 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010401 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010402
Duncan Sands74833f22007-09-17 10:26:40 +000010403 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010404 // mean appending it. Likewise for attributes.
10405
Devang Patelf2a4a922008-09-26 22:53:05 +000010406 // Add any result attributes.
10407 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010408 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010409
Duncan Sands74833f22007-09-17 10:26:40 +000010410 {
10411 unsigned Idx = 1;
10412 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10413 do {
10414 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010415 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010416 Value *NestVal = Tramp->getOperand(3);
10417 if (NestVal->getType() != NestTy)
10418 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10419 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010420 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010421 }
10422
10423 if (I == E)
10424 break;
10425
Duncan Sands48b81112008-01-14 19:52:09 +000010426 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010427 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010428 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010429 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010430 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010431
10432 ++Idx, ++I;
10433 } while (1);
10434 }
10435
Devang Patelf2a4a922008-09-26 22:53:05 +000010436 // Add any function attributes.
10437 if (Attributes Attr = Attrs.getFnAttributes())
10438 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10439
Duncan Sands74833f22007-09-17 10:26:40 +000010440 // The trampoline may have been bitcast to a bogus type (FTy).
10441 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010442 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010443
Duncan Sands74833f22007-09-17 10:26:40 +000010444 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010445 NewTypes.reserve(FTy->getNumParams()+1);
10446
Duncan Sands74833f22007-09-17 10:26:40 +000010447 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010448 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010449 {
10450 unsigned Idx = 1;
10451 FunctionType::param_iterator I = FTy->param_begin(),
10452 E = FTy->param_end();
10453
10454 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010455 if (Idx == NestIdx)
10456 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010457 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010458
10459 if (I == E)
10460 break;
10461
Duncan Sands48b81112008-01-14 19:52:09 +000010462 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010463 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010464
10465 ++Idx, ++I;
10466 } while (1);
10467 }
10468
10469 // Replace the trampoline call with a direct call. Let the generic
10470 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010471 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010472 FTy->isVarArg());
10473 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010474 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010475 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010476 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010477 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10478 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010479
10480 Instruction *NewCaller;
10481 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010482 NewCaller = InvokeInst::Create(NewCallee,
10483 II->getNormalDest(), II->getUnwindDest(),
10484 NewArgs.begin(), NewArgs.end(),
10485 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010486 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010487 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010488 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010489 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10490 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010491 if (cast<CallInst>(Caller)->isTailCall())
10492 cast<CallInst>(NewCaller)->setTailCall();
10493 cast<CallInst>(NewCaller)->
10494 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010495 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010496 }
10497 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10498 Caller->replaceAllUsesWith(NewCaller);
10499 Caller->eraseFromParent();
10500 RemoveFromWorkList(Caller);
10501 return 0;
10502 }
10503 }
10504
10505 // Replace the trampoline call with a direct call. Since there is no 'nest'
10506 // parameter, there is no need to adjust the argument list. Let the generic
10507 // code sort out any function type mismatches.
10508 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010509 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010510 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010511 CS.setCalledFunction(NewCallee);
10512 return CS.getInstruction();
10513}
10514
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010515/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10516/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10517/// and a single binop.
10518Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10519 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010520 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010521 unsigned Opc = FirstInst->getOpcode();
10522 Value *LHSVal = FirstInst->getOperand(0);
10523 Value *RHSVal = FirstInst->getOperand(1);
10524
10525 const Type *LHSType = LHSVal->getType();
10526 const Type *RHSType = RHSVal->getType();
10527
10528 // Scan to see if all operands are the same opcode, all have one use, and all
10529 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010530 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010531 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10532 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10533 // Verify type of the LHS matches so we don't fold cmp's of different
10534 // types or GEP's with different index types.
10535 I->getOperand(0)->getType() != LHSType ||
10536 I->getOperand(1)->getType() != RHSType)
10537 return 0;
10538
10539 // If they are CmpInst instructions, check their predicates
10540 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10541 if (cast<CmpInst>(I)->getPredicate() !=
10542 cast<CmpInst>(FirstInst)->getPredicate())
10543 return 0;
10544
10545 // Keep track of which operand needs a phi node.
10546 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10547 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10548 }
10549
Chris Lattner30078012008-12-01 03:42:51 +000010550 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010551
10552 Value *InLHS = FirstInst->getOperand(0);
10553 Value *InRHS = FirstInst->getOperand(1);
10554 PHINode *NewLHS = 0, *NewRHS = 0;
10555 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010556 NewLHS = PHINode::Create(LHSType,
10557 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010558 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10559 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10560 InsertNewInstBefore(NewLHS, PN);
10561 LHSVal = NewLHS;
10562 }
10563
10564 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010565 NewRHS = PHINode::Create(RHSType,
10566 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010567 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10568 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10569 InsertNewInstBefore(NewRHS, PN);
10570 RHSVal = NewRHS;
10571 }
10572
10573 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010574 if (NewLHS || NewRHS) {
10575 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10576 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10577 if (NewLHS) {
10578 Value *NewInLHS = InInst->getOperand(0);
10579 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10580 }
10581 if (NewRHS) {
10582 Value *NewInRHS = InInst->getOperand(1);
10583 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10584 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010585 }
10586 }
10587
10588 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010589 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010590 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson6601fcd2009-07-09 23:48:35 +000010591 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10592 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010593}
10594
Chris Lattner9e1916e2008-12-01 02:34:36 +000010595Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10596 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10597
10598 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10599 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010600 // This is true if all GEP bases are allocas and if all indices into them are
10601 // constants.
10602 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010603
10604 // Scan to see if all operands are the same opcode, all have one use, and all
10605 // kill their operands (i.e. the operands have one use).
10606 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10607 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10608 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10609 GEP->getNumOperands() != FirstInst->getNumOperands())
10610 return 0;
10611
Chris Lattneradf354b2009-02-21 00:46:50 +000010612 // Keep track of whether or not all GEPs are of alloca pointers.
10613 if (AllBasePointersAreAllocas &&
10614 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10615 !GEP->hasAllConstantIndices()))
10616 AllBasePointersAreAllocas = false;
10617
Chris Lattner9e1916e2008-12-01 02:34:36 +000010618 // Compare the operand lists.
10619 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10620 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10621 continue;
10622
10623 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10624 // if one of the PHIs has a constant for the index. The index may be
10625 // substantially cheaper to compute for the constants, so making it a
10626 // variable index could pessimize the path. This also handles the case
10627 // for struct indices, which must always be constant.
10628 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10629 isa<ConstantInt>(GEP->getOperand(op)))
10630 return 0;
10631
10632 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10633 return 0;
10634 FixedOperands[op] = 0; // Needs a PHI.
10635 }
10636 }
10637
Chris Lattneradf354b2009-02-21 00:46:50 +000010638 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010639 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010640 // offset calculation, but all the predecessors will have to materialize the
10641 // stack address into a register anyway. We'd actually rather *clone* the
10642 // load up into the predecessors so that we have a load of a gep of an alloca,
10643 // which can usually all be folded into the load.
10644 if (AllBasePointersAreAllocas)
10645 return 0;
10646
Chris Lattner9e1916e2008-12-01 02:34:36 +000010647 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10648 // that is variable.
10649 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10650
10651 bool HasAnyPHIs = false;
10652 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10653 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10654 Value *FirstOp = FirstInst->getOperand(i);
10655 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10656 FirstOp->getName()+".pn");
10657 InsertNewInstBefore(NewPN, PN);
10658
10659 NewPN->reserveOperandSpace(e);
10660 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10661 OperandPhis[i] = NewPN;
10662 FixedOperands[i] = NewPN;
10663 HasAnyPHIs = true;
10664 }
10665
10666
10667 // Add all operands to the new PHIs.
10668 if (HasAnyPHIs) {
10669 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10670 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10671 BasicBlock *InBB = PN.getIncomingBlock(i);
10672
10673 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10674 if (PHINode *OpPhi = OperandPhis[op])
10675 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10676 }
10677 }
10678
10679 Value *Base = FixedOperands[0];
Dan Gohman17f46f72009-07-28 01:40:03 +000010680 GetElementPtrInst *GEP =
10681 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10682 FixedOperands.end());
10683 if (cast<GEPOperator>(FirstInst)->isInBounds())
10684 cast<GEPOperator>(GEP)->setIsInBounds(true);
10685 return GEP;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010686}
10687
10688
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010689/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10690/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010691/// obvious the value of the load is not changed from the point of the load to
10692/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010693///
10694/// Finally, it is safe, but not profitable, to sink a load targetting a
10695/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10696/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010697static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010698 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10699
10700 for (++BBI; BBI != E; ++BBI)
10701 if (BBI->mayWriteToMemory())
10702 return false;
10703
10704 // Check for non-address taken alloca. If not address-taken already, it isn't
10705 // profitable to do this xform.
10706 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10707 bool isAddressTaken = false;
10708 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10709 UI != E; ++UI) {
10710 if (isa<LoadInst>(UI)) continue;
10711 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10712 // If storing TO the alloca, then the address isn't taken.
10713 if (SI->getOperand(1) == AI) continue;
10714 }
10715 isAddressTaken = true;
10716 break;
10717 }
10718
Chris Lattneradf354b2009-02-21 00:46:50 +000010719 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010720 return false;
10721 }
10722
Chris Lattneradf354b2009-02-21 00:46:50 +000010723 // If this load is a load from a GEP with a constant offset from an alloca,
10724 // then we don't want to sink it. In its present form, it will be
10725 // load [constant stack offset]. Sinking it will cause us to have to
10726 // materialize the stack addresses in each predecessor in a register only to
10727 // do a shared load from register in the successor.
10728 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10729 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10730 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10731 return false;
10732
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010733 return true;
10734}
10735
10736
10737// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10738// operator and they all are only used by the PHI, PHI together their
10739// inputs, and do the operation once, to the result of the PHI.
10740Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10741 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10742
10743 // Scan the instruction, looking for input operations that can be folded away.
10744 // If all input operands to the phi are the same instruction (e.g. a cast from
10745 // the same type or "+42") we can pull the operation through the PHI, reducing
10746 // code size and simplifying code.
10747 Constant *ConstantOp = 0;
10748 const Type *CastSrcTy = 0;
10749 bool isVolatile = false;
10750 if (isa<CastInst>(FirstInst)) {
10751 CastSrcTy = FirstInst->getOperand(0)->getType();
10752 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10753 // Can fold binop, compare or shift here if the RHS is a constant,
10754 // otherwise call FoldPHIArgBinOpIntoPHI.
10755 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10756 if (ConstantOp == 0)
10757 return FoldPHIArgBinOpIntoPHI(PN);
10758 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10759 isVolatile = LI->isVolatile();
10760 // We can't sink the load if the loaded value could be modified between the
10761 // load and the PHI.
10762 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010763 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010764 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010765
10766 // If the PHI is of volatile loads and the load block has multiple
10767 // successors, sinking it would remove a load of the volatile value from
10768 // the path through the other successor.
10769 if (isVolatile &&
10770 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10771 return 0;
10772
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010773 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010774 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010775 } else {
10776 return 0; // Cannot fold this operation.
10777 }
10778
10779 // Check to see if all arguments are the same operation.
10780 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10781 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10782 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10783 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10784 return 0;
10785 if (CastSrcTy) {
10786 if (I->getOperand(0)->getType() != CastSrcTy)
10787 return 0; // Cast operation must match.
10788 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10789 // We can't sink the load if the loaded value could be modified between
10790 // the load and the PHI.
10791 if (LI->isVolatile() != isVolatile ||
10792 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010793 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010794 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010795
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010796 // If the PHI is of volatile loads and the load block has multiple
10797 // successors, sinking it would remove a load of the volatile value from
10798 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010799 if (isVolatile &&
10800 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10801 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010802
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010803 } else if (I->getOperand(1) != ConstantOp) {
10804 return 0;
10805 }
10806 }
10807
10808 // Okay, they are all the same operation. Create a new PHI node of the
10809 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010810 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10811 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010812 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10813
10814 Value *InVal = FirstInst->getOperand(0);
10815 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10816
10817 // Add all operands to the new PHI.
10818 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10819 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10820 if (NewInVal != InVal)
10821 InVal = 0;
10822 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10823 }
10824
10825 Value *PhiVal;
10826 if (InVal) {
10827 // The new PHI unions all of the same values together. This is really
10828 // common, so we handle it intelligently here for compile-time speed.
10829 PhiVal = InVal;
10830 delete NewPN;
10831 } else {
10832 InsertNewInstBefore(NewPN, PN);
10833 PhiVal = NewPN;
10834 }
10835
10836 // Insert and return the new operation.
10837 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010838 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010839 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010840 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010841 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson6601fcd2009-07-09 23:48:35 +000010842 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010843 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010844 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10845
10846 // If this was a volatile load that we are merging, make sure to loop through
10847 // and mark all the input loads as non-volatile. If we don't do this, we will
10848 // insert a new volatile load and the old ones will not be deletable.
10849 if (isVolatile)
10850 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10851 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10852
10853 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010854}
10855
10856/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10857/// that is dead.
10858static bool DeadPHICycle(PHINode *PN,
10859 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10860 if (PN->use_empty()) return true;
10861 if (!PN->hasOneUse()) return false;
10862
10863 // Remember this node, and if we find the cycle, return.
10864 if (!PotentiallyDeadPHIs.insert(PN))
10865 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010866
10867 // Don't scan crazily complex things.
10868 if (PotentiallyDeadPHIs.size() == 16)
10869 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010870
10871 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10872 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10873
10874 return false;
10875}
10876
Chris Lattner27b695d2007-11-06 21:52:06 +000010877/// PHIsEqualValue - Return true if this phi node is always equal to
10878/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10879/// z = some value; x = phi (y, z); y = phi (x, z)
10880static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10881 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10882 // See if we already saw this PHI node.
10883 if (!ValueEqualPHIs.insert(PN))
10884 return true;
10885
10886 // Don't scan crazily complex things.
10887 if (ValueEqualPHIs.size() == 16)
10888 return false;
10889
10890 // Scan the operands to see if they are either phi nodes or are equal to
10891 // the value.
10892 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10893 Value *Op = PN->getIncomingValue(i);
10894 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10895 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10896 return false;
10897 } else if (Op != NonPhiInVal)
10898 return false;
10899 }
10900
10901 return true;
10902}
10903
10904
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010905// PHINode simplification
10906//
10907Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10908 // If LCSSA is around, don't mess with Phi nodes
10909 if (MustPreserveLCSSA) return 0;
10910
10911 if (Value *V = PN.hasConstantValue())
10912 return ReplaceInstUsesWith(PN, V);
10913
10914 // If all PHI operands are the same operation, pull them through the PHI,
10915 // reducing code size.
10916 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010917 isa<Instruction>(PN.getIncomingValue(1)) &&
10918 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10919 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10920 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10921 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010922 PN.getIncomingValue(0)->hasOneUse())
10923 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10924 return Result;
10925
10926 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10927 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10928 // PHI)... break the cycle.
10929 if (PN.hasOneUse()) {
10930 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10931 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10932 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10933 PotentiallyDeadPHIs.insert(&PN);
10934 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010935 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010936 }
10937
10938 // If this phi has a single use, and if that use just computes a value for
10939 // the next iteration of a loop, delete the phi. This occurs with unused
10940 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10941 // common case here is good because the only other things that catch this
10942 // are induction variable analysis (sometimes) and ADCE, which is only run
10943 // late.
10944 if (PHIUser->hasOneUse() &&
10945 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10946 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010947 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010948 }
10949 }
10950
Chris Lattner27b695d2007-11-06 21:52:06 +000010951 // We sometimes end up with phi cycles that non-obviously end up being the
10952 // same value, for example:
10953 // z = some value; x = phi (y, z); y = phi (x, z)
10954 // where the phi nodes don't necessarily need to be in the same block. Do a
10955 // quick check to see if the PHI node only contains a single non-phi value, if
10956 // so, scan to see if the phi cycle is actually equal to that value.
10957 {
10958 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10959 // Scan for the first non-phi operand.
10960 while (InValNo != NumOperandVals &&
10961 isa<PHINode>(PN.getIncomingValue(InValNo)))
10962 ++InValNo;
10963
10964 if (InValNo != NumOperandVals) {
10965 Value *NonPhiInVal = PN.getOperand(InValNo);
10966
10967 // Scan the rest of the operands to see if there are any conflicts, if so
10968 // there is no need to recursively scan other phis.
10969 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10970 Value *OpVal = PN.getIncomingValue(InValNo);
10971 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10972 break;
10973 }
10974
10975 // If we scanned over all operands, then we have one unique value plus
10976 // phi values. Scan PHI nodes to see if they all merge in each other or
10977 // the value.
10978 if (InValNo == NumOperandVals) {
10979 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10980 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10981 return ReplaceInstUsesWith(PN, NonPhiInVal);
10982 }
10983 }
10984 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010985 return 0;
10986}
10987
10988static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10989 Instruction *InsertPoint,
10990 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000010991 unsigned PtrSize = DTy->getScalarSizeInBits();
10992 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010993 // We must cast correctly to the pointer type. Ensure that we
10994 // sign extend the integer value if it is smaller as this is
10995 // used for address computation.
10996 Instruction::CastOps opcode =
10997 (VTySize < PtrSize ? Instruction::SExt :
10998 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10999 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11000}
11001
11002
11003Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11004 Value *PtrOp = GEP.getOperand(0);
11005 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
11006 // If so, eliminate the noop.
11007 if (GEP.getNumOperands() == 1)
11008 return ReplaceInstUsesWith(GEP, PtrOp);
11009
11010 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011011 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011012
11013 bool HasZeroPointerIndex = false;
11014 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11015 HasZeroPointerIndex = C->isNullValue();
11016
11017 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11018 return ReplaceInstUsesWith(GEP, PtrOp);
11019
11020 // Eliminate unneeded casts for indices.
11021 bool MadeChange = false;
11022
11023 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011024 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11025 i != e; ++i, ++GTI) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011026 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000011027 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011028 if (CI->getOpcode() == Instruction::ZExt ||
11029 CI->getOpcode() == Instruction::SExt) {
11030 const Type *SrcTy = CI->getOperand(0)->getType();
11031 // We can eliminate a cast from i32 to i64 iff the target
11032 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000011033 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011034 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000011035 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011036 }
11037 }
11038 }
11039 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000011040 // to what we need. If narrower, sign-extend it to what we need.
11041 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011042 // insert it. This explicit cast can make subsequent optimizations more
11043 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000011044 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011045 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011046 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson02b48c32009-07-29 18:55:55 +000011047 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011048 MadeChange = true;
11049 } else {
11050 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11051 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011052 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011053 MadeChange = true;
11054 }
Eric Christopher3e7381f2009-07-25 02:45:27 +000011055 } else if (TD->getTypeSizeInBits(Op->getType())
11056 < TD->getPointerSizeInBits()) {
Dan Gohman5d639ed2008-09-11 23:06:38 +000011057 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson02b48c32009-07-29 18:55:55 +000011058 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
Dan Gohman5d639ed2008-09-11 23:06:38 +000011059 MadeChange = true;
11060 } else {
11061 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11062 GEP);
11063 *i = Op;
11064 MadeChange = true;
11065 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011066 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011067 }
11068 }
11069 if (MadeChange) return &GEP;
11070
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011071 // Combine Indices - If the source pointer to this getelementptr instruction
11072 // is a getelementptr instruction, combine the indices of the two
11073 // getelementptr instructions into a single instruction.
11074 //
11075 SmallVector<Value*, 8> SrcGEPOperands;
Dan Gohman17f46f72009-07-28 01:40:03 +000011076 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11077 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011078 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011079 if (!Src->isInBounds())
11080 BothInBounds = false;
11081 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011082
11083 if (!SrcGEPOperands.empty()) {
11084 // Note that if our source is a gep chain itself that we wait for that
11085 // chain to be resolved before we perform this transformation. This
11086 // avoids us creating a TON of code in some cases.
11087 //
11088 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11089 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11090 return 0; // Wait until our source is folded to completion.
11091
11092 SmallVector<Value*, 8> Indices;
11093
11094 // Find out whether the last index in the source GEP is a sequential idx.
11095 bool EndsWithSequential = false;
11096 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11097 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11098 EndsWithSequential = !isa<StructType>(*I);
11099
11100 // Can we combine the two pointer arithmetics offsets?
11101 if (EndsWithSequential) {
11102 // Replace: gep (gep %P, long B), long A, ...
11103 // With: T = long A+B; gep %P, T, ...
11104 //
11105 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011106 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011107 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011108 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011109 Sum = SO1;
11110 } else {
11111 // If they aren't the same type, convert both to an integer of the
11112 // target's pointer size.
11113 if (SO1->getType() != GO1->getType()) {
11114 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011115 SO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011116 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011117 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011118 GO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011119 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmana80e2712009-07-21 23:21:54 +000011120 } else if (TD) {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011121 unsigned PS = TD->getPointerSizeInBits();
11122 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011123 // Convert GO1 to SO1's type.
11124 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11125
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011126 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011127 // Convert SO1 to GO1's type.
11128 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11129 } else {
11130 const Type *PT = TD->getIntPtrType();
11131 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11132 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11133 }
11134 }
11135 }
11136 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Anderson02b48c32009-07-29 18:55:55 +000011137 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
Owen Anderson24be4c12009-07-03 00:17:18 +000011138 cast<Constant>(GO1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011139 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011140 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011141 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11142 }
11143 }
11144
11145 // Recycle the GEP we already have if possible.
11146 if (SrcGEPOperands.size() == 2) {
11147 GEP.setOperand(0, SrcGEPOperands[0]);
11148 GEP.setOperand(1, Sum);
11149 return &GEP;
11150 } else {
11151 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11152 SrcGEPOperands.end()-1);
11153 Indices.push_back(Sum);
11154 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11155 }
11156 } else if (isa<Constant>(*GEP.idx_begin()) &&
11157 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11158 SrcGEPOperands.size() != 1) {
11159 // Otherwise we can do the fold if the first index of the GEP is a zero
11160 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11161 SrcGEPOperands.end());
11162 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11163 }
11164
Dan Gohman17f46f72009-07-28 01:40:03 +000011165 if (!Indices.empty()) {
11166 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11167 Indices.begin(),
11168 Indices.end(),
11169 GEP.getName());
11170 if (BothInBounds)
11171 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11172 return NewGEP;
11173 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011174
11175 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11176 // GEP of global variable. If all of the indices for this GEP are
11177 // constants, we can promote this to a constexpr instead of an instruction.
11178
11179 // Scan for nonconstants...
11180 SmallVector<Constant*, 8> Indices;
11181 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11182 for (; I != E && isa<Constant>(*I); ++I)
11183 Indices.push_back(cast<Constant>(*I));
11184
11185 if (I == E) { // If they are all constants...
Owen Anderson02b48c32009-07-29 18:55:55 +000011186 Constant *CE = ConstantExpr::getGetElementPtr(GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011187 &Indices[0],Indices.size());
11188
11189 // Replace all uses of the GEP with the new constexpr...
11190 return ReplaceInstUsesWith(GEP, CE);
11191 }
11192 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11193 if (!isa<PointerType>(X->getType())) {
11194 // Not interesting. Source pointer must be a cast from pointer.
11195 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011196 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11197 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011198 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011199 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11200 // into : GEP i8* X, ...
11201 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011202 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011203 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11204 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011205 if (const ArrayType *CATy =
11206 dyn_cast<ArrayType>(CPTy->getElementType())) {
11207 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11208 if (CATy->getElementType() == XTy->getElementType()) {
11209 // -> GEP i8* X, ...
11210 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011211 GetElementPtrInst *NewGEP =
11212 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11213 GEP.getName());
11214 if (cast<GEPOperator>(&GEP)->isInBounds())
11215 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11216 return NewGEP;
Duncan Sandscf866e62009-03-02 09:18:21 +000011217 } else if (const ArrayType *XATy =
11218 dyn_cast<ArrayType>(XTy->getElementType())) {
11219 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011220 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011221 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011222 // At this point, we know that the cast source type is a pointer
11223 // to an array of the same type as the destination pointer
11224 // array. Because the array type is never stepped over (there
11225 // is a leading zero) we can fold the cast into this GEP.
11226 GEP.setOperand(0, X);
11227 return &GEP;
11228 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011229 }
11230 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011231 } else if (GEP.getNumOperands() == 2) {
11232 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011233 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11234 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011235 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11236 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011237 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011238 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11239 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011240 Value *Idx[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011241 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011242 Idx[1] = GEP.getOperand(1);
Dan Gohman17f46f72009-07-28 01:40:03 +000011243 GetElementPtrInst *NewGEP =
11244 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11245 if (cast<GEPOperator>(&GEP)->isInBounds())
11246 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11247 Value *V = InsertNewInstBefore(NewGEP, GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011248 // V and GEP are both pointer types --> BitCast
11249 return new BitCastInst(V, GEP.getType());
11250 }
11251
11252 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011253 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011254 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011255 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011256
Dan Gohmana80e2712009-07-21 23:21:54 +000011257 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011258 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011259 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011260
11261 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11262 // allow either a mul, shift, or constant here.
11263 Value *NewIdx = 0;
11264 ConstantInt *Scale = 0;
11265 if (ArrayEltSize == 1) {
11266 NewIdx = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011267 Scale =
Owen Andersoneacb44d2009-07-24 23:12:02 +000011268 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011269 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011270 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011271 Scale = CI;
11272 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11273 if (Inst->getOpcode() == Instruction::Shl &&
11274 isa<ConstantInt>(Inst->getOperand(1))) {
11275 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11276 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011277 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011278 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011279 NewIdx = Inst->getOperand(0);
11280 } else if (Inst->getOpcode() == Instruction::Mul &&
11281 isa<ConstantInt>(Inst->getOperand(1))) {
11282 Scale = cast<ConstantInt>(Inst->getOperand(1));
11283 NewIdx = Inst->getOperand(0);
11284 }
11285 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011286
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011287 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011288 // out, perform the transformation. Note, we don't know whether Scale is
11289 // signed or not. We'll use unsigned version of division/modulo
11290 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011291 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011292 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011293 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011294 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011295 if (Scale->getZExtValue() != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011296 Constant *C =
Owen Anderson02b48c32009-07-29 18:55:55 +000011297 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011298 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011299 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011300 NewIdx = InsertNewInstBefore(Sc, GEP);
11301 }
11302
11303 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011304 Value *Idx[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011305 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011306 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011307 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011308 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohman17f46f72009-07-28 01:40:03 +000011309 if (cast<GEPOperator>(&GEP)->isInBounds())
11310 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011311 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11312 // The NewGEP must be pointer typed, so must the old one -> BitCast
11313 return new BitCastInst(NewGEP, GEP.getType());
11314 }
11315 }
11316 }
11317 }
Chris Lattner111ea772009-01-09 04:53:57 +000011318
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011319 /// See if we can simplify:
11320 /// X = bitcast A to B*
11321 /// Y = gep X, <...constant indices...>
11322 /// into a gep of the original struct. This is important for SROA and alias
11323 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011324 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011325 if (TD &&
11326 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011327 // Determine how much the GEP moves the pointer. We are guaranteed to get
11328 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011329 ConstantInt *OffsetV =
11330 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011331 int64_t Offset = OffsetV->getSExtValue();
11332
11333 // If this GEP instruction doesn't move the pointer, just replace the GEP
11334 // with a bitcast of the real input to the dest type.
11335 if (Offset == 0) {
11336 // If the bitcast is of an allocation, and the allocation will be
11337 // converted to match the type of the cast, don't touch this.
11338 if (isa<AllocationInst>(BCI->getOperand(0))) {
11339 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11340 if (Instruction *I = visitBitCast(*BCI)) {
11341 if (I != BCI) {
11342 I->takeName(BCI);
11343 BCI->getParent()->getInstList().insert(BCI, I);
11344 ReplaceInstUsesWith(*BCI, I);
11345 }
11346 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011347 }
Chris Lattner111ea772009-01-09 04:53:57 +000011348 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011349 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011350 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011351
11352 // Otherwise, if the offset is non-zero, we need to find out if there is a
11353 // field at Offset in 'A's type. If so, we can pull the cast through the
11354 // GEP.
11355 SmallVector<Value*, 8> NewIndices;
11356 const Type *InTy =
11357 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011358 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011359 Instruction *NGEP =
11360 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11361 NewIndices.end());
11362 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohman17f46f72009-07-28 01:40:03 +000011363 if (cast<GEPOperator>(&GEP)->isInBounds())
11364 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011365 InsertNewInstBefore(NGEP, GEP);
11366 NGEP->takeName(&GEP);
11367 return new BitCastInst(NGEP, GEP.getType());
11368 }
Chris Lattner111ea772009-01-09 04:53:57 +000011369 }
11370 }
11371
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011372 return 0;
11373}
11374
11375Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11376 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011377 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011378 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11379 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011380 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011381 AllocationInst *New = 0;
11382
11383 // Create and insert the replacement instruction...
11384 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +000011385 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011386 else {
11387 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson140166d2009-07-15 23:53:25 +000011388 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011389 }
11390
11391 InsertNewInstBefore(New, AI);
11392
11393 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011394 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011395 //
11396 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011397 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011398
11399 // Now that I is pointing to the first non-allocation-inst in the block,
11400 // insert our getelementptr instruction...
11401 //
Owen Andersonaac28372009-07-31 20:28:14 +000011402 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011403 Value *Idx[2];
11404 Idx[0] = NullIdx;
11405 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011406 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11407 New->getName()+".sub", It);
Dan Gohman17f46f72009-07-28 01:40:03 +000011408 cast<GEPOperator>(V)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011409
11410 // Now make everything use the getelementptr instead of the original
11411 // allocation.
11412 return ReplaceInstUsesWith(AI, V);
11413 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011414 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011415 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011416 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011417
Dan Gohmana80e2712009-07-21 23:21:54 +000011418 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011419 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011420 // Note that we only do this for alloca's, because malloc should allocate
11421 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011422 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011423 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011424
11425 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11426 if (AI.getAlignment() == 0)
11427 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11428 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011429
11430 return 0;
11431}
11432
11433Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11434 Value *Op = FI.getOperand(0);
11435
11436 // free undef -> unreachable.
11437 if (isa<UndefValue>(Op)) {
11438 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011439 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000011440 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011441 return EraseInstFromFunction(FI);
11442 }
11443
11444 // If we have 'free null' delete the instruction. This can happen in stl code
11445 // when lots of inlining happens.
11446 if (isa<ConstantPointerNull>(Op))
11447 return EraseInstFromFunction(FI);
11448
11449 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11450 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11451 FI.setOperand(0, CI->getOperand(0));
11452 return &FI;
11453 }
11454
11455 // Change free (gep X, 0,0,0,0) into free(X)
11456 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11457 if (GEPI->hasAllZeroIndices()) {
11458 AddToWorkList(GEPI);
11459 FI.setOperand(0, GEPI->getOperand(0));
11460 return &FI;
11461 }
11462 }
11463
11464 // Change free(malloc) into nothing, if the malloc has a single use.
11465 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11466 if (MI->hasOneUse()) {
11467 EraseInstFromFunction(FI);
11468 return EraseInstFromFunction(*MI);
11469 }
11470
11471 return 0;
11472}
11473
11474
11475/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011476static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011477 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011478 User *CI = cast<User>(LI.getOperand(0));
11479 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011480 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011481
Nick Lewycky291c5942009-05-08 06:47:37 +000011482 if (TD) {
11483 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11484 // Instead of loading constant c string, use corresponding integer value
11485 // directly if string length is small enough.
11486 std::string Str;
11487 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11488 unsigned len = Str.length();
11489 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11490 unsigned numBits = Ty->getPrimitiveSizeInBits();
11491 // Replace LI with immediate integer store.
11492 if ((numBits >> 3) == len + 1) {
11493 APInt StrVal(numBits, 0);
11494 APInt SingleChar(numBits, 0);
11495 if (TD->isLittleEndian()) {
11496 for (signed i = len-1; i >= 0; i--) {
11497 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11498 StrVal = (StrVal << 8) | SingleChar;
11499 }
11500 } else {
11501 for (unsigned i = 0; i < len; i++) {
11502 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11503 StrVal = (StrVal << 8) | SingleChar;
11504 }
11505 // Append NULL at the end.
11506 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011507 StrVal = (StrVal << 8) | SingleChar;
11508 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011509 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011510 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011511 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011512 }
11513 }
11514 }
11515
Mon P Wangbd05ed82009-02-07 22:19:29 +000011516 const PointerType *DestTy = cast<PointerType>(CI->getType());
11517 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011518 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011519
11520 // If the address spaces don't match, don't eliminate the cast.
11521 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11522 return 0;
11523
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011524 const Type *SrcPTy = SrcTy->getElementType();
11525
11526 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11527 isa<VectorType>(DestPTy)) {
11528 // If the source is an array, the code below will not succeed. Check to
11529 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11530 // constants.
11531 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11532 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11533 if (ASrcTy->getNumElements() != 0) {
11534 Value *Idxs[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011535 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
Owen Anderson02b48c32009-07-29 18:55:55 +000011536 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011537 SrcTy = cast<PointerType>(CastOp->getType());
11538 SrcPTy = SrcTy->getElementType();
11539 }
11540
Dan Gohmana80e2712009-07-21 23:21:54 +000011541 if (IC.getTargetData() &&
11542 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011543 isa<VectorType>(SrcPTy)) &&
11544 // Do not allow turning this into a load of an integer, which is then
11545 // casted to a pointer, this pessimizes pointer analysis a lot.
11546 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011547 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11548 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011549
11550 // Okay, we are casting from one integer or pointer type to another of
11551 // the same size. Instead of casting the pointer before the load, cast
11552 // the result of the loaded value.
11553 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11554 CI->getName(),
11555 LI.isVolatile()),LI);
11556 // Now cast the result of the load.
11557 return new BitCastInst(NewLoad, LI.getType());
11558 }
11559 }
11560 }
11561 return 0;
11562}
11563
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011564Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11565 Value *Op = LI.getOperand(0);
11566
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011567 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011568 if (TD) {
11569 unsigned KnownAlign =
11570 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11571 if (KnownAlign >
11572 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11573 LI.getAlignment()))
11574 LI.setAlignment(KnownAlign);
11575 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011576
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011577 // load (cast X) --> cast (load X) iff safe
11578 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011579 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011580 return Res;
11581
11582 // None of the following transforms are legal for volatile loads.
11583 if (LI.isVolatile()) return 0;
11584
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011585 // Do really simple store-to-load forwarding and load CSE, to catch cases
11586 // where there are several consequtive memory accesses to the same location,
11587 // separated by a few arithmetic operations.
11588 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011589 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11590 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011591
Christopher Lamb2c175392007-12-29 07:56:53 +000011592 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11593 const Value *GEPI0 = GEPI->getOperand(0);
11594 // TODO: Consider a target hook for valid address spaces for this xform.
11595 if (isa<ConstantPointerNull>(GEPI0) &&
11596 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011597 // Insert a new store to null instruction before the load to indicate
11598 // that this code is not reachable. We do this instead of inserting
11599 // an unreachable instruction directly because we cannot modify the
11600 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011601 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011602 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011603 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011604 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011605 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011606
11607 if (Constant *C = dyn_cast<Constant>(Op)) {
11608 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011609 // TODO: Consider a target hook for valid address spaces for this xform.
11610 if (isa<UndefValue>(C) || (C->isNullValue() &&
11611 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011612 // Insert a new store to null instruction before the load to indicate that
11613 // this code is not reachable. We do this instead of inserting an
11614 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011615 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011616 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011617 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011618 }
11619
11620 // Instcombine load (constant global) into the value loaded.
11621 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011622 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011623 return ReplaceInstUsesWith(LI, GV->getInitializer());
11624
11625 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011626 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011627 if (CE->getOpcode() == Instruction::GetElementPtr) {
11628 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011629 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011630 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011631 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Anderson175b6542009-07-22 00:24:57 +000011632 *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011633 return ReplaceInstUsesWith(LI, V);
11634 if (CE->getOperand(0)->isNullValue()) {
11635 // Insert a new store to null instruction before the load to indicate
11636 // that this code is not reachable. We do this instead of inserting
11637 // an unreachable instruction directly because we cannot modify the
11638 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011639 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011640 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011641 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011642 }
11643
11644 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011645 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011646 return Res;
11647 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011648 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011649 }
Chris Lattner0270a112007-08-11 18:48:48 +000011650
11651 // If this load comes from anywhere in a constant global, and if the global
11652 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011653 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011654 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011655 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011656 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011657 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011658 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011659 }
11660 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011661
11662 if (Op->hasOneUse()) {
11663 // Change select and PHI nodes to select values instead of addresses: this
11664 // helps alias analysis out a lot, allows many others simplifications, and
11665 // exposes redundancy in the code.
11666 //
11667 // Note that we cannot do the transformation unless we know that the
11668 // introduced loads cannot trap! Something like this is valid as long as
11669 // the condition is always false: load (select bool %C, int* null, int* %G),
11670 // but it would not be valid if we transformed it to load from null
11671 // unconditionally.
11672 //
11673 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11674 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11675 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11676 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11677 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11678 SI->getOperand(1)->getName()+".val"), LI);
11679 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11680 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011681 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011682 }
11683
11684 // load (select (cond, null, P)) -> load P
11685 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11686 if (C->isNullValue()) {
11687 LI.setOperand(0, SI->getOperand(2));
11688 return &LI;
11689 }
11690
11691 // load (select (cond, P, null)) -> load P
11692 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11693 if (C->isNullValue()) {
11694 LI.setOperand(0, SI->getOperand(1));
11695 return &LI;
11696 }
11697 }
11698 }
11699 return 0;
11700}
11701
11702/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011703/// when possible. This makes it generally easy to do alias analysis and/or
11704/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011705static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11706 User *CI = cast<User>(SI.getOperand(1));
11707 Value *CastOp = CI->getOperand(0);
11708
11709 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011710 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11711 if (SrcTy == 0) return 0;
11712
11713 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011714
Chris Lattnera032c0e2009-01-16 20:08:59 +000011715 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11716 return 0;
11717
Chris Lattner54dddc72009-01-24 01:00:13 +000011718 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11719 /// to its first element. This allows us to handle things like:
11720 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11721 /// on 32-bit hosts.
11722 SmallVector<Value*, 4> NewGEPIndices;
11723
Chris Lattnera032c0e2009-01-16 20:08:59 +000011724 // If the source is an array, the code below will not succeed. Check to
11725 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11726 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011727 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11728 // Index through pointer.
Owen Andersonaac28372009-07-31 20:28:14 +000011729 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
Chris Lattner54dddc72009-01-24 01:00:13 +000011730 NewGEPIndices.push_back(Zero);
11731
11732 while (1) {
11733 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011734 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011735 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011736 NewGEPIndices.push_back(Zero);
11737 SrcPTy = STy->getElementType(0);
11738 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11739 NewGEPIndices.push_back(Zero);
11740 SrcPTy = ATy->getElementType();
11741 } else {
11742 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011743 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011744 }
11745
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011746 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011747 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011748
11749 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11750 return 0;
11751
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011752 // If the pointers point into different address spaces or if they point to
11753 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011754 if (!IC.getTargetData() ||
11755 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011756 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011757 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11758 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011759 return 0;
11760
11761 // Okay, we are casting from one integer or pointer type to another of
11762 // the same size. Instead of casting the pointer before
11763 // the store, cast the value to be stored.
11764 Value *NewCast;
11765 Value *SIOp0 = SI.getOperand(0);
11766 Instruction::CastOps opcode = Instruction::BitCast;
11767 const Type* CastSrcTy = SIOp0->getType();
11768 const Type* CastDstTy = SrcPTy;
11769 if (isa<PointerType>(CastDstTy)) {
11770 if (CastSrcTy->isInteger())
11771 opcode = Instruction::IntToPtr;
11772 } else if (isa<IntegerType>(CastDstTy)) {
11773 if (isa<PointerType>(SIOp0->getType()))
11774 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011775 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011776
11777 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11778 // emit a GEP to index into its first field.
11779 if (!NewGEPIndices.empty()) {
11780 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Anderson02b48c32009-07-29 18:55:55 +000011781 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner54dddc72009-01-24 01:00:13 +000011782 NewGEPIndices.size());
11783 else
11784 CastOp = IC.InsertNewInstBefore(
11785 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11786 NewGEPIndices.end()), SI);
Dan Gohman17f46f72009-07-28 01:40:03 +000011787 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner54dddc72009-01-24 01:00:13 +000011788 }
11789
Chris Lattnera032c0e2009-01-16 20:08:59 +000011790 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Anderson02b48c32009-07-29 18:55:55 +000011791 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnera032c0e2009-01-16 20:08:59 +000011792 else
11793 NewCast = IC.InsertNewInstBefore(
11794 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11795 SI);
11796 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011797}
11798
Chris Lattner6fd8c802008-11-27 08:56:30 +000011799/// equivalentAddressValues - Test if A and B will obviously have the same
11800/// value. This includes recognizing that %t0 and %t1 will have the same
11801/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011802/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011803/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011804/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011805/// %t2 = load i32* %t1
11806///
11807static bool equivalentAddressValues(Value *A, Value *B) {
11808 // Test if the values are trivially equivalent.
11809 if (A == B) return true;
11810
11811 // Test if the values come form identical arithmetic instructions.
11812 if (isa<BinaryOperator>(A) ||
11813 isa<CastInst>(A) ||
11814 isa<PHINode>(A) ||
11815 isa<GetElementPtrInst>(A))
11816 if (Instruction *BI = dyn_cast<Instruction>(B))
11817 if (cast<Instruction>(A)->isIdenticalTo(BI))
11818 return true;
11819
11820 // Otherwise they may not be equivalent.
11821 return false;
11822}
11823
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011824// If this instruction has two uses, one of which is a llvm.dbg.declare,
11825// return the llvm.dbg.declare.
11826DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11827 if (!V->hasNUses(2))
11828 return 0;
11829 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11830 UI != E; ++UI) {
11831 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11832 return DI;
11833 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11834 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11835 return DI;
11836 }
11837 }
11838 return 0;
11839}
11840
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011841Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11842 Value *Val = SI.getOperand(0);
11843 Value *Ptr = SI.getOperand(1);
11844
11845 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11846 EraseInstFromFunction(SI);
11847 ++NumCombined;
11848 return 0;
11849 }
11850
11851 // If the RHS is an alloca with a single use, zapify the store, making the
11852 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011853 // If the RHS is an alloca with a two uses, the other one being a
11854 // llvm.dbg.declare, zapify the store and the declare, making the
11855 // alloca dead. We must do this to prevent declare's from affecting
11856 // codegen.
11857 if (!SI.isVolatile()) {
11858 if (Ptr->hasOneUse()) {
11859 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011860 EraseInstFromFunction(SI);
11861 ++NumCombined;
11862 return 0;
11863 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011864 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11865 if (isa<AllocaInst>(GEP->getOperand(0))) {
11866 if (GEP->getOperand(0)->hasOneUse()) {
11867 EraseInstFromFunction(SI);
11868 ++NumCombined;
11869 return 0;
11870 }
11871 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11872 EraseInstFromFunction(*DI);
11873 EraseInstFromFunction(SI);
11874 ++NumCombined;
11875 return 0;
11876 }
11877 }
11878 }
11879 }
11880 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11881 EraseInstFromFunction(*DI);
11882 EraseInstFromFunction(SI);
11883 ++NumCombined;
11884 return 0;
11885 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011886 }
11887
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011888 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011889 if (TD) {
11890 unsigned KnownAlign =
11891 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11892 if (KnownAlign >
11893 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11894 SI.getAlignment()))
11895 SI.setAlignment(KnownAlign);
11896 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011897
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011898 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011899 // stores to the same location, separated by a few arithmetic operations. This
11900 // situation often occurs with bitfield accesses.
11901 BasicBlock::iterator BBI = &SI;
11902 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11903 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011904 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011905 // Don't count debug info directives, lest they affect codegen,
11906 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11907 // It is necessary for correctness to skip those that feed into a
11908 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011909 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011910 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011911 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011912 continue;
11913 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011914
11915 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11916 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011917 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11918 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011919 ++NumDeadStore;
11920 ++BBI;
11921 EraseInstFromFunction(*PrevSI);
11922 continue;
11923 }
11924 break;
11925 }
11926
11927 // If this is a load, we have to stop. However, if the loaded value is from
11928 // the pointer we're loading and is producing the pointer we're storing,
11929 // then *this* store is dead (X = load P; store X -> P).
11930 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011931 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11932 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011933 EraseInstFromFunction(SI);
11934 ++NumCombined;
11935 return 0;
11936 }
11937 // Otherwise, this is a load from some other location. Stores before it
11938 // may not be dead.
11939 break;
11940 }
11941
11942 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011943 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011944 break;
11945 }
11946
11947
11948 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11949
11950 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011951 if (isa<ConstantPointerNull>(Ptr) &&
11952 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011953 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011954 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011955 if (Instruction *U = dyn_cast<Instruction>(Val))
11956 AddToWorkList(U); // Dropped a use.
11957 ++NumCombined;
11958 }
11959 return 0; // Do not modify these!
11960 }
11961
11962 // store undef, Ptr -> noop
11963 if (isa<UndefValue>(Val)) {
11964 EraseInstFromFunction(SI);
11965 ++NumCombined;
11966 return 0;
11967 }
11968
11969 // If the pointer destination is a cast, see if we can fold the cast into the
11970 // source instead.
11971 if (isa<CastInst>(Ptr))
11972 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11973 return Res;
11974 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11975 if (CE->isCast())
11976 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11977 return Res;
11978
11979
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011980 // If this store is the last instruction in the basic block (possibly
11981 // excepting debug info instructions and the pointer bitcasts that feed
11982 // into them), and if the block ends with an unconditional branch, try
11983 // to move it to the successor block.
11984 BBI = &SI;
11985 do {
11986 ++BBI;
11987 } while (isa<DbgInfoIntrinsic>(BBI) ||
11988 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011989 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11990 if (BI->isUnconditional())
11991 if (SimplifyStoreAtEndOfBlock(SI))
11992 return 0; // xform done!
11993
11994 return 0;
11995}
11996
11997/// SimplifyStoreAtEndOfBlock - Turn things like:
11998/// if () { *P = v1; } else { *P = v2 }
11999/// into a phi node with a store in the successor.
12000///
12001/// Simplify things like:
12002/// *P = v1; if () { *P = v2; }
12003/// into a phi node with a store in the successor.
12004///
12005bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12006 BasicBlock *StoreBB = SI.getParent();
12007
12008 // Check to see if the successor block has exactly two incoming edges. If
12009 // so, see if the other predecessor contains a store to the same location.
12010 // if so, insert a PHI node (if needed) and move the stores down.
12011 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12012
12013 // Determine whether Dest has exactly two predecessors and, if so, compute
12014 // the other predecessor.
12015 pred_iterator PI = pred_begin(DestBB);
12016 BasicBlock *OtherBB = 0;
12017 if (*PI != StoreBB)
12018 OtherBB = *PI;
12019 ++PI;
12020 if (PI == pred_end(DestBB))
12021 return false;
12022
12023 if (*PI != StoreBB) {
12024 if (OtherBB)
12025 return false;
12026 OtherBB = *PI;
12027 }
12028 if (++PI != pred_end(DestBB))
12029 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012030
12031 // Bail out if all the relevant blocks aren't distinct (this can happen,
12032 // for example, if SI is in an infinite loop)
12033 if (StoreBB == DestBB || OtherBB == DestBB)
12034 return false;
12035
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012036 // Verify that the other block ends in a branch and is not otherwise empty.
12037 BasicBlock::iterator BBI = OtherBB->getTerminator();
12038 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12039 if (!OtherBr || BBI == OtherBB->begin())
12040 return false;
12041
12042 // If the other block ends in an unconditional branch, check for the 'if then
12043 // else' case. there is an instruction before the branch.
12044 StoreInst *OtherStore = 0;
12045 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012046 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012047 // Skip over debugging info.
12048 while (isa<DbgInfoIntrinsic>(BBI) ||
12049 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12050 if (BBI==OtherBB->begin())
12051 return false;
12052 --BBI;
12053 }
12054 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012055 OtherStore = dyn_cast<StoreInst>(BBI);
12056 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12057 return false;
12058 } else {
12059 // Otherwise, the other block ended with a conditional branch. If one of the
12060 // destinations is StoreBB, then we have the if/then case.
12061 if (OtherBr->getSuccessor(0) != StoreBB &&
12062 OtherBr->getSuccessor(1) != StoreBB)
12063 return false;
12064
12065 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12066 // if/then triangle. See if there is a store to the same ptr as SI that
12067 // lives in OtherBB.
12068 for (;; --BBI) {
12069 // Check to see if we find the matching store.
12070 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12071 if (OtherStore->getOperand(1) != SI.getOperand(1))
12072 return false;
12073 break;
12074 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012075 // If we find something that may be using or overwriting the stored
12076 // value, or if we run out of instructions, we can't do the xform.
12077 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012078 BBI == OtherBB->begin())
12079 return false;
12080 }
12081
12082 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012083 // make sure nothing reads or overwrites the stored value in
12084 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012085 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12086 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012087 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012088 return false;
12089 }
12090 }
12091
12092 // Insert a PHI node now if we need it.
12093 Value *MergedVal = OtherStore->getOperand(0);
12094 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012095 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012096 PN->reserveOperandSpace(2);
12097 PN->addIncoming(SI.getOperand(0), SI.getParent());
12098 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12099 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12100 }
12101
12102 // Advance to a place where it is safe to insert the new store and
12103 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012104 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012105 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12106 OtherStore->isVolatile()), *BBI);
12107
12108 // Nuke the old stores.
12109 EraseInstFromFunction(SI);
12110 EraseInstFromFunction(*OtherStore);
12111 ++NumCombined;
12112 return true;
12113}
12114
12115
12116Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12117 // Change br (not X), label True, label False to: br X, label False, True
12118 Value *X = 0;
12119 BasicBlock *TrueDest;
12120 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012121 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012122 !isa<Constant>(X)) {
12123 // Swap Destinations and condition...
12124 BI.setCondition(X);
12125 BI.setSuccessor(0, FalseDest);
12126 BI.setSuccessor(1, TrueDest);
12127 return &BI;
12128 }
12129
12130 // Cannonicalize fcmp_one -> fcmp_oeq
12131 FCmpInst::Predicate FPred; Value *Y;
12132 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Dan Gohmancdff2122009-08-12 16:23:25 +000012133 TrueDest, FalseDest)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012134 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12135 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12136 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12137 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012138 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012139 NewSCC->takeName(I);
12140 // Swap Destinations and condition...
12141 BI.setCondition(NewSCC);
12142 BI.setSuccessor(0, FalseDest);
12143 BI.setSuccessor(1, TrueDest);
12144 RemoveFromWorkList(I);
12145 I->eraseFromParent();
12146 AddToWorkList(NewSCC);
12147 return &BI;
12148 }
12149
12150 // Cannonicalize icmp_ne -> icmp_eq
12151 ICmpInst::Predicate IPred;
12152 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Dan Gohmancdff2122009-08-12 16:23:25 +000012153 TrueDest, FalseDest)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012154 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12155 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12156 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12157 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12158 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012159 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012160 NewSCC->takeName(I);
12161 // Swap Destinations and condition...
12162 BI.setCondition(NewSCC);
12163 BI.setSuccessor(0, FalseDest);
12164 BI.setSuccessor(1, TrueDest);
12165 RemoveFromWorkList(I);
12166 I->eraseFromParent();;
12167 AddToWorkList(NewSCC);
12168 return &BI;
12169 }
12170
12171 return 0;
12172}
12173
12174Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12175 Value *Cond = SI.getCondition();
12176 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12177 if (I->getOpcode() == Instruction::Add)
12178 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12179 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12180 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012181 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012182 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012183 AddRHS));
12184 SI.setOperand(0, I->getOperand(0));
12185 AddToWorkList(I);
12186 return &SI;
12187 }
12188 }
12189 return 0;
12190}
12191
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012192Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012193 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012194
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012195 if (!EV.hasIndices())
12196 return ReplaceInstUsesWith(EV, Agg);
12197
12198 if (Constant *C = dyn_cast<Constant>(Agg)) {
12199 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012200 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012201
12202 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012203 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012204
12205 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12206 // Extract the element indexed by the first index out of the constant
12207 Value *V = C->getOperand(*EV.idx_begin());
12208 if (EV.getNumIndices() > 1)
12209 // Extract the remaining indices out of the constant indexed by the
12210 // first index
12211 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12212 else
12213 return ReplaceInstUsesWith(EV, V);
12214 }
12215 return 0; // Can't handle other constants
12216 }
12217 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12218 // We're extracting from an insertvalue instruction, compare the indices
12219 const unsigned *exti, *exte, *insi, *inse;
12220 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12221 exte = EV.idx_end(), inse = IV->idx_end();
12222 exti != exte && insi != inse;
12223 ++exti, ++insi) {
12224 if (*insi != *exti)
12225 // The insert and extract both reference distinctly different elements.
12226 // This means the extract is not influenced by the insert, and we can
12227 // replace the aggregate operand of the extract with the aggregate
12228 // operand of the insert. i.e., replace
12229 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12230 // %E = extractvalue { i32, { i32 } } %I, 0
12231 // with
12232 // %E = extractvalue { i32, { i32 } } %A, 0
12233 return ExtractValueInst::Create(IV->getAggregateOperand(),
12234 EV.idx_begin(), EV.idx_end());
12235 }
12236 if (exti == exte && insi == inse)
12237 // Both iterators are at the end: Index lists are identical. Replace
12238 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12239 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12240 // with "i32 42"
12241 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12242 if (exti == exte) {
12243 // The extract list is a prefix of the insert list. i.e. replace
12244 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12245 // %E = extractvalue { i32, { i32 } } %I, 1
12246 // with
12247 // %X = extractvalue { i32, { i32 } } %A, 1
12248 // %E = insertvalue { i32 } %X, i32 42, 0
12249 // by switching the order of the insert and extract (though the
12250 // insertvalue should be left in, since it may have other uses).
12251 Value *NewEV = InsertNewInstBefore(
12252 ExtractValueInst::Create(IV->getAggregateOperand(),
12253 EV.idx_begin(), EV.idx_end()),
12254 EV);
12255 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12256 insi, inse);
12257 }
12258 if (insi == inse)
12259 // The insert list is a prefix of the extract list
12260 // We can simply remove the common indices from the extract and make it
12261 // operate on the inserted value instead of the insertvalue result.
12262 // i.e., replace
12263 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12264 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12265 // with
12266 // %E extractvalue { i32 } { i32 42 }, 0
12267 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12268 exti, exte);
12269 }
12270 // Can't simplify extracts from other values. Note that nested extracts are
12271 // already simplified implicitely by the above (extract ( extract (insert) )
12272 // will be translated into extract ( insert ( extract ) ) first and then just
12273 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012274 return 0;
12275}
12276
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012277/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12278/// is to leave as a vector operation.
12279static bool CheapToScalarize(Value *V, bool isConstant) {
12280 if (isa<ConstantAggregateZero>(V))
12281 return true;
12282 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12283 if (isConstant) return true;
12284 // If all elts are the same, we can extract.
12285 Constant *Op0 = C->getOperand(0);
12286 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12287 if (C->getOperand(i) != Op0)
12288 return false;
12289 return true;
12290 }
12291 Instruction *I = dyn_cast<Instruction>(V);
12292 if (!I) return false;
12293
12294 // Insert element gets simplified to the inserted element or is deleted if
12295 // this is constant idx extract element and its a constant idx insertelt.
12296 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12297 isa<ConstantInt>(I->getOperand(2)))
12298 return true;
12299 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12300 return true;
12301 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12302 if (BO->hasOneUse() &&
12303 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12304 CheapToScalarize(BO->getOperand(1), isConstant)))
12305 return true;
12306 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12307 if (CI->hasOneUse() &&
12308 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12309 CheapToScalarize(CI->getOperand(1), isConstant)))
12310 return true;
12311
12312 return false;
12313}
12314
12315/// Read and decode a shufflevector mask.
12316///
12317/// It turns undef elements into values that are larger than the number of
12318/// elements in the input.
12319static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12320 unsigned NElts = SVI->getType()->getNumElements();
12321 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12322 return std::vector<unsigned>(NElts, 0);
12323 if (isa<UndefValue>(SVI->getOperand(2)))
12324 return std::vector<unsigned>(NElts, 2*NElts);
12325
12326 std::vector<unsigned> Result;
12327 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012328 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12329 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012330 Result.push_back(NElts*2); // undef -> 8
12331 else
Gabor Greif17396002008-06-12 21:37:33 +000012332 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012333 return Result;
12334}
12335
12336/// FindScalarElement - Given a vector and an element number, see if the scalar
12337/// value is already around as a register, for example if it were inserted then
12338/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012339static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012340 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012341 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12342 const VectorType *PTy = cast<VectorType>(V->getType());
12343 unsigned Width = PTy->getNumElements();
12344 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012345 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012346
12347 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012348 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012349 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012350 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012351 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12352 return CP->getOperand(EltNo);
12353 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12354 // If this is an insert to a variable element, we don't know what it is.
12355 if (!isa<ConstantInt>(III->getOperand(2)))
12356 return 0;
12357 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12358
12359 // If this is an insert to the element we are looking for, return the
12360 // inserted value.
12361 if (EltNo == IIElt)
12362 return III->getOperand(1);
12363
12364 // Otherwise, the insertelement doesn't modify the value, recurse on its
12365 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012366 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012367 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012368 unsigned LHSWidth =
12369 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012370 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012371 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012372 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012373 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012374 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012375 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012376 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012377 }
12378
12379 // Otherwise, we don't know.
12380 return 0;
12381}
12382
12383Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012384 // If vector val is undef, replace extract with scalar undef.
12385 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012386 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012387
12388 // If vector val is constant 0, replace extract with scalar 0.
12389 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012390 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012391
12392 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012393 // If vector val is constant with all elements the same, replace EI with
12394 // that element. When the elements are not identical, we cannot replace yet
12395 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012396 Constant *op0 = C->getOperand(0);
12397 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12398 if (C->getOperand(i) != op0) {
12399 op0 = 0;
12400 break;
12401 }
12402 if (op0)
12403 return ReplaceInstUsesWith(EI, op0);
12404 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012405
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012406 // If extracting a specified index from the vector, see if we can recursively
12407 // find a previously computed scalar that was inserted into the vector.
12408 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12409 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedmanf34209b2009-07-18 19:04:16 +000012410 unsigned VectorWidth =
12411 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012412
12413 // If this is extracting an invalid index, turn this into undef, to avoid
12414 // crashing the code below.
12415 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012416 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012417
12418 // This instruction only demands the single element from the input vector.
12419 // If the input vector has a single use, simplify it based on this use
12420 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012421 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012422 APInt UndefElts(VectorWidth, 0);
12423 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012424 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012425 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012426 EI.setOperand(0, V);
12427 return &EI;
12428 }
12429 }
12430
Owen Anderson24be4c12009-07-03 00:17:18 +000012431 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012432 return ReplaceInstUsesWith(EI, Elt);
12433
12434 // If the this extractelement is directly using a bitcast from a vector of
12435 // the same number of elements, see if we can find the source element from
12436 // it. In this case, we will end up needing to bitcast the scalars.
12437 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12438 if (const VectorType *VT =
12439 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12440 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012441 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12442 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012443 return new BitCastInst(Elt, EI.getType());
12444 }
12445 }
12446
12447 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12448 if (I->hasOneUse()) {
12449 // Push extractelement into predecessor operation if legal and
12450 // profitable to do so
12451 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12452 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12453 if (CheapToScalarize(BO, isConstantElt)) {
12454 ExtractElementInst *newEI0 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012455 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012456 EI.getName()+".lhs");
12457 ExtractElementInst *newEI1 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012458 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012459 EI.getName()+".rhs");
12460 InsertNewInstBefore(newEI0, EI);
12461 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012462 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012463 }
12464 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012465 unsigned AS =
12466 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012467 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012468 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012469 GetElementPtrInst *GEP =
12470 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohman17f46f72009-07-28 01:40:03 +000012471 cast<GEPOperator>(GEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012472 InsertNewInstBefore(GEP, EI);
12473 return new LoadInst(GEP);
12474 }
12475 }
12476 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12477 // Extracting the inserted element?
12478 if (IE->getOperand(2) == EI.getOperand(1))
12479 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12480 // If the inserted and extracted elements are constants, they must not
12481 // be the same value, extract from the pre-inserted value instead.
12482 if (isa<Constant>(IE->getOperand(2)) &&
12483 isa<Constant>(EI.getOperand(1))) {
12484 AddUsesToWorkList(EI);
12485 EI.setOperand(0, IE->getOperand(0));
12486 return &EI;
12487 }
12488 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12489 // If this is extracting an element from a shufflevector, figure out where
12490 // it came from and extract from the appropriate input element instead.
12491 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12492 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12493 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012494 unsigned LHSWidth =
12495 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12496
12497 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012498 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012499 else if (SrcIdx < LHSWidth*2) {
12500 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012501 Src = SVI->getOperand(1);
12502 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012503 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012504 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012505 return ExtractElementInst::Create(Src,
Owen Andersoneacb44d2009-07-24 23:12:02 +000012506 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012507 }
12508 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012509 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012510 }
12511 return 0;
12512}
12513
12514/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12515/// elements from either LHS or RHS, return the shuffle mask and true.
12516/// Otherwise, return false.
12517static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012518 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012519 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012520 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12521 "Invalid CollectSingleShuffleElements");
12522 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12523
12524 if (isa<UndefValue>(V)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012525 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012526 return true;
12527 } else if (V == LHS) {
12528 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012529 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012530 return true;
12531 } else if (V == RHS) {
12532 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012533 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012534 return true;
12535 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12536 // If this is an insert of an extract from some other vector, include it.
12537 Value *VecOp = IEI->getOperand(0);
12538 Value *ScalarOp = IEI->getOperand(1);
12539 Value *IdxOp = IEI->getOperand(2);
12540
12541 if (!isa<ConstantInt>(IdxOp))
12542 return false;
12543 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12544
12545 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12546 // Okay, we can handle this if the vector we are insertinting into is
12547 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012548 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012549 // If so, update the mask to reflect the inserted undef.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012550 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012551 return true;
12552 }
12553 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12554 if (isa<ConstantInt>(EI->getOperand(1)) &&
12555 EI->getOperand(0)->getType() == V->getType()) {
12556 unsigned ExtractedIdx =
12557 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12558
12559 // This must be extracting from either LHS or RHS.
12560 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12561 // Okay, we can handle this if the vector we are insertinting into is
12562 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012563 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012564 // If so, update the mask to reflect the inserted value.
12565 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012566 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012567 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012568 } else {
12569 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012570 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012571 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012572
12573 }
12574 return true;
12575 }
12576 }
12577 }
12578 }
12579 }
12580 // TODO: Handle shufflevector here!
12581
12582 return false;
12583}
12584
12585/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12586/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12587/// that computes V and the LHS value of the shuffle.
12588static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012589 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012590 assert(isa<VectorType>(V->getType()) &&
12591 (RHS == 0 || V->getType() == RHS->getType()) &&
12592 "Invalid shuffle!");
12593 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12594
12595 if (isa<UndefValue>(V)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012596 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012597 return V;
12598 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012599 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012600 return V;
12601 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12602 // If this is an insert of an extract from some other vector, include it.
12603 Value *VecOp = IEI->getOperand(0);
12604 Value *ScalarOp = IEI->getOperand(1);
12605 Value *IdxOp = IEI->getOperand(2);
12606
12607 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12608 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12609 EI->getOperand(0)->getType() == V->getType()) {
12610 unsigned ExtractedIdx =
12611 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12612 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12613
12614 // Either the extracted from or inserted into vector must be RHSVec,
12615 // otherwise we'd end up with a shuffle of three inputs.
12616 if (EI->getOperand(0) == RHS || RHS == 0) {
12617 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012618 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012619 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012620 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012621 return V;
12622 }
12623
12624 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012625 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12626 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012627 // Everything but the extracted element is replaced with the RHS.
12628 for (unsigned i = 0; i != NumElts; ++i) {
12629 if (i != InsertedIdx)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012630 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012631 }
12632 return V;
12633 }
12634
12635 // If this insertelement is a chain that comes from exactly these two
12636 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012637 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12638 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012639 return EI->getOperand(0);
12640
12641 }
12642 }
12643 }
12644 // TODO: Handle shufflevector here!
12645
12646 // Otherwise, can't do anything fancy. Return an identity vector.
12647 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012648 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012649 return V;
12650}
12651
12652Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12653 Value *VecOp = IE.getOperand(0);
12654 Value *ScalarOp = IE.getOperand(1);
12655 Value *IdxOp = IE.getOperand(2);
12656
12657 // Inserting an undef or into an undefined place, remove this.
12658 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12659 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012660
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012661 // If the inserted element was extracted from some other vector, and if the
12662 // indexes are constant, try to turn this into a shufflevector operation.
12663 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12664 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12665 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012666 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012667 unsigned ExtractedIdx =
12668 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12669 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12670
12671 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12672 return ReplaceInstUsesWith(IE, VecOp);
12673
12674 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012675 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012676
12677 // If we are extracting a value from a vector, then inserting it right
12678 // back into the same place, just use the input vector.
12679 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12680 return ReplaceInstUsesWith(IE, VecOp);
12681
12682 // We could theoretically do this for ANY input. However, doing so could
12683 // turn chains of insertelement instructions into a chain of shufflevector
12684 // instructions, and right now we do not merge shufflevectors. As such,
12685 // only do this in a situation where it is clear that there is benefit.
12686 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12687 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12688 // the values of VecOp, except then one read from EIOp0.
12689 // Build a new shuffle mask.
12690 std::vector<Constant*> Mask;
12691 if (isa<UndefValue>(VecOp))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012692 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012693 else {
12694 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneacb44d2009-07-24 23:12:02 +000012695 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012696 NumVectorElts));
12697 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012698 Mask[InsertedIdx] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012699 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012700 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson2f422e02009-07-28 21:19:26 +000012701 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012702 }
12703
12704 // If this insertelement isn't used by some other insertelement, turn it
12705 // (and any insertelements it points to), into one big shuffle.
12706 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12707 std::vector<Constant*> Mask;
12708 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012709 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012710 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012711 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012712 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012713 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012714 }
12715 }
12716 }
12717
Eli Friedmanbefee262009-06-06 20:08:03 +000012718 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12719 APInt UndefElts(VWidth, 0);
12720 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12721 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12722 return &IE;
12723
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012724 return 0;
12725}
12726
12727
12728Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12729 Value *LHS = SVI.getOperand(0);
12730 Value *RHS = SVI.getOperand(1);
12731 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12732
12733 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012734
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012735 // Undefined shuffle mask -> undefined value.
12736 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012737 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012738
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012739 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012740
12741 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12742 return 0;
12743
Evan Cheng63295ab2009-02-03 10:05:09 +000012744 APInt UndefElts(VWidth, 0);
12745 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12746 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012747 LHS = SVI.getOperand(0);
12748 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012749 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012750 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012751
12752 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12753 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12754 if (LHS == RHS || isa<UndefValue>(LHS)) {
12755 if (isa<UndefValue>(LHS) && LHS == RHS) {
12756 // shuffle(undef,undef,mask) -> undef.
12757 return ReplaceInstUsesWith(SVI, LHS);
12758 }
12759
12760 // Remap any references to RHS to use LHS.
12761 std::vector<Constant*> Elts;
12762 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12763 if (Mask[i] >= 2*e)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012764 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012765 else {
12766 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012767 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012768 Mask[i] = 2*e; // Turn into undef.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012769 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012770 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012771 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneacb44d2009-07-24 23:12:02 +000012772 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012774 }
12775 }
12776 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012777 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012778 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012779 LHS = SVI.getOperand(0);
12780 RHS = SVI.getOperand(1);
12781 MadeChange = true;
12782 }
12783
12784 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12785 bool isLHSID = true, isRHSID = true;
12786
12787 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12788 if (Mask[i] >= e*2) continue; // Ignore undef values.
12789 // Is this an identity shuffle of the LHS value?
12790 isLHSID &= (Mask[i] == i);
12791
12792 // Is this an identity shuffle of the RHS value?
12793 isRHSID &= (Mask[i]-e == i);
12794 }
12795
12796 // Eliminate identity shuffles.
12797 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12798 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12799
12800 // If the LHS is a shufflevector itself, see if we can combine it with this
12801 // one without producing an unusual shuffle. Here we are really conservative:
12802 // we are absolutely afraid of producing a shuffle mask not in the input
12803 // program, because the code gen may not be smart enough to turn a merged
12804 // shuffle into two specific shuffles: it may produce worse code. As such,
12805 // we only merge two shuffles if the result is one of the two input shuffle
12806 // masks. In this case, merging the shuffles just removes one instruction,
12807 // which we know is safe. This is good for things like turning:
12808 // (splat(splat)) -> splat.
12809 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12810 if (isa<UndefValue>(RHS)) {
12811 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12812
12813 std::vector<unsigned> NewMask;
12814 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12815 if (Mask[i] >= 2*e)
12816 NewMask.push_back(2*e);
12817 else
12818 NewMask.push_back(LHSMask[Mask[i]]);
12819
12820 // If the result mask is equal to the src shuffle or this shuffle mask, do
12821 // the replacement.
12822 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012823 unsigned LHSInNElts =
12824 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012825 std::vector<Constant*> Elts;
12826 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012827 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012828 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012829 } else {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012830 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012831 }
12832 }
12833 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12834 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012835 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012836 }
12837 }
12838 }
12839
12840 return MadeChange ? &SVI : 0;
12841}
12842
12843
12844
12845
12846/// TryToSinkInstruction - Try to move the specified instruction from its
12847/// current block into the beginning of DestBlock, which can only happen if it's
12848/// safe to move the instruction past all of the instructions between it and the
12849/// end of its block.
12850static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12851 assert(I->hasOneUse() && "Invariants didn't hold!");
12852
12853 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012854 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012855 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012856
12857 // Do not sink alloca instructions out of the entry block.
12858 if (isa<AllocaInst>(I) && I->getParent() ==
12859 &DestBlock->getParent()->getEntryBlock())
12860 return false;
12861
12862 // We can only sink load instructions if there is nothing between the load and
12863 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012864 if (I->mayReadFromMemory()) {
12865 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012866 Scan != E; ++Scan)
12867 if (Scan->mayWriteToMemory())
12868 return false;
12869 }
12870
Dan Gohman514277c2008-05-23 21:05:58 +000012871 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012872
Dale Johannesen24339f12009-03-03 01:09:07 +000012873 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012874 I->moveBefore(InsertPos);
12875 ++NumSunkInst;
12876 return true;
12877}
12878
12879
12880/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12881/// all reachable code to the worklist.
12882///
12883/// This has a couple of tricks to make the code faster and more powerful. In
12884/// particular, we constant fold and DCE instructions as we go, to avoid adding
12885/// them to the worklist (this significantly speeds up instcombine on code where
12886/// many instructions are dead or constant). Additionally, if we find a branch
12887/// whose condition is a known constant, we only visit the reachable successors.
12888///
12889static void AddReachableCodeToWorklist(BasicBlock *BB,
12890 SmallPtrSet<BasicBlock*, 64> &Visited,
12891 InstCombiner &IC,
12892 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012893 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012894 Worklist.push_back(BB);
12895
12896 while (!Worklist.empty()) {
12897 BB = Worklist.back();
12898 Worklist.pop_back();
12899
12900 // We have now visited this block! If we've already been here, ignore it.
12901 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012902
12903 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012904 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12905 Instruction *Inst = BBI++;
12906
12907 // DCE instruction if trivially dead.
12908 if (isInstructionTriviallyDead(Inst)) {
12909 ++NumDeadInst;
Dan Gohman3fa885b2009-08-12 16:28:31 +000012910 DOUT << "IC: DCE: " << *Inst << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012911 Inst->eraseFromParent();
12912 continue;
12913 }
12914
12915 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012916 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Dan Gohman3fa885b2009-08-12 16:28:31 +000012917 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012918 Inst->replaceAllUsesWith(C);
12919 ++NumConstProp;
12920 Inst->eraseFromParent();
12921 continue;
12922 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012923
Devang Patel794140c2008-11-19 18:56:50 +000012924 // If there are two consecutive llvm.dbg.stoppoint calls then
12925 // it is likely that the optimizer deleted code in between these
12926 // two intrinsics.
12927 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12928 if (DBI_Next) {
12929 if (DBI_Prev
12930 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12931 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12932 IC.RemoveFromWorkList(DBI_Prev);
12933 DBI_Prev->eraseFromParent();
12934 }
12935 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012936 } else {
12937 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012938 }
12939
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012940 IC.AddToWorkList(Inst);
12941 }
12942
12943 // Recursively visit successors. If this is a branch or switch on a
12944 // constant, only visit the reachable successor.
12945 TerminatorInst *TI = BB->getTerminator();
12946 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12947 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12948 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012949 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012950 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012951 continue;
12952 }
12953 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12954 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12955 // See if this is an explicit destination.
12956 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12957 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012958 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012959 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012960 continue;
12961 }
12962
12963 // Otherwise it is the default destination.
12964 Worklist.push_back(SI->getSuccessor(0));
12965 continue;
12966 }
12967 }
12968
12969 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12970 Worklist.push_back(TI->getSuccessor(i));
12971 }
12972}
12973
12974bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12975 bool Changed = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012976 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012977
Daniel Dunbar005975c2009-07-25 00:23:56 +000012978 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12979 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012980
12981 {
12982 // Do a depth-first traversal of the function, populate the worklist with
12983 // the reachable instructions. Ignore blocks that are not reachable. Keep
12984 // track of which blocks we visit.
12985 SmallPtrSet<BasicBlock*, 64> Visited;
12986 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12987
12988 // Do a quick scan over the function. If we find any blocks that are
12989 // unreachable, remove any instructions inside of them. This prevents
12990 // the instcombine code from having to deal with some bad special cases.
12991 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12992 if (!Visited.count(BB)) {
12993 Instruction *Term = BB->getTerminator();
12994 while (Term != BB->begin()) { // Remove instrs bottom-up
12995 BasicBlock::iterator I = Term; --I;
12996
Dan Gohman3fa885b2009-08-12 16:28:31 +000012997 DOUT << "IC: DCE: " << *I << '\n';
Dale Johannesendf356c62009-03-10 21:19:49 +000012998 // A debug intrinsic shouldn't force another iteration if we weren't
12999 // going to do one without it.
13000 if (!isa<DbgInfoIntrinsic>(I)) {
13001 ++NumDeadInst;
13002 Changed = true;
13003 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013004 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000013005 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013006 I->eraseFromParent();
13007 }
13008 }
13009 }
13010
13011 while (!Worklist.empty()) {
13012 Instruction *I = RemoveOneFromWorkList();
13013 if (I == 0) continue; // skip null values.
13014
13015 // Check to see if we can DCE the instruction.
13016 if (isInstructionTriviallyDead(I)) {
13017 // Add operands to the worklist.
13018 if (I->getNumOperands() < 4)
13019 AddUsesToWorkList(*I);
13020 ++NumDeadInst;
13021
Dan Gohman3fa885b2009-08-12 16:28:31 +000013022 DOUT << "IC: DCE: " << *I << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013023
13024 I->eraseFromParent();
13025 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013026 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013027 continue;
13028 }
13029
13030 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000013031 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Dan Gohman3fa885b2009-08-12 16:28:31 +000013032 DOUT << "IC: ConstFold to: " << *C << " from: " << *I << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013033
13034 // Add operands to the worklist.
13035 AddUsesToWorkList(*I);
13036 ReplaceInstUsesWith(*I, C);
13037
13038 ++NumConstProp;
13039 I->eraseFromParent();
13040 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013041 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013042 continue;
13043 }
13044
Eli Friedman5c619182009-07-15 22:13:34 +000013045 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000013046 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000013047 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13048 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000013049 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13050 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000013051 if (NewC != CE) {
13052 i->set(NewC);
13053 Changed = true;
13054 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000013055 }
13056
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013057 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013058 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013059 BasicBlock *BB = I->getParent();
13060 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13061 if (UserParent != BB) {
13062 bool UserIsSuccessor = false;
13063 // See if the user is one of our successors.
13064 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13065 if (*SI == UserParent) {
13066 UserIsSuccessor = true;
13067 break;
13068 }
13069
13070 // If the user is one of our immediate successors, and if that successor
13071 // only has us as a predecessors (we'd have to split the critical edge
13072 // otherwise), we can keep going.
13073 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13074 next(pred_begin(UserParent)) == pred_end(UserParent))
13075 // Okay, the CFG is simple enough, try to sink this instruction.
13076 Changed |= TryToSinkInstruction(I, UserParent);
13077 }
13078 }
13079
13080 // Now that we have an instruction, try combining it to simplify it...
13081#ifndef NDEBUG
13082 std::string OrigI;
13083#endif
13084 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13085 if (Instruction *Result = visit(*I)) {
13086 ++NumCombined;
13087 // Should we replace the old instruction with a new one?
13088 if (Result != I) {
Dan Gohman3fa885b2009-08-12 16:28:31 +000013089 DOUT << "IC: Old = " << *I << '\n'
13090 << " New = " << *Result << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013091
13092 // Everything uses the new instruction now.
13093 I->replaceAllUsesWith(Result);
13094
13095 // Push the new instruction and any users onto the worklist.
13096 AddToWorkList(Result);
13097 AddUsersToWorkList(*Result);
13098
13099 // Move the name to the new instruction first.
13100 Result->takeName(I);
13101
13102 // Insert the new instruction into the basic block...
13103 BasicBlock *InstParent = I->getParent();
13104 BasicBlock::iterator InsertPos = I;
13105
13106 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13107 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13108 ++InsertPos;
13109
13110 InstParent->getInstList().insert(InsertPos, Result);
13111
13112 // Make sure that we reprocess all operands now that we reduced their
13113 // use counts.
13114 AddUsesToWorkList(*I);
13115
13116 // Instructions can end up on the worklist more than once. Make sure
13117 // we do not process an instruction that has been deleted.
13118 RemoveFromWorkList(I);
13119
13120 // Erase the old instruction.
13121 InstParent->getInstList().erase(I);
13122 } else {
13123#ifndef NDEBUG
Dan Gohman3fa885b2009-08-12 16:28:31 +000013124 DOUT << "IC: Mod = " << OrigI << '\n'
13125 << " New = " << *I << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013126#endif
13127
13128 // If the instruction was modified, it's possible that it is now dead.
13129 // if so, remove it.
13130 if (isInstructionTriviallyDead(I)) {
13131 // Make sure we process all operands now that we are reducing their
13132 // use counts.
13133 AddUsesToWorkList(*I);
13134
13135 // Instructions may end up in the worklist more than once. Erase all
13136 // occurrences of this instruction.
13137 RemoveFromWorkList(I);
13138 I->eraseFromParent();
13139 } else {
13140 AddToWorkList(I);
13141 AddUsersToWorkList(*I);
13142 }
13143 }
13144 Changed = true;
13145 }
13146 }
13147
13148 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013149
13150 // Do an explicit clear, this shrinks the map if needed.
13151 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013152 return Changed;
13153}
13154
13155
13156bool InstCombiner::runOnFunction(Function &F) {
13157 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013158 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013159
13160 bool EverMadeChange = false;
13161
13162 // Iterate while there is work to do.
13163 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013164 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013165 EverMadeChange = true;
13166 return EverMadeChange;
13167}
13168
13169FunctionPass *llvm::createInstructionCombiningPass() {
13170 return new InstCombiner();
13171}