blob: 312ea5d3ca69098e634e0c364e8de611a7a3376f [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)
Owen Anderson35b47072009-08-13 21:58:54 +0000438 return Type::getInt32Ty(Ty->getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 }
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,
Owen Anderson35b47072009-08-13 21:58:54 +0000476 TD ? TD->getIntPtrType(CI->getContext()) : 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.
Owen Anderson35b47072009-08-13 21:58:54 +0000480 if ((Res == Instruction::IntToPtr &&
Dan Gohman033445f2009-08-19 23:38:22 +0000481 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson35b47072009-08-13 21:58:54 +0000482 (Res == Instruction::PtrToInt &&
Dan Gohman033445f2009-08-19 23:38:22 +0000483 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000484 Res = 0;
485
486 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487}
488
489/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490/// in any code being generated. It does not require codegen if V is simple
491/// enough or if the cast can be folded into other casts.
492static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
494 if (V->getType() == Ty || isa<Constant>(V)) return false;
495
496 // If this is another cast that can be eliminated, it isn't codegen either.
497 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000498 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499 return false;
500 return true;
501}
502
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503// SimplifyCommutative - This performs a few simplifications for commutative
504// operators:
505//
506// 1. Order operands such that they are listed from right (least complex) to
507// left (most complex). This puts constants before unary operators before
508// binary operators.
509//
510// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
512//
513bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514 bool Changed = false;
Owen Anderson15b39322009-07-13 04:09:18 +0000515 if (getComplexity(Context, I.getOperand(0)) <
516 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 Changed = !I.swapOperands();
518
519 if (!I.isAssociative()) return Changed;
520 Instruction::BinaryOps Opcode = I.getOpcode();
521 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000524 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 cast<Constant>(I.getOperand(1)),
526 cast<Constant>(Op->getOperand(1)));
527 I.setOperand(0, Op->getOperand(0));
528 I.setOperand(1, Folded);
529 return true;
530 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532 isOnlyUse(Op) && isOnlyUse(Op1)) {
533 Constant *C1 = cast<Constant>(Op->getOperand(1));
534 Constant *C2 = cast<Constant>(Op1->getOperand(1));
535
536 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000537 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000538 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 Op1->getOperand(0),
540 Op1->getName(), &I);
541 AddToWorkList(New);
542 I.setOperand(0, New);
543 I.setOperand(1, Folded);
544 return true;
545 }
546 }
547 return Changed;
548}
549
550/// SimplifyCompare - For a CmpInst this function just orders the operands
551/// so that theyare listed from right (least complex) to left (most complex).
552/// This puts constants before unary operators before binary operators.
553bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson15b39322009-07-13 04:09:18 +0000554 if (getComplexity(Context, I.getOperand(0)) >=
555 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 return false;
557 I.swapOperands();
558 // Compare instructions are not associative so there's nothing else we can do.
559 return true;
560}
561
562// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
563// if the LHS is a constant zero (which is the 'negate' form).
564//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000565static inline Value *dyn_castNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000566 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 return BinaryOperator::getNegArgument(V);
568
569 // Constants can be considered to be negated values if they can be folded.
570 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000571 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000572
573 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
574 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000575 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000576
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 return 0;
578}
579
Dan Gohman7ce405e2009-06-04 22:49:04 +0000580// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
581// instruction if the LHS is a constant negative zero (which is the 'negate'
582// form).
583//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000584static inline Value *dyn_castFNegVal(Value *V) {
Owen Anderson76f49252009-07-13 22:18:28 +0000585 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000586 return BinaryOperator::getFNegArgument(V);
587
588 // Constants can be considered to be negated values if they can be folded.
589 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000590 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000591
592 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
593 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000594 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000595
596 return 0;
597}
598
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000599static inline Value *dyn_castNotVal(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 if (BinaryOperator::isNot(V))
601 return BinaryOperator::getNotArgument(V);
602
603 // Constants can be considered to be not'ed values...
604 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000605 return ConstantInt::get(C->getType(), ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 return 0;
607}
608
609// dyn_castFoldableMul - If this value is a multiply that can be folded into
610// other computations (because it has a constant operand), return the
611// non-constant operand of the multiply, and set CST to point to the multiplier.
612// Otherwise, return null.
613//
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000614static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615 if (V->hasOneUse() && V->getType()->isInteger())
616 if (Instruction *I = dyn_cast<Instruction>(V)) {
617 if (I->getOpcode() == Instruction::Mul)
618 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
619 return I->getOperand(0);
620 if (I->getOpcode() == Instruction::Shl)
621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
622 // The multiplier is really 1 << CST.
623 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
624 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000625 CST = ConstantInt::get(V->getType()->getContext(),
626 APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 return I->getOperand(0);
628 }
629 }
630 return 0;
631}
632
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633/// AddOne - Add one to a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000634static Constant *AddOne(Constant *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000635 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000636 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637}
638/// SubOne - Subtract one from a ConstantInt
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000639static Constant *SubOne(ConstantInt *C) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000640 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000641 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000643/// MultiplyOverflows - True if the multiply can not be expressed in an int
644/// this size.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000645static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000646 uint32_t W = C1->getBitWidth();
647 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
648 if (sign) {
649 LHSExt.sext(W * 2);
650 RHSExt.sext(W * 2);
651 } else {
652 LHSExt.zext(W * 2);
653 RHSExt.zext(W * 2);
654 }
655
656 APInt MulExt = LHSExt * RHSExt;
657
658 if (sign) {
659 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
660 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
661 return MulExt.slt(Min) || MulExt.sgt(Max);
662 } else
663 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
664}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666
667/// ShrinkDemandedConstant - Check to see if the specified operand of the
668/// specified instruction is a constant integer. If so, check to see if there
669/// are any bits set in the constant that are not demanded. If so, shrink the
670/// constant and return true.
671static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000672 APInt Demanded) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 assert(I && "No instruction?");
674 assert(OpNo < I->getNumOperands() && "Operand index too large");
675
676 // If the operand is not a constant integer, nothing to do.
677 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
678 if (!OpC) return false;
679
680 // If there are no bits set that aren't demanded, nothing to do.
681 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
682 if ((~Demanded & OpC->getValue()) == 0)
683 return false;
684
685 // This instruction is producing bits that are not demanded. Shrink the RHS.
686 Demanded &= OpC->getValue();
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000687 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 return true;
689}
690
691// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
692// set of known zero and one bits, compute the maximum and minimum values that
693// could have the specified known zero and known one bits, returning them in
694// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000695static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 const APInt& KnownOne,
697 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000698 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
699 KnownZero.getBitWidth() == Min.getBitWidth() &&
700 KnownZero.getBitWidth() == Max.getBitWidth() &&
701 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 APInt UnknownBits = ~(KnownZero|KnownOne);
703
704 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
705 // bit if it is unknown.
706 Min = KnownOne;
707 Max = KnownOne|UnknownBits;
708
Dan Gohman7934d592009-04-25 17:12:48 +0000709 if (UnknownBits.isNegative()) { // Sign bit is unknown
710 Min.set(Min.getBitWidth()-1);
711 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712 }
713}
714
715// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
716// a set of known zero and one bits, compute the maximum and minimum values that
717// could have the specified known zero and known one bits, returning them in
718// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000719static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000720 const APInt &KnownOne,
721 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000722 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
723 KnownZero.getBitWidth() == Min.getBitWidth() &&
724 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
726 APInt UnknownBits = ~(KnownZero|KnownOne);
727
728 // The minimum value is when the unknown bits are all zeros.
729 Min = KnownOne;
730 // The maximum value is when the unknown bits are all ones.
731 Max = KnownOne|UnknownBits;
732}
733
Chris Lattner676c78e2009-01-31 08:15:18 +0000734/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
735/// SimplifyDemandedBits knows about. See if the instruction has any
736/// properties that allow us to simplify its operands.
737bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000738 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000739 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
740 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
741
742 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
743 KnownZero, KnownOne, 0);
744 if (V == 0) return false;
745 if (V == &Inst) return true;
746 ReplaceInstUsesWith(Inst, V);
747 return true;
748}
749
750/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
751/// specified instruction operand if possible, updating it in place. It returns
752/// true if it made any change and false otherwise.
753bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
754 APInt &KnownZero, APInt &KnownOne,
755 unsigned Depth) {
756 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
757 KnownZero, KnownOne, Depth);
758 if (NewVal == 0) return false;
759 U.set(NewVal);
760 return true;
761}
762
763
764/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
765/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766/// that only the bits set in DemandedMask of the result of V are ever used
767/// downstream. Consequently, depending on the mask and V, it may be possible
768/// to replace V with a constant or one of its operands. In such cases, this
769/// function does the replacement and returns true. In all other cases, it
770/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000771/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772/// to be zero in the expression. These are provided to potentially allow the
773/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
774/// the expression. KnownOne and KnownZero always follow the invariant that
775/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
776/// the bits in KnownOne and KnownZero may only be accurate for those bits set
777/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
778/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000779///
780/// This returns null if it did not change anything and it permits no
781/// simplification. This returns V itself if it did some simplification of V's
782/// operands based on the information about what bits are demanded. This returns
783/// some other non-null value if it found out that V is equal to another value
784/// in the context where the specified bits are demanded, but not for all users.
785Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
786 APInt &KnownZero, APInt &KnownOne,
787 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 assert(V != 0 && "Null pointer of Value???");
789 assert(Depth <= 6 && "Limit Search Depth");
790 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000791 const Type *VTy = V->getType();
792 assert((TD || !isa<PointerType>(VTy)) &&
793 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000794 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
795 (!VTy->isIntOrIntVector() ||
796 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000797 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000799 "Value *V, DemandedMask, KnownZero and KnownOne "
800 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000801 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
802 // We know all of the bits for a constant!
803 KnownOne = CI->getValue() & DemandedMask;
804 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000805 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000806 }
Dan Gohman7934d592009-04-25 17:12:48 +0000807 if (isa<ConstantPointerNull>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne.clear();
810 KnownZero = DemandedMask;
811 return 0;
812 }
813
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000814 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000816 if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (isa<UndefValue>(V))
818 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000819 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 }
821
Chris Lattner08817332009-01-31 08:24:16 +0000822 if (Depth == 6) // Limit search depth.
823 return 0;
824
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000825 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
826 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
827
Dan Gohman7934d592009-04-25 17:12:48 +0000828 Instruction *I = dyn_cast<Instruction>(V);
829 if (!I) {
830 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
831 return 0; // Only analyze instructions.
832 }
833
Chris Lattner08817332009-01-31 08:24:16 +0000834 // If there are multiple uses of this value and we aren't at the root, then
835 // we can't do any simplifications of the operands, because DemandedMask
836 // only reflects the bits demanded by *one* of the users.
837 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000838 // Despite the fact that we can't simplify this instruction in all User's
839 // context, we can at least compute the knownzero/knownone bits, and we can
840 // do simplifications that apply to *just* the one user if we know that
841 // this instruction has a simpler value in that context.
842 if (I->getOpcode() == Instruction::And) {
843 // If either the LHS or the RHS are Zero, the result is zero.
844 ComputeMaskedBits(I->getOperand(1), DemandedMask,
845 RHSKnownZero, RHSKnownOne, Depth+1);
846 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
847 LHSKnownZero, LHSKnownOne, Depth+1);
848
849 // If all of the demanded bits are known 1 on one side, return the other.
850 // These bits cannot contribute to the result of the 'and' in this
851 // context.
852 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
853 (DemandedMask & ~LHSKnownZero))
854 return I->getOperand(0);
855 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
856 (DemandedMask & ~RHSKnownZero))
857 return I->getOperand(1);
858
859 // If all of the demanded bits in the inputs are known zeros, return zero.
860 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000861 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000862
863 } else if (I->getOpcode() == Instruction::Or) {
864 // We can simplify (X|Y) -> X or Y in the user's context if we know that
865 // only bits from X or Y are demanded.
866
867 // If either the LHS or the RHS are One, the result is One.
868 ComputeMaskedBits(I->getOperand(1), DemandedMask,
869 RHSKnownZero, RHSKnownOne, Depth+1);
870 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
871 LHSKnownZero, LHSKnownOne, Depth+1);
872
873 // If all of the demanded bits are known zero on one side, return the
874 // other. These bits cannot contribute to the result of the 'or' in this
875 // context.
876 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
877 (DemandedMask & ~LHSKnownOne))
878 return I->getOperand(0);
879 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
880 (DemandedMask & ~RHSKnownOne))
881 return I->getOperand(1);
882
883 // If all of the potentially set bits on one side are known to be set on
884 // the other side, just use the 'other' side.
885 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
886 (DemandedMask & (~RHSKnownZero)))
887 return I->getOperand(0);
888 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
889 (DemandedMask & (~LHSKnownZero)))
890 return I->getOperand(1);
891 }
892
Chris Lattner08817332009-01-31 08:24:16 +0000893 // Compute the KnownZero/KnownOne bits to simplify things downstream.
894 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
895 return 0;
896 }
897
898 // If this is the root being simplified, allow it to have multiple uses,
899 // just set the DemandedMask to all bits so that we can try to simplify the
900 // operands. This allows visitTruncInst (for example) to simplify the
901 // operand of a trunc without duplicating all the logic below.
902 if (Depth == 0 && !V->hasOneUse())
903 DemandedMask = APInt::getAllOnesValue(BitWidth);
904
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000906 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000907 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000908 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909 case Instruction::And:
910 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000911 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
912 RHSKnownZero, RHSKnownOne, Depth+1) ||
913 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000915 return I;
916 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
917 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000918
919 // If all of the demanded bits are known 1 on one side, return the other.
920 // These bits cannot contribute to the result of the 'and'.
921 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
922 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000923 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
925 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000926 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927
928 // If all of the demanded bits in the inputs are known zeros, return zero.
929 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000930 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931
932 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000933 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000934 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935
936 // Output known-1 bits are only known if set in both the LHS & RHS.
937 RHSKnownOne &= LHSKnownOne;
938 // Output known-0 are known to be clear if zero in either the LHS | RHS.
939 RHSKnownZero |= LHSKnownZero;
940 break;
941 case Instruction::Or:
942 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000943 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944 RHSKnownZero, RHSKnownOne, Depth+1) ||
945 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000947 return I;
948 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
949 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000950
951 // If all of the demanded bits are known zero on one side, return the other.
952 // These bits cannot contribute to the result of the 'or'.
953 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
954 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000955 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
957 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000958 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959
960 // If all of the potentially set bits on one side are known to be set on
961 // the other side, just use the 'other' side.
962 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
963 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000964 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
966 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000967 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000968
969 // If the RHS is a constant, see if we can simplify it.
Dan Gohmanfe91cd62009-08-12 16:04:34 +0000970 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000971 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972
973 // Output known-0 bits are only known if clear in both the LHS & RHS.
974 RHSKnownZero &= LHSKnownZero;
975 // Output known-1 are known to be set if set in either the LHS | RHS.
976 RHSKnownOne |= LHSKnownOne;
977 break;
978 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000979 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
980 RHSKnownZero, RHSKnownOne, Depth+1) ||
981 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000983 return I;
984 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
985 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986
987 // If all of the demanded bits are known zero on one side, return the other.
988 // These bits cannot contribute to the result of the 'xor'.
989 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000992 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
994 // Output known-0 bits are known if clear or set in both the LHS & RHS.
995 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
996 (RHSKnownOne & LHSKnownOne);
997 // Output known-1 are known to be set if set in only one of the LHS, RHS.
998 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
999 (RHSKnownOne & LHSKnownZero);
1000
1001 // If all of the demanded bits are known to be zero on one side or the
1002 // other, turn this into an *inclusive* or.
1003 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1004 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1005 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001006 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001008 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 }
1010
1011 // If all of the demanded bits on one side are known, and all of the set
1012 // bits on that side are also known to be set on the other side, turn this
1013 // into an AND, as we know the bits will be cleared.
1014 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1015 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1016 // all known
1017 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001018 Constant *AndC = Constant::getIntegerValue(VTy,
1019 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001021 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001022 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023 }
1024 }
1025
1026 // If the RHS is a constant, see if we can simplify it.
1027 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001028 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001029 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030
1031 RHSKnownZero = KnownZeroOut;
1032 RHSKnownOne = KnownOneOut;
1033 break;
1034 }
1035 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001036 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1037 RHSKnownZero, RHSKnownOne, Depth+1) ||
1038 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001040 return I;
1041 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1042 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043
1044 // If the operands are constants, see if we can simplify them.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001045 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1046 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001047 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048
1049 // Only known if known in both the LHS and RHS.
1050 RHSKnownOne &= LHSKnownOne;
1051 RHSKnownZero &= LHSKnownZero;
1052 break;
1053 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001054 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 DemandedMask.zext(truncBf);
1056 RHSKnownZero.zext(truncBf);
1057 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001058 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001060 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061 DemandedMask.trunc(BitWidth);
1062 RHSKnownZero.trunc(BitWidth);
1063 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001064 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 break;
1066 }
1067 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001068 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001069 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001070
1071 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1072 if (const VectorType *SrcVTy =
1073 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1074 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1075 // Don't touch a bitcast between vectors of different element counts.
1076 return false;
1077 } else
1078 // Don't touch a scalar-to-vector bitcast.
1079 return false;
1080 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1081 // Don't touch a vector-to-scalar bitcast.
1082 return false;
1083
Chris Lattner676c78e2009-01-31 08:15:18 +00001084 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001086 return I;
1087 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001088 break;
1089 case Instruction::ZExt: {
1090 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001091 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092
1093 DemandedMask.trunc(SrcBitWidth);
1094 RHSKnownZero.trunc(SrcBitWidth);
1095 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001096 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001098 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 DemandedMask.zext(BitWidth);
1100 RHSKnownZero.zext(BitWidth);
1101 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001102 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 // The top bits are known to be zero.
1104 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1105 break;
1106 }
1107 case Instruction::SExt: {
1108 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001109 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110
1111 APInt InputDemandedBits = DemandedMask &
1112 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1113
1114 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1115 // If any of the sign extended bits are demanded, we know that the sign
1116 // bit is demanded.
1117 if ((NewBits & DemandedMask) != 0)
1118 InputDemandedBits.set(SrcBitWidth-1);
1119
1120 InputDemandedBits.trunc(SrcBitWidth);
1121 RHSKnownZero.trunc(SrcBitWidth);
1122 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001123 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001125 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 InputDemandedBits.zext(BitWidth);
1127 RHSKnownZero.zext(BitWidth);
1128 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001129 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130
1131 // If the sign bit of the input is known set or clear, then we know the
1132 // top bits of the result.
1133
1134 // If the input sign bit is known zero, or if the NewBits are not demanded
1135 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001136 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001138 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1139 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1141 RHSKnownOne |= NewBits;
1142 }
1143 break;
1144 }
1145 case Instruction::Add: {
1146 // Figure out what the input bits are. If the top bits of the and result
1147 // are not demanded, then the add doesn't demand them from its input
1148 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001149 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150
1151 // If there is a constant on the RHS, there are a variety of xformations
1152 // we can do.
1153 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1154 // If null, this should be simplified elsewhere. Some of the xforms here
1155 // won't work if the RHS is zero.
1156 if (RHS->isZero())
1157 break;
1158
1159 // If the top bit of the output is demanded, demand everything from the
1160 // input. Otherwise, we demand all the input bits except NLZ top bits.
1161 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1162
1163 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001164 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001166 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167
1168 // If the RHS of the add has bits set that can't affect the input, reduce
1169 // the constant.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001170 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001171 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172
1173 // Avoid excess work.
1174 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1175 break;
1176
1177 // Turn it into OR if input bits are zero.
1178 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1179 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001180 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001182 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 }
1184
1185 // We can say something about the output known-zero and known-one bits,
1186 // depending on potential carries from the input constant and the
1187 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1188 // bits set and the RHS constant is 0x01001, then we know we have a known
1189 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1190
1191 // To compute this, we first compute the potential carry bits. These are
1192 // the bits which may be modified. I'm not aware of a better way to do
1193 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001194 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1196
1197 // Now that we know which bits have carries, compute the known-1/0 sets.
1198
1199 // Bits are known one if they are known zero in one operand and one in the
1200 // other, and there is no input carry.
1201 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1202 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1203
1204 // Bits are known zero if they are known zero in both operands and there
1205 // is no input carry.
1206 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1207 } else {
1208 // If the high-bits of this ADD are not demanded, then it does not demand
1209 // the high bits of its LHS or RHS.
1210 if (DemandedMask[BitWidth-1] == 0) {
1211 // Right fill the mask of bits for this ADD to demand the most
1212 // significant bit and all those below it.
1213 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001214 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1215 LHSKnownZero, LHSKnownOne, Depth+1) ||
1216 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001217 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001218 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 }
1220 }
1221 break;
1222 }
1223 case Instruction::Sub:
1224 // If the high-bits of this SUB are not demanded, then it does not demand
1225 // the high bits of its LHS or RHS.
1226 if (DemandedMask[BitWidth-1] == 0) {
1227 // Right fill the mask of bits for this SUB to demand the most
1228 // significant bit and all those below it.
1229 uint32_t NLZ = DemandedMask.countLeadingZeros();
1230 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001231 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1232 LHSKnownZero, LHSKnownOne, Depth+1) ||
1233 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001235 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001237 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1238 // the known zeros and ones.
1239 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 break;
1241 case Instruction::Shl:
1242 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1243 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1244 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001247 return I;
1248 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 RHSKnownZero <<= ShiftAmt;
1250 RHSKnownOne <<= ShiftAmt;
1251 // low bits known zero.
1252 if (ShiftAmt)
1253 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1254 }
1255 break;
1256 case Instruction::LShr:
1257 // For a logical shift right
1258 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1260
1261 // Unsigned shift right.
1262 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001263 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001265 return I;
1266 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1268 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1269 if (ShiftAmt) {
1270 // Compute the new bits that are at the top now.
1271 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1272 RHSKnownZero |= HighBits; // high bits known zero.
1273 }
1274 }
1275 break;
1276 case Instruction::AShr:
1277 // If this is an arithmetic shift right and only the low-bit is set, we can
1278 // always convert this into a logical shr, even if the shift amount is
1279 // variable. The low bit of the shift cannot be an input sign bit unless
1280 // the shift amount is >= the size of the datatype, which is undefined.
1281 if (DemandedMask == 1) {
1282 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001283 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001285 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 }
1287
1288 // If the sign bit is the only bit demanded by this ashr, then there is no
1289 // need to do it, the shift doesn't change the high bit.
1290 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001291 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292
1293 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1294 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1295
1296 // Signed shift right.
1297 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1298 // If any of the "high bits" are demanded, we should set the sign bit as
1299 // demanded.
1300 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1301 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001302 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001304 return I;
1305 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 // Compute the new bits that are at the top now.
1307 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1308 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1309 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1310
1311 // Handle the sign bits.
1312 APInt SignBit(APInt::getSignBit(BitWidth));
1313 // Adjust to where it is now in the mask.
1314 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1315
1316 // If the input sign bit is known to be zero, or if none of the top bits
1317 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001318 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 (HighBits & ~DemandedMask) == HighBits) {
1320 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001321 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001323 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1325 RHSKnownOne |= HighBits;
1326 }
1327 }
1328 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001329 case Instruction::SRem:
1330 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001331 APInt RA = Rem->getValue().abs();
1332 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001333 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001334 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001335
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001336 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001337 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001338 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001339 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001340 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001341
1342 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1343 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001344
1345 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001346
Chris Lattner676c78e2009-01-31 08:15:18 +00001347 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001348 }
1349 }
1350 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001351 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001352 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1353 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001354 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1355 KnownZero2, KnownOne2, Depth+1) ||
1356 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001357 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001358 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001359
Chris Lattneree5417c2009-01-21 18:09:24 +00001360 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001361 Leaders = std::max(Leaders,
1362 KnownZero2.countLeadingOnes());
1363 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001364 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 }
Chris Lattner989ba312008-06-18 04:33:20 +00001366 case Instruction::Call:
1367 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1368 switch (II->getIntrinsicID()) {
1369 default: break;
1370 case Intrinsic::bswap: {
1371 // If the only bits demanded come from one byte of the bswap result,
1372 // just shift the input byte into position to eliminate the bswap.
1373 unsigned NLZ = DemandedMask.countLeadingZeros();
1374 unsigned NTZ = DemandedMask.countTrailingZeros();
1375
1376 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1377 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1378 // have 14 leading zeros, round to 8.
1379 NLZ &= ~7;
1380 NTZ &= ~7;
1381 // If we need exactly one byte, we can do this transformation.
1382 if (BitWidth-NLZ-NTZ == 8) {
1383 unsigned ResultBit = NTZ;
1384 unsigned InputBit = BitWidth-NTZ-8;
1385
1386 // Replace this with either a left or right shift to get the byte into
1387 // the right place.
1388 Instruction *NewVal;
1389 if (InputBit > ResultBit)
1390 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001391 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001392 else
1393 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001394 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001395 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001396 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001397 }
1398
1399 // TODO: Could compute known zero/one bits based on the input.
1400 break;
1401 }
1402 }
1403 }
Chris Lattner4946e222008-06-18 18:11:55 +00001404 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001405 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001406 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001407
1408 // If the client is only demanding bits that we know, return the known
1409 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001410 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1411 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 return false;
1413}
1414
1415
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001416/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001417/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418/// actually used by the caller. This method analyzes which elements of the
1419/// operand are undef and returns that information in UndefElts.
1420///
1421/// If the information about demanded elements can be used to simplify the
1422/// operation, the operation is simplified, then the resultant value is
1423/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001424Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1425 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 unsigned Depth) {
1427 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001428 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001429 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430
1431 if (isa<UndefValue>(V)) {
1432 // If the entire vector is undefined, just return this info.
1433 UndefElts = EltMask;
1434 return 0;
1435 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1436 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001437 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001439
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 UndefElts = 0;
1441 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1442 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001443 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444
1445 std::vector<Constant*> Elts;
1446 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001447 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001449 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1451 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001452 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453 } else { // Otherwise, defined.
1454 Elts.push_back(CP->getOperand(i));
1455 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001456
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001458 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 return NewCP != CP ? NewCP : 0;
1460 } else if (isa<ConstantAggregateZero>(V)) {
1461 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1462 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001463
1464 // Check if this is identity. If so, return 0 since we are not simplifying
1465 // anything.
1466 if (DemandedElts == ((1ULL << VWidth) -1))
1467 return 0;
1468
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001470 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001471 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001473 for (unsigned i = 0; i != VWidth; ++i) {
1474 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1475 Elts.push_back(Elt);
1476 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001478 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479 }
1480
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001481 // Limit search depth.
1482 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001483 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001484
1485 // If multiple users are using the root value, procede with
1486 // simplification conservatively assuming that all elements
1487 // are needed.
1488 if (!V->hasOneUse()) {
1489 // Quit if we find multiple users of a non-root value though.
1490 // They'll be handled when it's their turn to be visited by
1491 // the main instcombine process.
1492 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001494 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001495
1496 // Conservatively assume that all elements are needed.
1497 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001498 }
1499
1500 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001501 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001502
1503 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001504 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505 Value *TmpV;
1506 switch (I->getOpcode()) {
1507 default: break;
1508
1509 case Instruction::InsertElement: {
1510 // If this is a variable index, we don't know which element it overwrites.
1511 // demand exactly the same input as we produce.
1512 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1513 if (Idx == 0) {
1514 // Note that we can't propagate undef elt info, because we don't know
1515 // which elt is getting updated.
1516 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1517 UndefElts2, Depth+1);
1518 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1519 break;
1520 }
1521
1522 // If this is inserting an element that isn't demanded, remove this
1523 // insertelement.
1524 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001525 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526 return AddSoonDeadInstToWorklist(*I, 0);
1527
1528 // Otherwise, the element inserted overwrites whatever was there, so the
1529 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001530 APInt DemandedElts2 = DemandedElts;
1531 DemandedElts2.clear(IdxNo);
1532 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 UndefElts, Depth+1);
1534 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1535
1536 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001537 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001538 break;
1539 }
1540 case Instruction::ShuffleVector: {
1541 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001542 uint64_t LHSVWidth =
1543 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001544 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001545 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001546 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001547 unsigned MaskVal = Shuffle->getMaskValue(i);
1548 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001549 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001550 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001551 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001552 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001553 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001554 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001555 }
1556 }
1557 }
1558
Nate Begemanb4d176f2009-02-11 22:36:25 +00001559 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001560 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001561 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001562 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1563
Nate Begemanb4d176f2009-02-11 22:36:25 +00001564 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001565 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1566 UndefElts3, Depth+1);
1567 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1568
1569 bool NewUndefElts = false;
1570 for (unsigned i = 0; i < VWidth; i++) {
1571 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001572 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001573 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001574 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001575 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001576 NewUndefElts = true;
1577 UndefElts.set(i);
1578 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001579 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001580 if (UndefElts3[MaskVal - LHSVWidth]) {
1581 NewUndefElts = true;
1582 UndefElts.set(i);
1583 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001584 }
1585 }
1586
1587 if (NewUndefElts) {
1588 // Add additional discovered undefs.
1589 std::vector<Constant*> Elts;
1590 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001591 if (UndefElts[i])
Owen Anderson35b47072009-08-13 21:58:54 +00001592 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001593 else
Owen Anderson35b47072009-08-13 21:58:54 +00001594 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001595 Shuffle->getMaskValue(i)));
1596 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001597 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001598 MadeChange = true;
1599 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001600 break;
1601 }
1602 case Instruction::BitCast: {
1603 // Vector->vector casts only.
1604 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1605 if (!VTy) break;
1606 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001607 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 unsigned Ratio;
1609
1610 if (VWidth == InVWidth) {
1611 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1612 // elements as are demanded of us.
1613 Ratio = 1;
1614 InputDemandedElts = DemandedElts;
1615 } else if (VWidth > InVWidth) {
1616 // Untested so far.
1617 break;
1618
1619 // If there are more elements in the result than there are in the source,
1620 // then an input element is live if any of the corresponding output
1621 // elements are live.
1622 Ratio = VWidth/InVWidth;
1623 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001624 if (DemandedElts[OutIdx])
1625 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001626 }
1627 } else {
1628 // Untested so far.
1629 break;
1630
1631 // If there are more elements in the source than there are in the result,
1632 // then an input element is live if the corresponding output element is
1633 // live.
1634 Ratio = InVWidth/VWidth;
1635 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001636 if (DemandedElts[InIdx/Ratio])
1637 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001638 }
1639
1640 // div/rem demand all inputs, because they don't want divide by zero.
1641 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1642 UndefElts2, Depth+1);
1643 if (TmpV) {
1644 I->setOperand(0, TmpV);
1645 MadeChange = true;
1646 }
1647
1648 UndefElts = UndefElts2;
1649 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001650 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001651 // If there are more elements in the result than there are in the source,
1652 // then an output element is undef if the corresponding input element is
1653 // undef.
1654 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001655 if (UndefElts2[OutIdx/Ratio])
1656 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001658 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001659 // If there are more elements in the source than there are in the result,
1660 // then a result element is undef if all of the corresponding input
1661 // elements are undef.
1662 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1663 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001664 if (!UndefElts2[InIdx]) // Not undef?
1665 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666 }
1667 break;
1668 }
1669 case Instruction::And:
1670 case Instruction::Or:
1671 case Instruction::Xor:
1672 case Instruction::Add:
1673 case Instruction::Sub:
1674 case Instruction::Mul:
1675 // div/rem demand all inputs, because they don't want divide by zero.
1676 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1677 UndefElts, Depth+1);
1678 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1679 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1680 UndefElts2, Depth+1);
1681 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1682
1683 // Output elements are undefined if both are undefined. Consider things
1684 // like undef&0. The result is known zero, not undef.
1685 UndefElts &= UndefElts2;
1686 break;
1687
1688 case Instruction::Call: {
1689 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1690 if (!II) break;
1691 switch (II->getIntrinsicID()) {
1692 default: break;
1693
1694 // Binary vector operations that work column-wise. A dest element is a
1695 // function of the corresponding input elements from the two inputs.
1696 case Intrinsic::x86_sse_sub_ss:
1697 case Intrinsic::x86_sse_mul_ss:
1698 case Intrinsic::x86_sse_min_ss:
1699 case Intrinsic::x86_sse_max_ss:
1700 case Intrinsic::x86_sse2_sub_sd:
1701 case Intrinsic::x86_sse2_mul_sd:
1702 case Intrinsic::x86_sse2_min_sd:
1703 case Intrinsic::x86_sse2_max_sd:
1704 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1705 UndefElts, Depth+1);
1706 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1707 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1708 UndefElts2, Depth+1);
1709 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1710
1711 // If only the low elt is demanded and this is a scalarizable intrinsic,
1712 // scalarize it now.
1713 if (DemandedElts == 1) {
1714 switch (II->getIntrinsicID()) {
1715 default: break;
1716 case Intrinsic::x86_sse_sub_ss:
1717 case Intrinsic::x86_sse_mul_ss:
1718 case Intrinsic::x86_sse2_sub_sd:
1719 case Intrinsic::x86_sse2_mul_sd:
1720 // TODO: Lower MIN/MAX/ABS/etc
1721 Value *LHS = II->getOperand(1);
1722 Value *RHS = II->getOperand(2);
1723 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001724 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001725 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001726 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson35b47072009-08-13 21:58:54 +00001727 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728
1729 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001730 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001733 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734 II->getName()), *II);
1735 break;
1736 case Intrinsic::x86_sse_mul_ss:
1737 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001738 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739 II->getName()), *II);
1740 break;
1741 }
1742
1743 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001744 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001745 UndefValue::get(II->getType()), TmpV,
Owen Anderson35b47072009-08-13 21:58:54 +00001746 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747 InsertNewInstBefore(New, *II);
1748 AddSoonDeadInstToWorklist(*II, 0);
1749 return New;
1750 }
1751 }
1752
1753 // Output elements are undefined if both are undefined. Consider things
1754 // like undef&0. The result is known zero, not undef.
1755 UndefElts &= UndefElts2;
1756 break;
1757 }
1758 break;
1759 }
1760 }
1761 return MadeChange ? I : 0;
1762}
1763
Dan Gohman5d56fd42008-05-19 22:14:15 +00001764
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765/// AssociativeOpt - Perform an optimization on an associative operator. This
1766/// function is designed to check a chain of associative operators for a
1767/// potential to apply a certain optimization. Since the optimization may be
1768/// applicable if the expression was reassociated, this checks the chain, then
1769/// reassociates the expression as necessary to expose the optimization
1770/// opportunity. This makes use of a special Functor, which must define
1771/// 'shouldApply' and 'apply' methods.
1772///
1773template<typename Functor>
Dan Gohmanfe91cd62009-08-12 16:04:34 +00001774static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001775 unsigned Opcode = Root.getOpcode();
1776 Value *LHS = Root.getOperand(0);
1777
1778 // Quick check, see if the immediate LHS matches...
1779 if (F.shouldApply(LHS))
1780 return F.apply(Root);
1781
1782 // Otherwise, if the LHS is not of the same opcode as the root, return.
1783 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1784 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1785 // Should we apply this transform to the RHS?
1786 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1787
1788 // If not to the RHS, check to see if we should apply to the LHS...
1789 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1790 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1791 ShouldApply = true;
1792 }
1793
1794 // If the functor wants to apply the optimization to the RHS of LHSI,
1795 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1796 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001797 // Now all of the instructions are in the current basic block, go ahead
1798 // and perform the reassociation.
1799 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1800
1801 // First move the selected RHS to the LHS of the root...
1802 Root.setOperand(0, LHSI->getOperand(1));
1803
1804 // Make what used to be the LHS of the root be the user of the root...
1805 Value *ExtraOperand = TmpLHSI->getOperand(1);
1806 if (&Root == TmpLHSI) {
Owen Andersonaac28372009-07-31 20:28:14 +00001807 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001808 return 0;
1809 }
1810 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1811 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001813 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001814 ARI = Root;
1815
1816 // Now propagate the ExtraOperand down the chain of instructions until we
1817 // get to LHSI.
1818 while (TmpLHSI != LHSI) {
1819 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1820 // Move the instruction to immediately before the chain we are
1821 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001822 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001823 ARI = NextLHSI;
1824
1825 Value *NextOp = NextLHSI->getOperand(1);
1826 NextLHSI->setOperand(1, ExtraOperand);
1827 TmpLHSI = NextLHSI;
1828 ExtraOperand = NextOp;
1829 }
1830
1831 // Now that the instructions are reassociated, have the functor perform
1832 // the transformation...
1833 return F.apply(Root);
1834 }
1835
1836 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1837 }
1838 return 0;
1839}
1840
Dan Gohman089efff2008-05-13 00:00:25 +00001841namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842
Nick Lewycky27f6c132008-05-23 04:34:58 +00001843// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001844struct AddRHS {
1845 Value *RHS;
Dan Gohmancdff2122009-08-12 16:23:25 +00001846 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001847 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1848 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001849 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001850 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851 }
1852};
1853
1854// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1855// iff C1&C2 == 0
1856struct AddMaskingAnd {
1857 Constant *C2;
Dan Gohmancdff2122009-08-12 16:23:25 +00001858 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001859 bool shouldApply(Value *LHS) const {
1860 ConstantInt *C1;
Dan Gohmancdff2122009-08-12 16:23:25 +00001861 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001862 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 }
1864 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001865 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001866 }
1867};
1868
Dan Gohman089efff2008-05-13 00:00:25 +00001869}
1870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1872 InstCombiner *IC) {
Owen Anderson5349f052009-07-06 23:00:19 +00001873 LLVMContext *Context = IC->getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00001874
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001876 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001877 }
1878
1879 // Figure out if the constant is the left or the right argument.
1880 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1881 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1882
1883 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1884 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001885 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1886 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001887 }
1888
1889 Value *Op0 = SO, *Op1 = ConstOperand;
1890 if (!ConstIsRHS)
1891 std::swap(Op0, Op1);
1892 Instruction *New;
1893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001894 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001895 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00001896 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +00001897 Op0, Op1, SO->getName()+".cmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898 else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001899 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 }
1901 return IC->InsertNewInstBefore(New, I);
1902}
1903
1904// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1905// constant as the other operand, try to fold the binary operator into the
1906// select arguments. This also works for Cast instructions, which obviously do
1907// not have a second operand.
1908static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1909 InstCombiner *IC) {
1910 // Don't modify shared select instructions
1911 if (!SI->hasOneUse()) return 0;
1912 Value *TV = SI->getOperand(1);
1913 Value *FV = SI->getOperand(2);
1914
1915 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1916 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson35b47072009-08-13 21:58:54 +00001917 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001918
1919 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1920 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1921
Gabor Greifd6da1d02008-04-06 20:25:17 +00001922 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1923 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001924 }
1925 return 0;
1926}
1927
1928
1929/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1930/// node as operand #0, see if we can fold the instruction into the PHI (which
1931/// is only possible if all operands to the PHI are constants).
1932Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1933 PHINode *PN = cast<PHINode>(I.getOperand(0));
1934 unsigned NumPHIValues = PN->getNumIncomingValues();
1935 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1936
1937 // Check to see if all of the operands of the PHI are constants. If there is
1938 // one non-constant value, remember the BB it is. If there is more than one
1939 // or if *it* is a PHI, bail out.
1940 BasicBlock *NonConstBB = 0;
1941 for (unsigned i = 0; i != NumPHIValues; ++i)
1942 if (!isa<Constant>(PN->getIncomingValue(i))) {
1943 if (NonConstBB) return 0; // More than one non-const value.
1944 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1945 NonConstBB = PN->getIncomingBlock(i);
1946
1947 // If the incoming non-constant value is in I's block, we have an infinite
1948 // loop.
1949 if (NonConstBB == I.getParent())
1950 return 0;
1951 }
1952
1953 // If there is exactly one non-constant value, we can insert a copy of the
1954 // operation in that block. However, if this is a critical edge, we would be
1955 // inserting the computation one some other paths (e.g. inside a loop). Only
1956 // do this if the pred block is unconditionally branching into the phi block.
1957 if (NonConstBB) {
1958 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1959 if (!BI || !BI->isUnconditional()) return 0;
1960 }
1961
1962 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001963 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001964 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1965 InsertNewInstBefore(NewPN, *PN);
1966 NewPN->takeName(PN);
1967
1968 // Next, add all of the operands to the PHI.
1969 if (I.getNumOperands() == 2) {
1970 Constant *C = cast<Constant>(I.getOperand(1));
1971 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001972 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001973 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1974 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00001975 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 else
Owen Anderson02b48c32009-07-29 18:55:55 +00001977 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001978 } else {
1979 assert(PN->getIncomingBlock(i) == NonConstBB);
1980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001981 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001982 PN->getIncomingValue(i), C, "phitmp",
1983 NonConstBB->getTerminator());
1984 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +00001985 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986 CI->getPredicate(),
1987 PN->getIncomingValue(i), C, "phitmp",
1988 NonConstBB->getTerminator());
1989 else
Edwin Törökbd448e32009-07-14 16:55:14 +00001990 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001991
1992 AddToWorkList(cast<Instruction>(InV));
1993 }
1994 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1995 }
1996 } else {
1997 CastInst *CI = cast<CastInst>(&I);
1998 const Type *RetTy = CI->getType();
1999 for (unsigned i = 0; i != NumPHIValues; ++i) {
2000 Value *InV;
2001 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002002 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002003 } else {
2004 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002005 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002006 I.getType(), "phitmp",
2007 NonConstBB->getTerminator());
2008 AddToWorkList(cast<Instruction>(InV));
2009 }
2010 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2011 }
2012 }
2013 return ReplaceInstUsesWith(I, NewPN);
2014}
2015
Chris Lattner55476162008-01-29 06:52:45 +00002016
Chris Lattner3554f972008-05-20 05:46:13 +00002017/// WillNotOverflowSignedAdd - Return true if we can prove that:
2018/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2019/// This basically requires proving that the add in the original type would not
2020/// overflow to change the sign bit or have a carry out.
2021bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2022 // There are different heuristics we can use for this. Here are some simple
2023 // ones.
2024
2025 // Add has the property that adding any two 2's complement numbers can only
2026 // have one carry bit which can change a sign. As such, if LHS and RHS each
2027 // have at least two sign bits, we know that the addition of the two values will
2028 // sign extend fine.
2029 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2030 return true;
2031
2032
2033 // If one of the operands only has one non-zero bit, and if the other operand
2034 // has a known-zero bit in a more significant place than it (not including the
2035 // sign bit) the ripple may go up to and fill the zero, but won't change the
2036 // sign. For example, (X & ~4) + 1.
2037
2038 // TODO: Implement.
2039
2040 return false;
2041}
2042
Chris Lattner55476162008-01-29 06:52:45 +00002043
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2045 bool Changed = SimplifyCommutative(I);
2046 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2047
2048 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2049 // X + undef -> undef
2050 if (isa<UndefValue>(RHS))
2051 return ReplaceInstUsesWith(I, RHS);
2052
2053 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002054 if (RHSC->isNullValue())
2055 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002056
2057 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2058 // X + (signbit) --> X ^ signbit
2059 const APInt& Val = CI->getValue();
2060 uint32_t BitWidth = Val.getBitWidth();
2061 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002062 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063
2064 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2065 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002066 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002067 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002068
Eli Friedmana21526d2009-07-13 22:27:52 +00002069 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002070 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson35b47072009-08-13 21:58:54 +00002071 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002072 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002073 }
2074
2075 if (isa<PHINode>(LHS))
2076 if (Instruction *NV = FoldOpIntoPhi(I))
2077 return NV;
2078
2079 ConstantInt *XorRHS = 0;
2080 Value *XorLHS = 0;
2081 if (isa<ConstantInt>(RHSC) &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002082 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002083 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2085
2086 uint32_t Size = TySizeBits / 2;
2087 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2088 APInt CFF80Val(-C0080Val);
2089 do {
2090 if (TySizeBits > Size) {
2091 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2092 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2093 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2094 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2095 // This is a sign extend if the top bits are known zero.
2096 if (!MaskedValueIsZero(XorLHS,
2097 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2098 Size = 0; // Not a sign ext, but can't be any others either.
2099 break;
2100 }
2101 }
2102 Size >>= 1;
2103 C0080Val = APIntOps::lshr(C0080Val, Size);
2104 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2105 } while (Size >= 1);
2106
2107 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002108 // with funny bit widths then this switch statement should be removed. It
2109 // is just here to get the size of the "middle" type back up to something
2110 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002111 const Type *MiddleType = 0;
2112 switch (Size) {
2113 default: break;
Owen Anderson35b47072009-08-13 21:58:54 +00002114 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2115 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2116 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002117 }
2118 if (MiddleType) {
2119 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2120 InsertNewInstBefore(NewTrunc, I);
2121 return new SExtInst(NewTrunc, I.getType(), I.getName());
2122 }
2123 }
2124 }
2125
Owen Anderson35b47072009-08-13 21:58:54 +00002126 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002127 return BinaryOperator::CreateXor(LHS, RHS);
2128
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002129 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002130 if (I.getType()->isInteger()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00002131 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Anderson24be4c12009-07-03 00:17:18 +00002132 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002133
2134 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2135 if (RHSI->getOpcode() == Instruction::Sub)
2136 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2137 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2138 }
2139 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2140 if (LHSI->getOpcode() == Instruction::Sub)
2141 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2142 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2143 }
2144 }
2145
2146 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002147 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002148 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002149 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002150 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002151 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002152 InsertNewInstBefore(NewAdd, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00002153 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002154 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002155 }
2156
Gabor Greifa645dd32008-05-16 19:29:10 +00002157 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002158 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159
2160 // A + -B --> A - B
2161 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002162 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002164
2165
2166 ConstantInt *C2;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002167 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002169 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002170
2171 // X*C1 + X*C2 --> X * (C1+C2)
2172 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002173 if (X == dyn_castFoldableMul(RHS, C1))
Owen Anderson02b48c32009-07-29 18:55:55 +00002174 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175 }
2176
2177 // X + X*C --> X * (C+1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002178 if (dyn_castFoldableMul(RHS, C2) == LHS)
2179 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002180
2181 // X + ~X --> -1 since ~X = -X-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002182 if (dyn_castNotVal(LHS) == RHS ||
2183 dyn_castNotVal(RHS) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002184 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002185
2186
2187 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohmancdff2122009-08-12 16:23:25 +00002188 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2189 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002190 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002191
2192 // A+B --> A|B iff A and B have no bits set in common.
2193 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2194 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2195 APInt LHSKnownOne(IT->getBitWidth(), 0);
2196 APInt LHSKnownZero(IT->getBitWidth(), 0);
2197 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2198 if (LHSKnownZero != 0) {
2199 APInt RHSKnownOne(IT->getBitWidth(), 0);
2200 APInt RHSKnownZero(IT->getBitWidth(), 0);
2201 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2202
2203 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002204 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002205 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002206 }
2207 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002208
Nick Lewycky83598a72008-02-03 07:42:09 +00002209 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002210 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002211 Value *W, *X, *Y, *Z;
Dan Gohmancdff2122009-08-12 16:23:25 +00002212 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2213 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002214 if (W != Y) {
2215 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002216 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002217 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002218 std::swap(W, X);
2219 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002220 std::swap(Y, Z);
2221 std::swap(W, X);
2222 }
2223 }
2224
2225 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002226 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002227 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002228 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002229 }
2230 }
2231 }
2232
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002233 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2234 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002235 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002236 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237
2238 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002239 if (LHS->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00002240 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002241 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002242 if (Anded == CRHS) {
2243 // See if all bits from the first bit set in the Add RHS up are included
2244 // in the mask. First, get the rightmost bit.
2245 const APInt& AddRHSV = CRHS->getValue();
2246
2247 // Form a mask of all bits from the lowest bit added through the top.
2248 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2249
2250 // See if the and mask includes all of these bits.
2251 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2252
2253 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2254 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002255 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002256 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002257 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 }
2259 }
2260 }
2261
2262 // Try to fold constant add into select arguments.
2263 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2264 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2265 return R;
2266 }
2267
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002268 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002269 {
2270 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002271 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002272 if (!SI) {
2273 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002274 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002275 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002276 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002277 Value *TV = SI->getTrueValue();
2278 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002279 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002280
2281 // Can we fold the add into the argument of the select?
2282 // We check both true and false select arguments for a matching subtract.
Dan Gohmancdff2122009-08-12 16:23:25 +00002283 if (match(FV, m_Zero()) &&
2284 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002285 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002286 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohmancdff2122009-08-12 16:23:25 +00002287 if (match(TV, m_Zero()) &&
2288 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner641ea462008-11-16 04:46:19 +00002289 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002290 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002291 }
2292 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002293
Chris Lattner3554f972008-05-20 05:46:13 +00002294 // Check for (add (sext x), y), see if we can merge this into an
2295 // integer add followed by a sext.
2296 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2297 // (add (sext x), cst) --> (sext (add x, cst'))
2298 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2299 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002300 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002301 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002302 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new, smaller add.
2305 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2306 CI, "addconv");
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SExtInst(NewAdd, I.getType());
2309 }
2310 }
2311
2312 // (add (sext x), (sext y)) --> (sext (add int x, y))
2313 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2314 // Only do this if x/y have the same type, if at last one of them has a
2315 // single use (so we don't increase the number of sexts), and if the
2316 // integer add will not overflow.
2317 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320 RHSConv->getOperand(0))) {
2321 // Insert the new integer add.
2322 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0),
2324 "addconv");
2325 InsertNewInstBefore(NewAdd, I);
2326 return new SExtInst(NewAdd, I.getType());
2327 }
2328 }
2329 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002330
2331 return Changed ? &I : 0;
2332}
2333
2334Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2335 bool Changed = SimplifyCommutative(I);
2336 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2337
2338 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2339 // X + 0 --> X
2340 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002341 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002342 (I.getType())->getValueAPF()))
2343 return ReplaceInstUsesWith(I, LHS);
2344 }
2345
2346 if (isa<PHINode>(LHS))
2347 if (Instruction *NV = FoldOpIntoPhi(I))
2348 return NV;
2349 }
2350
2351 // -A + B --> B - A
2352 // -A + -B --> -(A + B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002353 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002354 return BinaryOperator::CreateFSub(RHS, LHSV);
2355
2356 // A + -B --> A - B
2357 if (!isa<Constant>(RHS))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002358 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002359 return BinaryOperator::CreateFSub(LHS, V);
2360
2361 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2362 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2363 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2364 return ReplaceInstUsesWith(I, LHS);
2365
Chris Lattner3554f972008-05-20 05:46:13 +00002366 // Check for (add double (sitofp x), y), see if we can merge this into an
2367 // integer add followed by a promotion.
2368 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2369 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2370 // ... if the constant fits in the integer value. This is useful for things
2371 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2372 // requires a constant pool load, and generally allows the add to be better
2373 // instcombined.
2374 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2375 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002376 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002377 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002378 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002379 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2380 // Insert the new integer add.
2381 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2382 CI, "addconv");
2383 InsertNewInstBefore(NewAdd, I);
2384 return new SIToFPInst(NewAdd, I.getType());
2385 }
2386 }
2387
2388 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2389 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2390 // Only do this if x/y have the same type, if at last one of them has a
2391 // single use (so we don't increase the number of int->fp conversions),
2392 // and if the integer add will not overflow.
2393 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2394 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2395 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2396 RHSConv->getOperand(0))) {
2397 // Insert the new integer add.
2398 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2399 RHSConv->getOperand(0),
2400 "addconv");
2401 InsertNewInstBefore(NewAdd, I);
2402 return new SIToFPInst(NewAdd, I.getType());
2403 }
2404 }
2405 }
2406
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002407 return Changed ? &I : 0;
2408}
2409
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002410Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2412
Dan Gohman7ce405e2009-06-04 22:49:04 +00002413 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002415
2416 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002417 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002418 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002419
2420 if (isa<UndefValue>(Op0))
2421 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2422 if (isa<UndefValue>(Op1))
2423 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2424
2425 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2426 // Replace (-1 - A) with (~A)...
2427 if (C->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00002428 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429
2430 // C - ~X == X + (1+C)
2431 Value *X = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00002432 if (match(Op1, m_Not(m_Value(X))))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002433 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434
2435 // -(X >>u 31) -> (X >>s 31)
2436 // -(X >>s 31) -> (X >>u 31)
2437 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002438 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002439 if (SI->getOpcode() == Instruction::LShr) {
2440 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2441 // Check to see if we are shifting out everything but the sign bit.
2442 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2443 SI->getType()->getPrimitiveSizeInBits()-1) {
2444 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002445 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002446 SI->getOperand(0), CU, SI->getName());
2447 }
2448 }
2449 }
2450 else if (SI->getOpcode() == Instruction::AShr) {
2451 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2452 // Check to see if we are shifting out everything but the sign bit.
2453 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2454 SI->getType()->getPrimitiveSizeInBits()-1) {
2455 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002456 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457 SI->getOperand(0), CU, SI->getName());
2458 }
2459 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002460 }
2461 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002462 }
2463
2464 // Try to fold constant sub into select arguments.
2465 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2466 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2467 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002468
2469 // C - zext(bool) -> bool ? C - 1 : C
2470 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson35b47072009-08-13 21:58:54 +00002471 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002472 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 }
2474
Owen Anderson35b47072009-08-13 21:58:54 +00002475 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002476 return BinaryOperator::CreateXor(Op0, Op1);
2477
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002479 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002480 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002481 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002482 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002484 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002485 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2487 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2488 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002489 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002490 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491 }
2492 }
2493
2494 if (Op1I->hasOneUse()) {
2495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2496 // is not used by anyone else...
2497 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002498 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499 // Swap the two operands of the subexpr...
2500 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2501 Op1I->setOperand(0, IIOp1);
2502 Op1I->setOperand(1, IIOp0);
2503
2504 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002505 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 }
2507
2508 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2509 //
2510 if (Op1I->getOpcode() == Instruction::And &&
2511 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2512 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2513
2514 Value *NewNot =
Dan Gohmancdff2122009-08-12 16:23:25 +00002515 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517 }
2518
2519 // 0 - (X sdiv C) -> (X sdiv -C)
2520 if (Op1I->getOpcode() == Instruction::SDiv)
2521 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2522 if (CSI->isZero())
2523 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002525 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002526
2527 // X - X*C --> X * (1-C)
2528 ConstantInt *C2 = 0;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002529 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002530 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002531 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002532 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002533 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002534 }
2535 }
2536 }
2537
Dan Gohman7ce405e2009-06-04 22:49:04 +00002538 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2539 if (Op0I->getOpcode() == Instruction::Add) {
2540 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2541 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2542 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2543 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2544 } else if (Op0I->getOpcode() == Instruction::Sub) {
2545 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002546 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002547 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002548 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002549 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550
2551 ConstantInt *C1;
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002552 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002554 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002555
2556 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002557 if (X == dyn_castFoldableMul(Op1, C2))
Owen Anderson02b48c32009-07-29 18:55:55 +00002558 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002559 }
2560 return 0;
2561}
2562
Dan Gohman7ce405e2009-06-04 22:49:04 +00002563Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2564 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2565
2566 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002567 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002568 return BinaryOperator::CreateFAdd(Op0, V);
2569
2570 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2571 if (Op1I->getOpcode() == Instruction::FAdd) {
2572 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002573 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00002574 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002575 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohmancdff2122009-08-12 16:23:25 +00002576 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson15b39322009-07-13 04:09:18 +00002577 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002578 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002579 }
2580
2581 return 0;
2582}
2583
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002584/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2585/// comparison only checks the sign bit. If it only checks the sign bit, set
2586/// TrueIfSigned if the result of the comparison is true when the input value is
2587/// signed.
2588static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2589 bool &TrueIfSigned) {
2590 switch (pred) {
2591 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2592 TrueIfSigned = true;
2593 return RHS->isZero();
2594 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2595 TrueIfSigned = true;
2596 return RHS->isAllOnesValue();
2597 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2598 TrueIfSigned = false;
2599 return RHS->isAllOnesValue();
2600 case ICmpInst::ICMP_UGT:
2601 // True if LHS u> RHS and RHS == high-bit-mask - 1
2602 TrueIfSigned = true;
2603 return RHS->getValue() ==
2604 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2605 case ICmpInst::ICMP_UGE:
2606 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2607 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002608 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002609 default:
2610 return false;
2611 }
2612}
2613
2614Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2615 bool Changed = SimplifyCommutative(I);
2616 Value *Op0 = I.getOperand(0);
2617
Eli Friedmane426ded2009-07-18 09:12:15 +00002618 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002619 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002620
2621 // Simplify mul instructions with a constant RHS...
2622 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2623 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2624
2625 // ((X << C1)*C2) == (X * (C2 << C1))
2626 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2627 if (SI->getOpcode() == Instruction::Shl)
2628 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002629 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002630 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002631
2632 if (CI->isZero())
2633 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2634 if (CI->equalsInt(1)) // X * 1 == X
2635 return ReplaceInstUsesWith(I, Op0);
2636 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002637 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638
2639 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2640 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002641 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002642 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002643 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002644 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002645 if (Op1->isNullValue())
2646 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002647
2648 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2649 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohmancdff2122009-08-12 16:23:25 +00002650 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002651
2652 // As above, vector X*splat(1.0) -> X in all defined cases.
2653 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002654 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2655 if (CI->equalsInt(1))
2656 return ReplaceInstUsesWith(I, Op0);
2657 }
2658 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002659 }
2660
2661 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2662 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002663 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002665 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002666 Op1, "tmp");
2667 InsertNewInstBefore(Add, I);
Owen Anderson02b48c32009-07-29 18:55:55 +00002668 Value *C1C2 = ConstantExpr::getMul(Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002670 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002671
2672 }
2673
2674 // Try to fold constant mul into select arguments.
2675 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2676 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2677 return R;
2678
2679 if (isa<PHINode>(Op0))
2680 if (Instruction *NV = FoldOpIntoPhi(I))
2681 return NV;
2682 }
2683
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002684 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2685 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002687
Nick Lewycky1c246402008-11-21 07:33:58 +00002688 // (X / Y) * Y = X - (X % Y)
2689 // (X / Y) * -Y = (X % Y) - X
2690 {
2691 Value *Op1 = I.getOperand(1);
2692 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2693 if (!BO ||
2694 (BO->getOpcode() != Instruction::UDiv &&
2695 BO->getOpcode() != Instruction::SDiv)) {
2696 Op1 = Op0;
2697 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2698 }
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002699 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky1c246402008-11-21 07:33:58 +00002700 if (BO && BO->hasOneUse() &&
2701 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2702 (BO->getOpcode() == Instruction::UDiv ||
2703 BO->getOpcode() == Instruction::SDiv)) {
2704 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2705
Dan Gohman07878902009-08-12 16:33:09 +00002706 // If the division is exact, X % Y is zero.
2707 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2708 if (SDiv->isExact()) {
2709 if (Op1BO == Op1)
2710 return ReplaceInstUsesWith(I, Op0BO);
2711 else
2712 return BinaryOperator::CreateNeg(Op0BO);
2713 }
2714
Nick Lewycky1c246402008-11-21 07:33:58 +00002715 Instruction *Rem;
2716 if (BO->getOpcode() == Instruction::UDiv)
2717 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2718 else
2719 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2720
2721 InsertNewInstBefore(Rem, I);
2722 Rem->takeName(BO);
2723
2724 if (Op1BO == Op1)
2725 return BinaryOperator::CreateSub(Op0BO, Rem);
2726 else
2727 return BinaryOperator::CreateSub(Rem, Op0BO);
2728 }
2729 }
2730
Owen Anderson35b47072009-08-13 21:58:54 +00002731 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002732 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2733
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734 // If one of the operands of the multiply is a cast from a boolean value, then
2735 // we know the bool is either zero or one, so this is a 'masking' multiply.
2736 // See if we can simplify things based on how the boolean was originally
2737 // formed.
2738 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002739 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson35b47072009-08-13 21:58:54 +00002740 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002741 BoolCast = CI;
2742 if (!BoolCast)
2743 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson35b47072009-08-13 21:58:54 +00002744 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 BoolCast = CI;
2746 if (BoolCast) {
2747 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2748 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2749 const Type *SCOpTy = SCIOp0->getType();
2750 bool TIS = false;
2751
2752 // If the icmp is true iff the sign bit of X is set, then convert this
2753 // multiply into a shift/and combination.
2754 if (isa<ConstantInt>(SCIOp1) &&
2755 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2756 TIS) {
2757 // Shift the X value right to turn it into "all signbits".
Owen Andersoneacb44d2009-07-24 23:12:02 +00002758 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002759 SCOpTy->getPrimitiveSizeInBits()-1);
2760 Value *V =
2761 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002762 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002763 BoolCast->getOperand(0)->getName()+
2764 ".mask"), I);
2765
2766 // If the multiply type is not the same as the source type, sign extend
2767 // or truncate to the multiply type.
2768 if (I.getType() != V->getType()) {
2769 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2770 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2771 Instruction::CastOps opcode =
2772 (SrcBits == DstBits ? Instruction::BitCast :
2773 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2774 V = InsertCastBefore(opcode, V, I.getType(), I);
2775 }
2776
2777 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002778 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779 }
2780 }
2781 }
2782
2783 return Changed ? &I : 0;
2784}
2785
Dan Gohman7ce405e2009-06-04 22:49:04 +00002786Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2787 bool Changed = SimplifyCommutative(I);
2788 Value *Op0 = I.getOperand(0);
2789
2790 // Simplify mul instructions with a constant RHS...
2791 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2792 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2793 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2794 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2795 if (Op1F->isExactlyValue(1.0))
2796 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2797 } else if (isa<VectorType>(Op1->getType())) {
2798 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2799 // As above, vector X*splat(1.0) -> X in all defined cases.
2800 if (Constant *Splat = Op1V->getSplatValue()) {
2801 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2802 if (F->isExactlyValue(1.0))
2803 return ReplaceInstUsesWith(I, Op0);
2804 }
2805 }
2806 }
2807
2808 // Try to fold constant mul into select arguments.
2809 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2810 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2811 return R;
2812
2813 if (isa<PHINode>(Op0))
2814 if (Instruction *NV = FoldOpIntoPhi(I))
2815 return NV;
2816 }
2817
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002818 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2819 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002820 return BinaryOperator::CreateFMul(Op0v, Op1v);
2821
2822 return Changed ? &I : 0;
2823}
2824
Chris Lattner76972db2008-07-14 00:15:52 +00002825/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2826/// instruction.
2827bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2828 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2829
2830 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2831 int NonNullOperand = -1;
2832 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2833 if (ST->isNullValue())
2834 NonNullOperand = 2;
2835 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2836 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2837 if (ST->isNullValue())
2838 NonNullOperand = 1;
2839
2840 if (NonNullOperand == -1)
2841 return false;
2842
2843 Value *SelectCond = SI->getOperand(0);
2844
2845 // Change the div/rem to use 'Y' instead of the select.
2846 I.setOperand(1, SI->getOperand(NonNullOperand));
2847
2848 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2849 // problem. However, the select, or the condition of the select may have
2850 // multiple uses. Based on our knowledge that the operand must be non-zero,
2851 // propagate the known value for the select into other uses of it, and
2852 // propagate a known value of the condition into its other users.
2853
2854 // If the select and condition only have a single use, don't bother with this,
2855 // early exit.
2856 if (SI->use_empty() && SelectCond->hasOneUse())
2857 return true;
2858
2859 // Scan the current block backward, looking for other uses of SI.
2860 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2861
2862 while (BBI != BBFront) {
2863 --BBI;
2864 // If we found a call to a function, we can't assume it will return, so
2865 // information from below it cannot be propagated above it.
2866 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2867 break;
2868
2869 // Replace uses of the select or its condition with the known values.
2870 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2871 I != E; ++I) {
2872 if (*I == SI) {
2873 *I = SI->getOperand(NonNullOperand);
2874 AddToWorkList(BBI);
2875 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002876 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2877 ConstantInt::getFalse(*Context);
Chris Lattner76972db2008-07-14 00:15:52 +00002878 AddToWorkList(BBI);
2879 }
2880 }
2881
2882 // If we past the instruction, quit looking for it.
2883 if (&*BBI == SI)
2884 SI = 0;
2885 if (&*BBI == SelectCond)
2886 SelectCond = 0;
2887
2888 // If we ran out of things to eliminate, break out of the loop.
2889 if (SelectCond == 0 && SI == 0)
2890 break;
2891
2892 }
2893 return true;
2894}
2895
2896
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002897/// This function implements the transforms on div instructions that work
2898/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2899/// used by the visitors to those instructions.
2900/// @brief Transforms common to all three div instructions
2901Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
Chris Lattner653ef3c2008-02-19 06:12:18 +00002904 // undef / X -> 0 for integer.
2905 // undef / X -> undef for FP (the undef could be a snan).
2906 if (isa<UndefValue>(Op0)) {
2907 if (Op0->getType()->isFPOrFPVector())
2908 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002909 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002910 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911
2912 // X / undef -> undef
2913 if (isa<UndefValue>(Op1))
2914 return ReplaceInstUsesWith(I, Op1);
2915
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916 return 0;
2917}
2918
2919/// This function implements the transforms common to both integer division
2920/// instructions (udiv and sdiv). It is called by the visitors to those integer
2921/// division instructions.
2922/// @brief Common integer divide transforms
2923Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2924 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2925
Chris Lattnercefb36c2008-05-16 02:59:42 +00002926 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002927 if (Op0 == Op1) {
2928 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002929 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002930 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002931 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002932 }
2933
Owen Andersoneacb44d2009-07-24 23:12:02 +00002934 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002935 return ReplaceInstUsesWith(I, CI);
2936 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002937
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002938 if (Instruction *Common = commonDivTransforms(I))
2939 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002940
2941 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2942 // This does not apply for fdiv.
2943 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2944 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002945
2946 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2947 // div X, 1 == X
2948 if (RHS->equalsInt(1))
2949 return ReplaceInstUsesWith(I, Op0);
2950
2951 // (X / C1) / C2 -> X / (C1*C2)
2952 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2953 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2954 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002955 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00002956 I.getOpcode()==Instruction::SDiv))
Owen Andersonaac28372009-07-31 20:28:14 +00002957 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002958 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002959 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002960 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002961 }
2962
2963 if (!RHS->isZero()) { // avoid X udiv 0
2964 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2965 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2966 return R;
2967 if (isa<PHINode>(Op0))
2968 if (Instruction *NV = FoldOpIntoPhi(I))
2969 return NV;
2970 }
2971 }
2972
2973 // 0 / X == 0, we don't need to preserve faults!
2974 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2975 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00002976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002978 // It can't be division by zero, hence it must be division by one.
Owen Anderson35b47072009-08-13 21:58:54 +00002979 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002980 return ReplaceInstUsesWith(I, Op0);
2981
Nick Lewycky94418732008-11-27 20:21:08 +00002982 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2983 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2984 // div X, 1 == X
2985 if (X->isOne())
2986 return ReplaceInstUsesWith(I, Op0);
2987 }
2988
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989 return 0;
2990}
2991
2992Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2994
2995 // Handle the integer div common cases
2996 if (Instruction *Common = commonIDivTransforms(I))
2997 return Common;
2998
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002999 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003000 // X udiv C^2 -> X >> C
3001 // Check to see if this is an unsigned division with an exact power of 2,
3002 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003004 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003005 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003006
3007 // X udiv C, where C >= signbit
3008 if (C->getValue().isNegative()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00003009 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky240182a2008-11-27 22:41:10 +00003010 I);
Owen Andersonaac28372009-07-31 20:28:14 +00003011 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003012 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003014 }
3015
3016 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3017 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3018 if (RHSI->getOpcode() == Instruction::Shl &&
3019 isa<ConstantInt>(RHSI->getOperand(0))) {
3020 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3021 if (C1.isPowerOf2()) {
3022 Value *N = RHSI->getOperand(1);
3023 const Type *NTy = N->getType();
3024 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003025 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003026 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003028 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 }
3030 }
3031 }
3032
3033 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3034 // where C1&C2 are powers of two.
3035 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3036 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3037 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3038 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3039 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3040 // Compute the shift amounts
3041 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3042 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003043 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003044 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003045 Op0, TC, SI->getName()+".t");
3046 TSI = InsertNewInstBefore(TSI, I);
3047
3048 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003049 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003050 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 Op0, FC, SI->getName()+".f");
3052 FSI = InsertNewInstBefore(FSI, I);
3053
3054 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003055 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003056 }
3057 }
3058 return 0;
3059}
3060
3061Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3063
3064 // Handle the integer div common cases
3065 if (Instruction *Common = commonIDivTransforms(I))
3066 return Common;
3067
3068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3069 // sdiv X, -1 == -X
3070 if (RHS->isAllOnesValue())
Dan Gohmancdff2122009-08-12 16:23:25 +00003071 return BinaryOperator::CreateNeg(Op0);
Dan Gohman31b6b132009-08-11 20:47:47 +00003072
Dan Gohman07878902009-08-12 16:33:09 +00003073 // sdiv X, C --> ashr X, log2(C)
Dan Gohman31b6b132009-08-11 20:47:47 +00003074 if (cast<SDivOperator>(&I)->isExact() &&
3075 RHS->getValue().isNonNegative() &&
3076 RHS->getValue().isPowerOf2()) {
3077 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3078 RHS->getValue().exactLogBase2());
3079 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3080 }
Dan Gohman5ce93b32009-08-12 16:37:02 +00003081
3082 // -X/C --> X/-C provided the negation doesn't overflow.
3083 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3084 if (isa<Constant>(Sub->getOperand(0)) &&
3085 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohmanb5ed4492009-08-20 17:11:38 +00003086 Sub->hasNoSignedWrap())
Dan Gohman5ce93b32009-08-12 16:37:02 +00003087 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3088 ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 }
3090
3091 // If the sign bits of both operands are zero (i.e. we can prove they are
3092 // unsigned inputs), turn this into a udiv.
3093 if (I.getType()->isInteger()) {
3094 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003095 if (MaskedValueIsZero(Op0, Mask)) {
3096 if (MaskedValueIsZero(Op1, Mask)) {
3097 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3098 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3099 }
3100 ConstantInt *ShiftedInt;
Dan Gohmancdff2122009-08-12 16:23:25 +00003101 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedmana17b85f2009-07-18 09:53:21 +00003102 ShiftedInt->getValue().isPowerOf2()) {
3103 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3104 // Safe because the only negative value (1 << Y) can take on is
3105 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3106 // the sign bit set.
3107 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3108 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003110 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003111
3112 return 0;
3113}
3114
3115Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3116 return commonDivTransforms(I);
3117}
3118
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003119/// This function implements the transforms on rem instructions that work
3120/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3121/// is used by the visitors to those instructions.
3122/// @brief Transforms common to all three rem instructions
3123Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3125
Chris Lattner653ef3c2008-02-19 06:12:18 +00003126 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3127 if (I.getType()->isFPOrFPVector())
3128 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003129 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003130 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131 if (isa<UndefValue>(Op1))
3132 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3133
3134 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003135 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3136 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137
3138 return 0;
3139}
3140
3141/// This function implements the transforms common to both integer remainder
3142/// instructions (urem and srem). It is called by the visitors to those integer
3143/// remainder instructions.
3144/// @brief Common integer remainder transforms
3145Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3146 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3147
3148 if (Instruction *common = commonRemTransforms(I))
3149 return common;
3150
Dale Johannesena51f7372009-01-21 00:35:19 +00003151 // 0 % X == 0 for integer, we don't need to preserve faults!
3152 if (Constant *LHS = dyn_cast<Constant>(Op0))
3153 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003155
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3157 // X % 0 == undef, we don't need to preserve faults!
3158 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003159 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160
3161 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003162 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003163
3164 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3166 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3167 return R;
3168 } else if (isa<PHINode>(Op0I)) {
3169 if (Instruction *NV = FoldOpIntoPhi(I))
3170 return NV;
3171 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003172
3173 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003174 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003175 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176 }
3177 }
3178
3179 return 0;
3180}
3181
3182Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3183 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3184
3185 if (Instruction *common = commonIRemTransforms(I))
3186 return common;
3187
3188 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3189 // X urem C^2 -> X and C
3190 // Check to see if this is an unsigned remainder with an exact power of 2,
3191 // if so, convert to a bitwise and.
3192 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3193 if (C->getValue().isPowerOf2())
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003194 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195 }
3196
3197 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3198 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3199 if (RHSI->getOpcode() == Instruction::Shl &&
3200 isa<ConstantInt>(RHSI->getOperand(0))) {
3201 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003202 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003203 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003205 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003206 }
3207 }
3208 }
3209
3210 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3211 // where C1&C2 are powers of two.
3212 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3213 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3214 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3215 // STO == 0 and SFO == 0 handled above.
3216 if ((STO->getValue().isPowerOf2()) &&
3217 (SFO->getValue().isPowerOf2())) {
3218 Value *TrueAnd = InsertNewInstBefore(
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003219 BinaryOperator::CreateAnd(Op0, SubOne(STO),
Owen Anderson24be4c12009-07-03 00:17:18 +00003220 SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 Value *FalseAnd = InsertNewInstBefore(
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003222 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
Owen Anderson24be4c12009-07-03 00:17:18 +00003223 SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003224 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003225 }
3226 }
3227 }
3228
3229 return 0;
3230}
3231
3232Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3233 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3234
Dan Gohmandb3dd962007-11-05 23:16:33 +00003235 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003236 if (Instruction *common = commonIRemTransforms(I))
3237 return common;
3238
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003239 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003240 if (!isa<Constant>(RHSNeg) ||
3241 (isa<ConstantInt>(RHSNeg) &&
3242 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003243 // X % -Y -> X % Y
3244 AddUsesToWorkList(I);
3245 I.setOperand(1, RHSNeg);
3246 return &I;
3247 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003248
Dan Gohmandb3dd962007-11-05 23:16:33 +00003249 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003250 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003251 if (I.getType()->isInteger()) {
3252 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3253 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3254 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003255 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003256 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003257 }
3258
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003259 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003260 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3261 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003262
Nick Lewyckyfd746832008-12-20 16:48:00 +00003263 bool hasNegative = false;
3264 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3265 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3266 if (RHS->getValue().isNegative())
3267 hasNegative = true;
3268
3269 if (hasNegative) {
3270 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003271 for (unsigned i = 0; i != VWidth; ++i) {
3272 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3273 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003274 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003275 else
3276 Elts[i] = RHS;
3277 }
3278 }
3279
Owen Anderson2f422e02009-07-28 21:19:26 +00003280 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003281 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003282 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003283 I.setOperand(1, NewRHSV);
3284 return &I;
3285 }
3286 }
3287 }
3288
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003289 return 0;
3290}
3291
3292Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3293 return commonRemTransforms(I);
3294}
3295
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296// isOneBitSet - Return true if there is exactly one bit set in the specified
3297// constant.
3298static bool isOneBitSet(const ConstantInt *CI) {
3299 return CI->getValue().isPowerOf2();
3300}
3301
3302// isHighOnes - Return true if the constant is of the form 1+0+.
3303// This is the same as lowones(~X).
3304static bool isHighOnes(const ConstantInt *CI) {
3305 return (~CI->getValue() + 1).isPowerOf2();
3306}
3307
3308/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3309/// are carefully arranged to allow folding of expressions such as:
3310///
3311/// (A < B) | (A > B) --> (A != B)
3312///
3313/// Note that this is only valid if the first and second predicates have the
3314/// same sign. Is illegal to do: (A u< B) | (A s> B)
3315///
3316/// Three bits are used to represent the condition, as follows:
3317/// 0 A > B
3318/// 1 A == B
3319/// 2 A < B
3320///
3321/// <=> Value Definition
3322/// 000 0 Always false
3323/// 001 1 A > B
3324/// 010 2 A == B
3325/// 011 3 A >= B
3326/// 100 4 A < B
3327/// 101 5 A != B
3328/// 110 6 A <= B
3329/// 111 7 Always true
3330///
3331static unsigned getICmpCode(const ICmpInst *ICI) {
3332 switch (ICI->getPredicate()) {
3333 // False -> 0
3334 case ICmpInst::ICMP_UGT: return 1; // 001
3335 case ICmpInst::ICMP_SGT: return 1; // 001
3336 case ICmpInst::ICMP_EQ: return 2; // 010
3337 case ICmpInst::ICMP_UGE: return 3; // 011
3338 case ICmpInst::ICMP_SGE: return 3; // 011
3339 case ICmpInst::ICMP_ULT: return 4; // 100
3340 case ICmpInst::ICMP_SLT: return 4; // 100
3341 case ICmpInst::ICMP_NE: return 5; // 101
3342 case ICmpInst::ICMP_ULE: return 6; // 110
3343 case ICmpInst::ICMP_SLE: return 6; // 110
3344 // True -> 7
3345 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003346 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003347 return 0;
3348 }
3349}
3350
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003351/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3352/// predicate into a three bit mask. It also returns whether it is an ordered
3353/// predicate by reference.
3354static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3355 isOrdered = false;
3356 switch (CC) {
3357 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3358 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003359 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3360 case FCmpInst::FCMP_UGT: return 1; // 001
3361 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3362 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003363 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3364 case FCmpInst::FCMP_UGE: return 3; // 011
3365 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3366 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003367 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3368 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003369 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3370 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003371 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003372 default:
3373 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003374 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003375 return 0;
3376 }
3377}
3378
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003379/// getICmpValue - This is the complement of getICmpCode, which turns an
3380/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003381/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003382/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003383static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003384 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003385 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003386 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003387 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003388 case 1:
3389 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003390 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003392 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3393 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003394 case 3:
3395 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003396 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003397 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003398 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003399 case 4:
3400 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003401 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003403 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3404 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 case 6:
3406 if (sign)
Dan Gohmane6803b82009-08-25 23:17:54 +00003407 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003408 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003409 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003410 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 }
3412}
3413
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003414/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3415/// opcode and two operands into either a FCmp instruction. isordered is passed
3416/// in to determine which kind of predicate to use in the new fcmp instruction.
3417static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003418 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003419 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003420 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003421 case 0:
3422 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003423 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003424 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003425 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003426 case 1:
3427 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003428 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003429 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003430 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003431 case 2:
3432 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003433 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003434 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003435 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003436 case 3:
3437 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003438 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003439 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003440 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003441 case 4:
3442 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003443 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003444 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003445 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003446 case 5:
3447 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003448 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003449 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003450 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003451 case 6:
3452 if (isordered)
Dan Gohmane6803b82009-08-25 23:17:54 +00003453 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003454 else
Dan Gohmane6803b82009-08-25 23:17:54 +00003455 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003456 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003457 }
3458}
3459
Chris Lattner2972b822008-11-16 04:55:20 +00003460/// PredicatesFoldable - Return true if both predicates match sign or if at
3461/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003462static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3463 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003464 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3465 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003466}
3467
3468namespace {
3469// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3470struct FoldICmpLogical {
3471 InstCombiner &IC;
3472 Value *LHS, *RHS;
3473 ICmpInst::Predicate pred;
3474 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3475 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3476 pred(ICI->getPredicate()) {}
3477 bool shouldApply(Value *V) const {
3478 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3479 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003480 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3481 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003482 return false;
3483 }
3484 Instruction *apply(Instruction &Log) const {
3485 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3486 if (ICI->getOperand(0) != LHS) {
3487 assert(ICI->getOperand(1) == LHS);
3488 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3489 }
3490
3491 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3492 unsigned LHSCode = getICmpCode(ICI);
3493 unsigned RHSCode = getICmpCode(RHSICI);
3494 unsigned Code;
3495 switch (Log.getOpcode()) {
3496 case Instruction::And: Code = LHSCode & RHSCode; break;
3497 case Instruction::Or: Code = LHSCode | RHSCode; break;
3498 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003499 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500 }
3501
3502 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3503 ICmpInst::isSignedPredicate(ICI->getPredicate());
3504
Owen Anderson24be4c12009-07-03 00:17:18 +00003505 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 if (Instruction *I = dyn_cast<Instruction>(RV))
3507 return I;
3508 // Otherwise, it's a constant boolean value...
3509 return IC.ReplaceInstUsesWith(Log, RV);
3510 }
3511};
3512} // end anonymous namespace
3513
3514// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3515// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3516// guaranteed to be a binary operator.
3517Instruction *InstCombiner::OptAndOp(Instruction *Op,
3518 ConstantInt *OpRHS,
3519 ConstantInt *AndRHS,
3520 BinaryOperator &TheAnd) {
3521 Value *X = Op->getOperand(0);
3522 Constant *Together = 0;
3523 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003524 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003525
3526 switch (Op->getOpcode()) {
3527 case Instruction::Xor:
3528 if (Op->hasOneUse()) {
3529 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003530 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003531 InsertNewInstBefore(And, TheAnd);
3532 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003533 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 }
3535 break;
3536 case Instruction::Or:
3537 if (Together == AndRHS) // (X | C) & C --> C
3538 return ReplaceInstUsesWith(TheAnd, AndRHS);
3539
3540 if (Op->hasOneUse() && Together != OpRHS) {
3541 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003542 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543 InsertNewInstBefore(Or, TheAnd);
3544 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003545 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546 }
3547 break;
3548 case Instruction::Add:
3549 if (Op->hasOneUse()) {
3550 // Adding a one to a single bit bit-field should be turned into an XOR
3551 // of the bit. First thing to check is to see if this AND is with a
3552 // single bit constant.
3553 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3554
3555 // If there is only one bit set...
3556 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3557 // Ok, at this point, we know that we are masking the result of the
3558 // ADD down to exactly one bit. If the constant we are adding has
3559 // no bits set below this bit, then we can eliminate the ADD.
3560 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3561
3562 // Check to see if any bits below the one bit set in AndRHSV are set.
3563 if ((AddRHS & (AndRHSV-1)) == 0) {
3564 // If not, the only thing that can effect the output of the AND is
3565 // the bit specified by AndRHSV. If that bit is set, the effect of
3566 // the XOR is to toggle the bit. If it is clear, then the ADD has
3567 // no effect.
3568 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3569 TheAnd.setOperand(0, X);
3570 return &TheAnd;
3571 } else {
3572 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003573 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003574 InsertNewInstBefore(NewAnd, TheAnd);
3575 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003576 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577 }
3578 }
3579 }
3580 }
3581 break;
3582
3583 case Instruction::Shl: {
3584 // We know that the AND will not produce any of the bits shifted in, so if
3585 // the anded constant includes them, clear them now!
3586 //
3587 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3588 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3589 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003590 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003591
3592 if (CI->getValue() == ShlMask) {
3593 // Masking out bits that the shift already masks
3594 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3595 } else if (CI != AndRHS) { // Reducing bits set in and.
3596 TheAnd.setOperand(1, CI);
3597 return &TheAnd;
3598 }
3599 break;
3600 }
3601 case Instruction::LShr:
3602 {
3603 // We know that the AND will not produce any of the bits shifted in, so if
3604 // the anded constant includes them, clear them now! This only applies to
3605 // unsigned shifts, because a signed shr may bring in set bits!
3606 //
3607 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3608 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3609 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003610 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003611
3612 if (CI->getValue() == ShrMask) {
3613 // Masking out bits that the shift already masks.
3614 return ReplaceInstUsesWith(TheAnd, Op);
3615 } else if (CI != AndRHS) {
3616 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3617 return &TheAnd;
3618 }
3619 break;
3620 }
3621 case Instruction::AShr:
3622 // Signed shr.
3623 // See if this is shifting in some sign extension, then masking it out
3624 // with an and.
3625 if (Op->hasOneUse()) {
3626 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3627 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3628 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003629 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003630 if (C == AndRHS) { // Masking out bits shifted in.
3631 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3632 // Make the argument unsigned.
3633 Value *ShVal = Op->getOperand(0);
3634 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003635 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003636 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003637 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003638 }
3639 }
3640 break;
3641 }
3642 return 0;
3643}
3644
3645
3646/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3647/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3648/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3649/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3650/// insert new instructions.
3651Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3652 bool isSigned, bool Inside,
3653 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003654 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3656 "Lo is not <= Hi in range emission code!");
3657
3658 if (Inside) {
3659 if (Lo == Hi) // Trivially false.
Dan Gohmane6803b82009-08-25 23:17:54 +00003660 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003661
3662 // V >= Min && V < Hi --> V < Hi
3663 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3664 ICmpInst::Predicate pred = (isSigned ?
3665 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003666 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003667 }
3668
3669 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003670 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003671 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003672 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003673 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003674 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003675 }
3676
3677 if (Lo == Hi) // Trivially true.
Dan Gohmane6803b82009-08-25 23:17:54 +00003678 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003679
3680 // V < Min || V >= Hi -> V > Hi-1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003681 Hi = SubOne(cast<ConstantInt>(Hi));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003682 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3683 ICmpInst::Predicate pred = (isSigned ?
3684 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohmane6803b82009-08-25 23:17:54 +00003685 return new ICmpInst(pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686 }
3687
3688 // Emit V-Lo >u Hi-1-Lo
3689 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003690 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003691 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003693 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohmane6803b82009-08-25 23:17:54 +00003694 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695}
3696
3697// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3698// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3699// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3700// not, since all 1s are not contiguous.
3701static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3702 const APInt& V = Val->getValue();
3703 uint32_t BitWidth = Val->getType()->getBitWidth();
3704 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3705
3706 // look for the first zero bit after the run of ones
3707 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3708 // look for the first non-zero bit
3709 ME = V.getActiveBits();
3710 return true;
3711}
3712
3713/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3714/// where isSub determines whether the operator is a sub. If we can fold one of
3715/// the following xforms:
3716///
3717/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3718/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3719/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3720///
3721/// return (A +/- B).
3722///
3723Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3724 ConstantInt *Mask, bool isSub,
3725 Instruction &I) {
3726 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3727 if (!LHSI || LHSI->getNumOperands() != 2 ||
3728 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3729
3730 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3731
3732 switch (LHSI->getOpcode()) {
3733 default: return 0;
3734 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003735 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3737 if ((Mask->getValue().countLeadingZeros() +
3738 Mask->getValue().countPopulation()) ==
3739 Mask->getValue().getBitWidth())
3740 break;
3741
3742 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3743 // part, we don't need any explicit masks to take them out of A. If that
3744 // is all N is, ignore it.
3745 uint32_t MB = 0, ME = 0;
3746 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3747 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3748 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3749 if (MaskedValueIsZero(RHS, Mask))
3750 break;
3751 }
3752 }
3753 return 0;
3754 case Instruction::Or:
3755 case Instruction::Xor:
3756 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3757 if ((Mask->getValue().countLeadingZeros() +
3758 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003759 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003760 break;
3761 return 0;
3762 }
3763
3764 Instruction *New;
3765 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003766 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003767 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003768 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 return InsertNewInstBefore(New, I);
3770}
3771
Chris Lattner0631ea72008-11-16 05:06:21 +00003772/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3773Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3774 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003775 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003776 ConstantInt *LHSCst, *RHSCst;
3777 ICmpInst::Predicate LHSCC, RHSCC;
3778
Chris Lattnerf3803482008-11-16 05:10:52 +00003779 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003780 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00003781 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00003782 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00003783 m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003784 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003785
3786 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3787 // where C is a power of 2
3788 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3789 LHSCst->getValue().isPowerOf2()) {
3790 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3791 InsertNewInstBefore(NewOr, I);
Dan Gohmane6803b82009-08-25 23:17:54 +00003792 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003793 }
3794
3795 // From here on, we only handle:
3796 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3797 if (Val != Val2) return 0;
3798
Chris Lattner0631ea72008-11-16 05:06:21 +00003799 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3800 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3801 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3802 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3803 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3804 return 0;
3805
3806 // We can't fold (ugt x, C) & (sgt x, C2).
3807 if (!PredicatesFoldable(LHSCC, RHSCC))
3808 return 0;
3809
3810 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003811 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003812 if (ICmpInst::isSignedPredicate(LHSCC) ||
3813 (ICmpInst::isEquality(LHSCC) &&
3814 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003815 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003816 else
Chris Lattner665298f2008-11-16 05:14:43 +00003817 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3818
3819 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003820 std::swap(LHS, RHS);
3821 std::swap(LHSCst, RHSCst);
3822 std::swap(LHSCC, RHSCC);
3823 }
3824
3825 // At this point, we know we have have two icmp instructions
3826 // comparing a value against two constants and and'ing the result
3827 // together. Because of the above check, we know that we only have
3828 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3829 // (from the FoldICmpLogical check above), that the two constants
3830 // are not equal and that the larger constant is on the RHS
3831 assert(LHSCst != RHSCst && "Compares not folded above?");
3832
3833 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003834 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003835 case ICmpInst::ICMP_EQ:
3836 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003837 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003838 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3839 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3840 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003841 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003842 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3843 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3844 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3845 return ReplaceInstUsesWith(I, LHS);
3846 }
3847 case ICmpInst::ICMP_NE:
3848 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003849 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003850 case ICmpInst::ICMP_ULT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003851 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003852 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003853 break; // (X != 13 & X u< 15) -> no change
3854 case ICmpInst::ICMP_SLT:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003855 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohmane6803b82009-08-25 23:17:54 +00003856 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003857 break; // (X != 13 & X s< 15) -> no change
3858 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3859 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3860 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3861 return ReplaceInstUsesWith(I, RHS);
3862 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003863 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003864 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003865 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3866 Val->getName()+".off");
3867 InsertNewInstBefore(Add, I);
Dan Gohmane6803b82009-08-25 23:17:54 +00003868 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003869 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003870 }
3871 break; // (X != 13 & X != 15) -> no change
3872 }
3873 break;
3874 case ICmpInst::ICMP_ULT:
3875 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003876 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003877 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3878 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003879 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3881 break;
3882 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3883 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3884 return ReplaceInstUsesWith(I, LHS);
3885 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3886 break;
3887 }
3888 break;
3889 case ICmpInst::ICMP_SLT:
3890 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003891 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003892 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3893 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003894 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003895 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3896 break;
3897 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3898 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3899 return ReplaceInstUsesWith(I, LHS);
3900 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3901 break;
3902 }
3903 break;
3904 case ICmpInst::ICMP_UGT:
3905 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003906 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003907 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3908 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3909 return ReplaceInstUsesWith(I, RHS);
3910 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3911 break;
3912 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003913 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003914 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003915 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003916 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003917 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003918 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003919 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3920 break;
3921 }
3922 break;
3923 case ICmpInst::ICMP_SGT:
3924 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003925 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003926 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3927 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3928 return ReplaceInstUsesWith(I, RHS);
3929 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3930 break;
3931 case ICmpInst::ICMP_NE:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003932 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohmane6803b82009-08-25 23:17:54 +00003933 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003934 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003935 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohmanfe91cd62009-08-12 16:04:34 +00003936 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00003937 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003938 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3939 break;
3940 }
3941 break;
3942 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003943
3944 return 0;
3945}
3946
Chris Lattner93a359a2009-07-23 05:14:02 +00003947Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3948 FCmpInst *RHS) {
3949
3950 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3951 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3952 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3953 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3954 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3955 // If either of the constants are nans, then the whole thing returns
3956 // false.
3957 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003958 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmane6803b82009-08-25 23:17:54 +00003959 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner93a359a2009-07-23 05:14:02 +00003960 LHS->getOperand(0), RHS->getOperand(0));
3961 }
Chris Lattnercf373552009-07-23 05:32:17 +00003962
3963 // Handle vector zeros. This occurs because the canonical form of
3964 // "fcmp ord x,x" is "fcmp ord x, 0".
3965 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3966 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00003967 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnercf373552009-07-23 05:32:17 +00003968 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003969 return 0;
3970 }
3971
3972 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3973 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3974 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3975
3976
3977 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3978 // Swap RHS operands to match LHS.
3979 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3980 std::swap(Op1LHS, Op1RHS);
3981 }
3982
3983 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3984 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3985 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00003986 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +00003987
3988 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003989 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003990 if (Op0CC == FCmpInst::FCMP_TRUE)
3991 return ReplaceInstUsesWith(I, RHS);
3992 if (Op1CC == FCmpInst::FCMP_TRUE)
3993 return ReplaceInstUsesWith(I, LHS);
3994
3995 bool Op0Ordered;
3996 bool Op1Ordered;
3997 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3998 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3999 if (Op1Pred == 0) {
4000 std::swap(LHS, RHS);
4001 std::swap(Op0Pred, Op1Pred);
4002 std::swap(Op0Ordered, Op1Ordered);
4003 }
4004 if (Op0Pred == 0) {
4005 // uno && ueq -> uno && (uno || eq) -> ueq
4006 // ord && olt -> ord && (ord && lt) -> olt
4007 if (Op0Ordered == Op1Ordered)
4008 return ReplaceInstUsesWith(I, RHS);
4009
4010 // uno && oeq -> uno && (ord && eq) -> false
4011 // uno && ord -> false
4012 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004013 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00004014 // ord && ueq -> ord && (uno || eq) -> oeq
4015 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4016 Op0LHS, Op0RHS, Context));
4017 }
4018 }
4019
4020 return 0;
4021}
4022
Chris Lattner0631ea72008-11-16 05:06:21 +00004023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004024Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4025 bool Changed = SimplifyCommutative(I);
4026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4027
4028 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004029 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004030
4031 // and X, X = X
4032 if (Op0 == Op1)
4033 return ReplaceInstUsesWith(I, Op1);
4034
4035 // See if we can simplify any instructions used by the instruction whose sole
4036 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004037 if (SimplifyDemandedInstructionBits(I))
4038 return &I;
4039 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004040 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4041 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4042 return ReplaceInstUsesWith(I, I.getOperand(0));
4043 } else if (isa<ConstantAggregateZero>(Op1)) {
4044 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4045 }
4046 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004047
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004048 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4049 const APInt& AndRHSMask = AndRHS->getValue();
4050 APInt NotAndRHS(~AndRHSMask);
4051
4052 // Optimize a variety of ((val OP C1) & C2) combinations...
4053 if (isa<BinaryOperator>(Op0)) {
4054 Instruction *Op0I = cast<Instruction>(Op0);
4055 Value *Op0LHS = Op0I->getOperand(0);
4056 Value *Op0RHS = Op0I->getOperand(1);
4057 switch (Op0I->getOpcode()) {
4058 case Instruction::Xor:
4059 case Instruction::Or:
4060 // If the mask is only needed on one incoming arm, push it up.
4061 if (Op0I->hasOneUse()) {
4062 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4063 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004064 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004065 Op0RHS->getName()+".masked");
4066 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004067 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004068 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4069 }
4070 if (!isa<Constant>(Op0RHS) &&
4071 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4072 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004073 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004074 Op0LHS->getName()+".masked");
4075 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004076 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004077 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4078 }
4079 }
4080
4081 break;
4082 case Instruction::Add:
4083 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4084 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4085 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004087 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004088 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004089 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 break;
4091
4092 case Instruction::Sub:
4093 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4094 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4095 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004097 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004098
Nick Lewyckya349ba42008-07-10 05:51:40 +00004099 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4100 // has 1's for all bits that the subtraction with A might affect.
4101 if (Op0I->hasOneUse()) {
4102 uint32_t BitWidth = AndRHSMask.getBitWidth();
4103 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4104 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4105
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004106 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004107 if (!(A && A->isZero()) && // avoid infinite recursion.
4108 MaskedValueIsZero(Op0LHS, Mask)) {
Dan Gohmancdff2122009-08-12 16:23:25 +00004109 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004110 InsertNewInstBefore(NewNeg, I);
4111 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4112 }
4113 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004114 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004115
4116 case Instruction::Shl:
4117 case Instruction::LShr:
4118 // (1 << x) & 1 --> zext(x == 0)
4119 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004120 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Dan Gohmane6803b82009-08-25 23:17:54 +00004121 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00004122 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004123 InsertNewInstBefore(NewICmp, I);
4124 return new ZExtInst(NewICmp, I.getType());
4125 }
4126 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004127 }
4128
4129 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4130 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4131 return Res;
4132 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4133 // If this is an integer truncation or change from signed-to-unsigned, and
4134 // if the source is an and/or with immediate, transform it. This
4135 // frequently occurs for bitfield accesses.
4136 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4137 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4138 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004139 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004140 if (CastOp->getOpcode() == Instruction::And) {
4141 // Change: and (cast (and X, C1) to T), C2
4142 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4143 // This will fold the two constants together, which may allow
4144 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004145 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146 CastOp->getOperand(0), I.getType(),
4147 CastOp->getName()+".shrunk");
4148 NewCast = InsertNewInstBefore(NewCast, I);
4149 // trunc_or_bitcast(C1)&C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004150 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004151 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4152 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004153 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004154 } else if (CastOp->getOpcode() == Instruction::Or) {
4155 // Change: and (cast (or X, C1) to T), C2
4156 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004157 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004158 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4159 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004160 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004161 return ReplaceInstUsesWith(I, AndRHS);
4162 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004163 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004164 }
4165 }
4166
4167 // Try to fold constant and into select arguments.
4168 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4169 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4170 return R;
4171 if (isa<PHINode>(Op0))
4172 if (Instruction *NV = FoldOpIntoPhi(I))
4173 return NV;
4174 }
4175
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004176 Value *Op0NotVal = dyn_castNotVal(Op0);
4177 Value *Op1NotVal = dyn_castNotVal(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004178
4179 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004180 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004181
4182 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4183 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004184 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 I.getName()+".demorgan");
4186 InsertNewInstBefore(Or, I);
Dan Gohmancdff2122009-08-12 16:23:25 +00004187 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004188 }
4189
4190 {
4191 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004192 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4194 return ReplaceInstUsesWith(I, Op1);
4195
4196 // (A|B) & ~(A&B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004197 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004198 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004199 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004200 }
4201 }
4202
Dan Gohmancdff2122009-08-12 16:23:25 +00004203 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004204 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4205 return ReplaceInstUsesWith(I, Op0);
4206
4207 // ~(A&B) & (A|B) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004208 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004209 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004210 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004211 }
4212 }
4213
4214 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004215 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004216 if (A == Op1) { // (A^B)&A -> A&(A^B)
4217 I.swapOperands(); // Simplify below
4218 std::swap(Op0, Op1);
4219 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4220 cast<BinaryOperator>(Op0)->swapOperands();
4221 I.swapOperands(); // Simplify below
4222 std::swap(Op0, Op1);
4223 }
4224 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004225
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004226 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004227 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004228 if (B == Op0) { // B&(A^B) -> B&(B^A)
4229 cast<BinaryOperator>(Op1)->swapOperands();
4230 std::swap(A, B);
4231 }
4232 if (A == Op0) { // A&(A^B) -> A & ~B
Dan Gohmancdff2122009-08-12 16:23:25 +00004233 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004234 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004235 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004236 }
4237 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004238
4239 // (A&((~A)|B)) -> A&B
Dan Gohmancdff2122009-08-12 16:23:25 +00004240 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4241 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004242 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004243 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4244 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattner9db479f2008-12-01 05:16:26 +00004245 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004246 }
4247
4248 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4249 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004250 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004251 return R;
4252
Chris Lattner0631ea72008-11-16 05:06:21 +00004253 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4254 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4255 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004256 }
4257
4258 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4259 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4260 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4261 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4262 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004263 if (SrcTy == Op1C->getOperand(0)->getType() &&
4264 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004265 // Only do this if the casts both really cause code to be generated.
4266 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4267 I.getType(), TD) &&
4268 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4269 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004270 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004271 Op1C->getOperand(0),
4272 I.getName());
4273 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004274 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004275 }
4276 }
4277
4278 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4279 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4280 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4281 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4282 SI0->getOperand(1) == SI1->getOperand(1) &&
4283 (SI0->hasOneUse() || SI1->hasOneUse())) {
4284 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004285 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004286 SI1->getOperand(0),
4287 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004288 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004289 SI1->getOperand(1));
4290 }
4291 }
4292
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004293 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004294 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004295 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4296 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4297 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004298 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004299
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004300 return Changed ? &I : 0;
4301}
4302
Chris Lattner567f5112008-10-05 02:13:19 +00004303/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4304/// capable of providing pieces of a bswap. The subexpression provides pieces
4305/// of a bswap if it is proven that each of the non-zero bytes in the output of
4306/// the expression came from the corresponding "byte swapped" byte in some other
4307/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4308/// we know that the expression deposits the low byte of %X into the high byte
4309/// of the bswap result and that all other bytes are zero. This expression is
4310/// accepted, the high byte of ByteValues is set to X to indicate a correct
4311/// match.
4312///
4313/// This function returns true if the match was unsuccessful and false if so.
4314/// On entry to the function the "OverallLeftShift" is a signed integer value
4315/// indicating the number of bytes that the subexpression is later shifted. For
4316/// example, if the expression is later right shifted by 16 bits, the
4317/// OverallLeftShift value would be -2 on entry. This is used to specify which
4318/// byte of ByteValues is actually being set.
4319///
4320/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4321/// byte is masked to zero by a user. For example, in (X & 255), X will be
4322/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4323/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4324/// always in the local (OverallLeftShift) coordinate space.
4325///
4326static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4327 SmallVector<Value*, 8> &ByteValues) {
4328 if (Instruction *I = dyn_cast<Instruction>(V)) {
4329 // If this is an or instruction, it may be an inner node of the bswap.
4330 if (I->getOpcode() == Instruction::Or) {
4331 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4332 ByteValues) ||
4333 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4334 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004335 }
Chris Lattner567f5112008-10-05 02:13:19 +00004336
4337 // If this is a logical shift by a constant multiple of 8, recurse with
4338 // OverallLeftShift and ByteMask adjusted.
4339 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4340 unsigned ShAmt =
4341 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4342 // Ensure the shift amount is defined and of a byte value.
4343 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4344 return true;
4345
4346 unsigned ByteShift = ShAmt >> 3;
4347 if (I->getOpcode() == Instruction::Shl) {
4348 // X << 2 -> collect(X, +2)
4349 OverallLeftShift += ByteShift;
4350 ByteMask >>= ByteShift;
4351 } else {
4352 // X >>u 2 -> collect(X, -2)
4353 OverallLeftShift -= ByteShift;
4354 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004355 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004356 }
4357
4358 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4359 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4360
4361 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4362 ByteValues);
4363 }
4364
4365 // If this is a logical 'and' with a mask that clears bytes, clear the
4366 // corresponding bytes in ByteMask.
4367 if (I->getOpcode() == Instruction::And &&
4368 isa<ConstantInt>(I->getOperand(1))) {
4369 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4370 unsigned NumBytes = ByteValues.size();
4371 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4372 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4373
4374 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4375 // If this byte is masked out by a later operation, we don't care what
4376 // the and mask is.
4377 if ((ByteMask & (1 << i)) == 0)
4378 continue;
4379
4380 // If the AndMask is all zeros for this byte, clear the bit.
4381 APInt MaskB = AndMask & Byte;
4382 if (MaskB == 0) {
4383 ByteMask &= ~(1U << i);
4384 continue;
4385 }
4386
4387 // If the AndMask is not all ones for this byte, it's not a bytezap.
4388 if (MaskB != Byte)
4389 return true;
4390
4391 // Otherwise, this byte is kept.
4392 }
4393
4394 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4395 ByteValues);
4396 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004397 }
4398
Chris Lattner567f5112008-10-05 02:13:19 +00004399 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4400 // the input value to the bswap. Some observations: 1) if more than one byte
4401 // is demanded from this input, then it could not be successfully assembled
4402 // into a byteswap. At least one of the two bytes would not be aligned with
4403 // their ultimate destination.
4404 if (!isPowerOf2_32(ByteMask)) return true;
4405 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004406
Chris Lattner567f5112008-10-05 02:13:19 +00004407 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4408 // is demanded, it needs to go into byte 0 of the result. This means that the
4409 // byte needs to be shifted until it lands in the right byte bucket. The
4410 // shift amount depends on the position: if the byte is coming from the high
4411 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4412 // low part, it must be shifted left.
4413 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4414 if (InputByteNo < ByteValues.size()/2) {
4415 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4416 return true;
4417 } else {
4418 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4419 return true;
4420 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004421
4422 // If the destination byte value is already defined, the values are or'd
4423 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004424 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004425 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004426 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004427 return false;
4428}
4429
4430/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4431/// If so, insert the new bswap intrinsic and return it.
4432Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4433 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004434 if (!ITy || ITy->getBitWidth() % 16 ||
4435 // ByteMask only allows up to 32-byte values.
4436 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004437 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4438
4439 /// ByteValues - For each byte of the result, we keep track of which value
4440 /// defines each byte.
4441 SmallVector<Value*, 8> ByteValues;
4442 ByteValues.resize(ITy->getBitWidth()/8);
4443
4444 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004445 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4446 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 return 0;
4448
4449 // Check to see if all of the bytes come from the same value.
4450 Value *V = ByteValues[0];
4451 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4452
4453 // Check to make sure that all of the bytes come from the same value.
4454 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4455 if (ByteValues[i] != V)
4456 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004457 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004458 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004459 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004460 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004461}
4462
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004463/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4464/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4465/// we can simplify this expression to "cond ? C : D or B".
4466static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004467 Value *C, Value *D,
4468 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004469 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004470 Value *Cond = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004471 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004472 return 0;
4473
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004474 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohmancdff2122009-08-12 16:23:25 +00004475 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004476 return SelectInst::Create(Cond, C, B);
Dan Gohmancdff2122009-08-12 16:23:25 +00004477 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004478 return SelectInst::Create(Cond, C, B);
4479 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohmancdff2122009-08-12 16:23:25 +00004480 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004481 return SelectInst::Create(Cond, C, D);
Dan Gohmancdff2122009-08-12 16:23:25 +00004482 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004483 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004484 return 0;
4485}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004486
Chris Lattner0c678e52008-11-16 05:20:07 +00004487/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4488Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4489 ICmpInst *LHS, ICmpInst *RHS) {
4490 Value *Val, *Val2;
4491 ConstantInt *LHSCst, *RHSCst;
4492 ICmpInst::Predicate LHSCC, RHSCC;
4493
4494 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004495 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohmancdff2122009-08-12 16:23:25 +00004496 m_ConstantInt(LHSCst))) ||
Owen Andersona21eb582009-07-10 17:35:01 +00004497 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohmancdff2122009-08-12 16:23:25 +00004498 m_ConstantInt(RHSCst))))
Chris Lattner0c678e52008-11-16 05:20:07 +00004499 return 0;
4500
4501 // From here on, we only handle:
4502 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4503 if (Val != Val2) return 0;
4504
4505 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4506 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4507 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4508 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4509 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4510 return 0;
4511
4512 // We can't fold (ugt x, C) | (sgt x, C2).
4513 if (!PredicatesFoldable(LHSCC, RHSCC))
4514 return 0;
4515
4516 // Ensure that the larger constant is on the RHS.
4517 bool ShouldSwap;
4518 if (ICmpInst::isSignedPredicate(LHSCC) ||
4519 (ICmpInst::isEquality(LHSCC) &&
4520 ICmpInst::isSignedPredicate(RHSCC)))
4521 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4522 else
4523 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4524
4525 if (ShouldSwap) {
4526 std::swap(LHS, RHS);
4527 std::swap(LHSCst, RHSCst);
4528 std::swap(LHSCC, RHSCC);
4529 }
4530
4531 // At this point, we know we have have two icmp instructions
4532 // comparing a value against two constants and or'ing the result
4533 // together. Because of the above check, we know that we only have
4534 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4535 // FoldICmpLogical check above), that the two constants are not
4536 // equal.
4537 assert(LHSCst != RHSCst && "Compares not folded above?");
4538
4539 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004540 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004541 case ICmpInst::ICMP_EQ:
4542 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004543 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004544 case ICmpInst::ICMP_EQ:
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004545 if (LHSCst == SubOne(RHSCst)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004546 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004547 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004548 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4549 Val->getName()+".off");
4550 InsertNewInstBefore(Add, I);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004551 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohmane6803b82009-08-25 23:17:54 +00004552 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004553 }
4554 break; // (X == 13 | X == 15) -> no change
4555 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4556 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4557 break;
4558 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4559 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4560 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4561 return ReplaceInstUsesWith(I, RHS);
4562 }
4563 break;
4564 case ICmpInst::ICMP_NE:
4565 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004566 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004567 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4568 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4569 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4570 return ReplaceInstUsesWith(I, LHS);
4571 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4572 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4573 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004574 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004575 }
4576 break;
4577 case ICmpInst::ICMP_ULT:
4578 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004579 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4581 break;
4582 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4583 // If RHSCst is [us]MAXINT, it is always false. Not handling
4584 // this can cause overflow.
4585 if (RHSCst->isMaxValue(false))
4586 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004587 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004588 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004589 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4590 break;
4591 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4592 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4593 return ReplaceInstUsesWith(I, RHS);
4594 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4595 break;
4596 }
4597 break;
4598 case ICmpInst::ICMP_SLT:
4599 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004600 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004601 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4602 break;
4603 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4604 // If RHSCst is [us]MAXINT, it is always false. Not handling
4605 // this can cause overflow.
4606 if (RHSCst->isMaxValue(true))
4607 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004608 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Anderson24be4c12009-07-03 00:17:18 +00004609 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004610 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4611 break;
4612 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4613 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4614 return ReplaceInstUsesWith(I, RHS);
4615 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4616 break;
4617 }
4618 break;
4619 case ICmpInst::ICMP_UGT:
4620 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004621 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004622 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4623 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4624 return ReplaceInstUsesWith(I, LHS);
4625 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4626 break;
4627 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4628 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004629 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004630 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4631 break;
4632 }
4633 break;
4634 case ICmpInst::ICMP_SGT:
4635 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004636 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004637 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4638 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4639 return ReplaceInstUsesWith(I, LHS);
4640 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4641 break;
4642 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4643 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004644 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004645 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4646 break;
4647 }
4648 break;
4649 }
4650 return 0;
4651}
4652
Chris Lattner57e66fa2009-07-23 05:46:22 +00004653Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4654 FCmpInst *RHS) {
4655 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4656 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4657 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4658 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4659 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4660 // If either of the constants are nans, then the whole thing returns
4661 // true.
4662 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004663 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004664
4665 // Otherwise, no need to compare the two constants, compare the
4666 // rest.
Dan Gohmane6803b82009-08-25 23:17:54 +00004667 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004668 LHS->getOperand(0), RHS->getOperand(0));
4669 }
4670
4671 // Handle vector zeros. This occurs because the canonical form of
4672 // "fcmp uno x,x" is "fcmp uno x, 0".
4673 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4674 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00004675 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004676 LHS->getOperand(0), RHS->getOperand(0));
4677
4678 return 0;
4679 }
4680
4681 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4682 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4683 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4684
4685 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4686 // Swap RHS operands to match LHS.
4687 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4688 std::swap(Op1LHS, Op1RHS);
4689 }
4690 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4691 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4692 if (Op0CC == Op1CC)
Dan Gohmane6803b82009-08-25 23:17:54 +00004693 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner57e66fa2009-07-23 05:46:22 +00004694 Op0LHS, Op0RHS);
4695 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004696 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004697 if (Op0CC == FCmpInst::FCMP_FALSE)
4698 return ReplaceInstUsesWith(I, RHS);
4699 if (Op1CC == FCmpInst::FCMP_FALSE)
4700 return ReplaceInstUsesWith(I, LHS);
4701 bool Op0Ordered;
4702 bool Op1Ordered;
4703 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4704 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4705 if (Op0Ordered == Op1Ordered) {
4706 // If both are ordered or unordered, return a new fcmp with
4707 // or'ed predicates.
4708 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4709 Op0LHS, Op0RHS, Context);
4710 if (Instruction *I = dyn_cast<Instruction>(RV))
4711 return I;
4712 // Otherwise, it's a constant boolean value...
4713 return ReplaceInstUsesWith(I, RV);
4714 }
4715 }
4716 return 0;
4717}
4718
Bill Wendlingdae376a2008-12-01 08:23:25 +00004719/// FoldOrWithConstants - This helper function folds:
4720///
Bill Wendling236a1192008-12-02 05:09:00 +00004721/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004722///
4723/// into:
4724///
Bill Wendling236a1192008-12-02 05:09:00 +00004725/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004726///
Bill Wendling236a1192008-12-02 05:09:00 +00004727/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004728Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004729 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004730 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4731 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004732
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004733 Value *V1 = 0;
4734 ConstantInt *CI2 = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004735 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004736
Bill Wendling86ee3162008-12-02 06:18:11 +00004737 APInt Xor = CI1->getValue() ^ CI2->getValue();
4738 if (!Xor.isAllOnesValue()) return 0;
4739
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004740 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004741 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004742 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4743 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004744 }
4745
4746 return 0;
4747}
4748
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004749Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4750 bool Changed = SimplifyCommutative(I);
4751 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4752
4753 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004754 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004755
4756 // or X, X = X
4757 if (Op0 == Op1)
4758 return ReplaceInstUsesWith(I, Op0);
4759
4760 // See if we can simplify any instructions used by the instruction whose sole
4761 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004762 if (SimplifyDemandedInstructionBits(I))
4763 return &I;
4764 if (isa<VectorType>(I.getType())) {
4765 if (isa<ConstantAggregateZero>(Op1)) {
4766 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4767 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4768 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4769 return ReplaceInstUsesWith(I, I.getOperand(1));
4770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004771 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004773 // or X, -1 == -1
4774 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4775 ConstantInt *C1 = 0; Value *X = 0;
4776 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004777 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004778 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004779 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004780 InsertNewInstBefore(Or, I);
4781 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004782 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004783 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004784 }
4785
4786 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohmancdff2122009-08-12 16:23:25 +00004787 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersona21eb582009-07-10 17:35:01 +00004788 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004789 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004790 InsertNewInstBefore(Or, I);
4791 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004792 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004793 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004794 }
4795
4796 // Try to fold constant and into select arguments.
4797 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4798 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4799 return R;
4800 if (isa<PHINode>(Op0))
4801 if (Instruction *NV = FoldOpIntoPhi(I))
4802 return NV;
4803 }
4804
4805 Value *A = 0, *B = 0;
4806 ConstantInt *C1 = 0, *C2 = 0;
4807
Dan Gohmancdff2122009-08-12 16:23:25 +00004808 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004809 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4810 return ReplaceInstUsesWith(I, Op1);
Dan Gohmancdff2122009-08-12 16:23:25 +00004811 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004812 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4813 return ReplaceInstUsesWith(I, Op0);
4814
4815 // (A | B) | C and A | (B | C) -> bswap if possible.
4816 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohmancdff2122009-08-12 16:23:25 +00004817 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4818 match(Op1, m_Or(m_Value(), m_Value())) ||
4819 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4820 match(Op1, m_Shift(m_Value(), m_Value())))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004821 if (Instruction *BSwap = MatchBSwap(I))
4822 return BSwap;
4823 }
4824
4825 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004826 if (Op0->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004827 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004828 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004829 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004830 InsertNewInstBefore(NOr, I);
4831 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004832 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004833 }
4834
4835 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004836 if (Op1->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004837 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004838 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004839 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004840 InsertNewInstBefore(NOr, I);
4841 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004842 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004843 }
4844
4845 // (A & C)|(B & D)
4846 Value *C = 0, *D = 0;
Dan Gohmancdff2122009-08-12 16:23:25 +00004847 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4848 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004849 Value *V1 = 0, *V2 = 0, *V3 = 0;
4850 C1 = dyn_cast<ConstantInt>(C);
4851 C2 = dyn_cast<ConstantInt>(D);
4852 if (C1 && C2) { // (A & C1)|(B & C2)
4853 // If we have: ((V + N) & C1) | (V & C2)
4854 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4855 // replace with V+N.
4856 if (C1->getValue() == ~C2->getValue()) {
4857 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohmancdff2122009-08-12 16:23:25 +00004858 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004859 // Add commutes, try both ways.
4860 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4861 return ReplaceInstUsesWith(I, A);
4862 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4863 return ReplaceInstUsesWith(I, A);
4864 }
4865 // Or commutes, try both ways.
4866 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohmancdff2122009-08-12 16:23:25 +00004867 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004868 // Add commutes, try both ways.
4869 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4870 return ReplaceInstUsesWith(I, B);
4871 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4872 return ReplaceInstUsesWith(I, B);
4873 }
4874 }
4875 V1 = 0; V2 = 0; V3 = 0;
4876 }
4877
4878 // Check to see if we have any common things being and'ed. If so, find the
4879 // terms for V1 & (V2|V3).
4880 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4881 if (A == B) // (A & C)|(A & D) == A & (C|D)
4882 V1 = A, V2 = C, V3 = D;
4883 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4884 V1 = A, V2 = B, V3 = C;
4885 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4886 V1 = C, V2 = A, V3 = D;
4887 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4888 V1 = C, V2 = A, V3 = B;
4889
4890 if (V1) {
4891 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004892 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4893 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004894 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004895 }
Dan Gohman279952c2008-10-28 22:38:57 +00004896
Dan Gohman35b76162008-10-30 20:40:10 +00004897 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004898 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004899 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004900 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004901 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004902 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004903 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004904 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004905 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004906
Bill Wendling22ca8352008-11-30 13:52:49 +00004907 // ((A&~B)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004908 if ((match(C, m_Not(m_Specific(D))) &&
4909 match(B, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004910 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004911 // ((~B&A)|(~A&B)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004912 if ((match(A, m_Not(m_Specific(D))) &&
4913 match(B, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004914 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004915 // ((A&~B)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004916 if ((match(C, m_Not(m_Specific(B))) &&
4917 match(D, m_Not(m_Specific(A)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004918 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004919 // ((~B&A)|(B&~A)) -> A^B
Dan Gohmancdff2122009-08-12 16:23:25 +00004920 if ((match(A, m_Not(m_Specific(B))) &&
4921 match(D, m_Not(m_Specific(C)))))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004922 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004923 }
4924
4925 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4926 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4927 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4928 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4929 SI0->getOperand(1) == SI1->getOperand(1) &&
4930 (SI0->hasOneUse() || SI1->hasOneUse())) {
4931 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004932 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004933 SI1->getOperand(0),
4934 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004935 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004936 SI1->getOperand(1));
4937 }
4938 }
4939
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004940 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004941 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4942 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004943 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004944 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004945 }
4946 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohmancdff2122009-08-12 16:23:25 +00004947 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4948 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004949 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004950 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004951 }
4952
Dan Gohmancdff2122009-08-12 16:23:25 +00004953 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004954 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004955 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004956 } else {
4957 A = 0;
4958 }
4959 // Note, A is still live here!
Dan Gohmancdff2122009-08-12 16:23:25 +00004960 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004961 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004962 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004963
4964 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4965 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004966 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004967 I.getName()+".demorgan"), I);
Dan Gohmancdff2122009-08-12 16:23:25 +00004968 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004969 }
4970 }
4971
4972 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4973 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00004974 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004975 return R;
4976
Chris Lattner0c678e52008-11-16 05:20:07 +00004977 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4978 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4979 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004980 }
4981
4982 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004983 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004984 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4985 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004986 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4987 !isa<ICmpInst>(Op1C->getOperand(0))) {
4988 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004989 if (SrcTy == Op1C->getOperand(0)->getType() &&
4990 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004991 // Only do this if the casts both really cause code to be
4992 // generated.
4993 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4994 I.getType(), TD) &&
4995 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4996 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004997 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004998 Op1C->getOperand(0),
4999 I.getName());
5000 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005001 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00005002 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005003 }
5004 }
Chris Lattner91882432007-10-24 05:38:08 +00005005 }
5006
5007
5008 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5009 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00005010 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5011 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5012 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00005013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005014
5015 return Changed ? &I : 0;
5016}
5017
Dan Gohman089efff2008-05-13 00:00:25 +00005018namespace {
5019
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005020// XorSelf - Implements: X ^ X --> 0
5021struct XorSelf {
5022 Value *RHS;
5023 XorSelf(Value *rhs) : RHS(rhs) {}
5024 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5025 Instruction *apply(BinaryOperator &Xor) const {
5026 return &Xor;
5027 }
5028};
5029
Dan Gohman089efff2008-05-13 00:00:25 +00005030}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005031
5032Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5033 bool Changed = SimplifyCommutative(I);
5034 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5035
Evan Chenge5cd8032008-03-25 20:07:13 +00005036 if (isa<UndefValue>(Op1)) {
5037 if (isa<UndefValue>(Op0))
5038 // Handle undef ^ undef -> 0 special case. This is a common
5039 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005040 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005041 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005042 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005043
5044 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005045 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005046 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005048 }
5049
5050 // See if we can simplify any instructions used by the instruction whose sole
5051 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005052 if (SimplifyDemandedInstructionBits(I))
5053 return &I;
5054 if (isa<VectorType>(I.getType()))
5055 if (isa<ConstantAggregateZero>(Op1))
5056 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005057
5058 // Is this a ~ operation?
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005059 if (Value *NotOp = dyn_castNotVal(&I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5061 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5062 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5063 if (Op0I->getOpcode() == Instruction::And ||
5064 Op0I->getOpcode() == Instruction::Or) {
Dan Gohmanfe91cd62009-08-12 16:04:34 +00005065 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5066 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005067 Instruction *NotY =
Dan Gohmancdff2122009-08-12 16:23:25 +00005068 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005069 Op0I->getOperand(1)->getName()+".not");
5070 InsertNewInstBefore(NotY, I);
5071 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005072 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005073 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005074 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005075 }
5076 }
5077 }
5078 }
5079
5080
5081 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00005082 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005083 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005084 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005085 return new ICmpInst(ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005086 ICI->getOperand(0), ICI->getOperand(1));
5087
Nick Lewycky1405e922007-08-06 20:04:16 +00005088 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohmane6803b82009-08-25 23:17:54 +00005089 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005090 FCI->getOperand(0), FCI->getOperand(1));
5091 }
5092
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005093 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5094 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5095 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5096 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5097 Instruction::CastOps Opcode = Op0C->getOpcode();
5098 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005099 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson4f720fa2009-07-31 17:39:07 +00005100 ConstantInt::getTrue(*Context),
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005101 Op0C->getDestTy())) {
5102 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5103 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 Anderson35b47072009-08-13 21:58:54 +00005338 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), 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 Anderson35b47072009-08-13 21:58:54 +00005374 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), 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);
Owen Anderson35b47072009-08-13 21:58:54 +00005395 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
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)
Owen Anderson35b47072009-08-13 21:58:54 +00005545 VariableIdx = new TruncInst(VariableIdx,
5546 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005547 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005548 return VariableIdx;
5549 }
5550
5551 // Otherwise, there is an index. The computation we will do will be modulo
5552 // the pointer size, so get it.
5553 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5554
5555 Offset &= PtrSizeMask;
5556 VariableScale &= PtrSizeMask;
5557
5558 // To do this transformation, any constant index must be a multiple of the
5559 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5560 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5561 // multiple of the variable scale.
5562 int64_t NewOffs = Offset / (int64_t)VariableScale;
5563 if (Offset != NewOffs*(int64_t)VariableScale)
5564 return 0;
5565
5566 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson35b47072009-08-13 21:58:54 +00005567 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattnereba75862008-04-22 02:53:33 +00005568 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005569 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005570 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005571 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005572 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005573 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005574}
5575
5576
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005577/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5578/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005579Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005580 ICmpInst::Predicate Cond,
5581 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005582 // Look through bitcasts.
5583 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5584 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005585
5586 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005587 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005588 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005589 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005590 // know pointers can't overflow since the gep is inbounds. See if we can
5591 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005592 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5593
5594 // If not, synthesize the offset the hard way.
5595 if (Offset == 0)
5596 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohmane6803b82009-08-25 23:17:54 +00005597 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005598 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005599 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005600 // If the base pointers are different, but the indices are the same, just
5601 // compare the base pointer.
5602 if (PtrBase != GEPRHS->getOperand(0)) {
5603 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5604 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5605 GEPRHS->getOperand(0)->getType();
5606 if (IndicesTheSame)
5607 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5608 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5609 IndicesTheSame = false;
5610 break;
5611 }
5612
5613 // If all indices are the same, just compare the base pointers.
5614 if (IndicesTheSame)
Dan Gohmane6803b82009-08-25 23:17:54 +00005615 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005616 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5617
5618 // Otherwise, the base pointers are different and the indices are
5619 // different, bail out.
5620 return 0;
5621 }
5622
5623 // If one of the GEPs has all zero indices, recurse.
5624 bool AllZeros = true;
5625 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5626 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5627 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5628 AllZeros = false;
5629 break;
5630 }
5631 if (AllZeros)
5632 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5633 ICmpInst::getSwappedPredicate(Cond), I);
5634
5635 // If the other GEP has all zero indices, recurse.
5636 AllZeros = true;
5637 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5638 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5639 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5640 AllZeros = false;
5641 break;
5642 }
5643 if (AllZeros)
5644 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5645
5646 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5647 // If the GEPs only differ by one index, compare it.
5648 unsigned NumDifferences = 0; // Keep track of # differences.
5649 unsigned DiffOperand = 0; // The operand that differs.
5650 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5651 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5652 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5653 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5654 // Irreconcilable differences.
5655 NumDifferences = 2;
5656 break;
5657 } else {
5658 if (NumDifferences++) break;
5659 DiffOperand = i;
5660 }
5661 }
5662
5663 if (NumDifferences == 0) // SAME GEP?
5664 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson35b47072009-08-13 21:58:54 +00005665 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewycky09284cf2008-05-17 07:33:39 +00005666 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005667
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005668 else if (NumDifferences == 1) {
5669 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5670 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5671 // Make sure we do a signed comparison here.
Dan Gohmane6803b82009-08-25 23:17:54 +00005672 return new ICmpInst(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);
Dan Gohmane6803b82009-08-25 23:17:54 +00005684 return new ICmpInst(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.
Dan Gohmane6803b82009-08-25 23:17:54 +00005879 return new ICmpInst(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 Anderson35b47072009-08-13 21:58:54 +00005926 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
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.
Dan Gohmane6803b82009-08-25 23:17:54 +00005967 Op2 = InsertNewInstBefore(new FCmpInst(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.
Dan Gohmane6803b82009-08-25 23:17:54 +00005974 Op1 = InsertNewInstBefore(new FCmpInst(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 Anderson35b47072009-08-13 21:58:54 +00005996 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
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 Anderson35b47072009-08-13 21:58:54 +00006000 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
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 Anderson35b47072009-08-13 21:58:54 +00006008 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
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
Owen Anderson35b47072009-08-13 21:58:54 +00006012 if (Ty == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006013 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
Dan Gohmane6803b82009-08-25 23:17:54 +00006074 return new ICmpInst(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));
Dan Gohmane6803b82009-08-25 23:17:54 +00006085 return new ICmpInst(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));
Dan Gohmane6803b82009-08-25 23:17:54 +00006090 return new ICmpInst(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));
Dan Gohmane6803b82009-08-25 23:17:54 +00006095 return new ICmpInst(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));
Dan Gohmane6803b82009-08-25 23:17:54 +00006100 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006147 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006150 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006171 return new ICmpInst(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
Dan Gohmane6803b82009-08-25 23:17:54 +00006174 return new ICmpInst(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))
Dan Gohmane6803b82009-08-25 23:17:54 +00006179 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006190 return new ICmpInst(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
Dan Gohmane6803b82009-08-25 23:17:54 +00006193 return new ICmpInst(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))
Dan Gohmane6803b82009-08-25 23:17:54 +00006198 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006208 return new ICmpInst(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
Dan Gohmane6803b82009-08-25 23:17:54 +00006211 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006222 return new ICmpInst(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
Dan Gohmane6803b82009-08-25 23:17:54 +00006225 return new ICmpInst(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())))
Dan Gohmane6803b82009-08-25 23:17:54 +00006264 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006306 return new ICmpInst(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.
Dan Gohmane6803b82009-08-25 23:17:54 +00006329 Op2 = InsertNewInstBefore(new ICmpInst(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.
Dan Gohmane6803b82009-08-25 23:17:54 +00006336 Op1 = InsertNewInstBefore(new ICmpInst(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 Anderson35b47072009-08-13 21:58:54 +00006351 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
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 }
Dan Gohmane6803b82009-08-25 23:17:54 +00006391 return new ICmpInst(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
Dan Gohmane6803b82009-08-25 23:17:54 +00006418 return new ICmpInst(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();
Dan Gohmane6803b82009-08-25 23:17:54 +00006426 return new ICmpInst(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);
Dan Gohmane6803b82009-08-25 23:17:54 +00006435 return new ICmpInst(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);
Dan Gohmane6803b82009-08-25 23:17:54 +00006459 return new ICmpInst(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))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006472 return new ICmpInst(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))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006481 return new ICmpInst(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;
Dan Gohmane6803b82009-08-25 23:17:54 +00006486 return new ICmpInst(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");
Dan Gohmane6803b82009-08-25 23:17:54 +00006498 return new ICmpInst(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
Dan Gohmane6803b82009-08-25 23:17:54 +00006503 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6504 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6505 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6506 if (B == D) return new ICmpInst(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;
Dan Gohmane6803b82009-08-25 23:17:54 +00006514 return new ICmpInst(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))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006520 return new ICmpInst(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))))
Dan Gohmane6803b82009-08-25 23:17:54 +00006525 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006669 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670 ICmpInst::ICMP_UGE, X, LoBound);
6671 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006672 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006680 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006681 ICmpInst::ICMP_ULT, X, LoBound);
6682 else if (LoOverflow)
Dan Gohmane6803b82009-08-25 23:17:54 +00006683 return new ICmpInst(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));
Dan Gohmane6803b82009-08-25 23:17:54 +00006693 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006701 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006702 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006703 return new ICmpInst(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;
Dan Gohmane6803b82009-08-25 23:17:54 +00006732 return new ICmpInst(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)
Dan Gohmane6803b82009-08-25 23:17:54 +00006761 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohmanfe91cd62009-08-12 16:04:34 +00006762 SubOne(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006763 else
Dan Gohmane6803b82009-08-25 23:17:54 +00006764 return new ICmpInst(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();
Dan Gohmane6803b82009-08-25 23:17:54 +00006775 return new ICmpInst(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);
Dan Gohmane6803b82009-08-25 23:17:54 +00006786 return new ICmpInst(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);
Dan Gohmane6803b82009-08-25 23:17:54 +00006818 return new ICmpInst(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 Anderson35b47072009-08-13 21:58:54 +00006936 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), 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);
Dan Gohmane6803b82009-08-25 23:17:54 +00006951 return new ICmpInst(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
Dan Gohmane6803b82009-08-25 23:17:54 +00006968 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006969 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006970 }
6971 break;
6972 }
6973
6974 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6975 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006976 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006977 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006978 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006979
Chris Lattner5ee84f82008-03-21 05:19:58 +00006980 // Check that the shift amount is in range. If not, don't perform
6981 // undefined shifts. When the shift is visited it will be
6982 // simplified.
6983 uint32_t TypeBits = RHSV.getBitWidth();
6984 if (ShAmt->uge(TypeBits))
6985 break;
6986
6987 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006988
Chris Lattner5ee84f82008-03-21 05:19:58 +00006989 // If we are comparing against bits always shifted out, the
6990 // comparison cannot succeed.
6991 APInt Comp = RHSV << ShAmtVal;
6992 if (LHSI->getOpcode() == Instruction::LShr)
6993 Comp = Comp.lshr(ShAmtVal);
6994 else
6995 Comp = Comp.ashr(ShAmtVal);
6996
6997 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6998 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson35b47072009-08-13 21:58:54 +00006999 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00007000 return ReplaceInstUsesWith(ICI, Cst);
7001 }
7002
7003 // Otherwise, check to see if the bits shifted out are known to be zero.
7004 // If so, we can compare against the unshifted value:
7005 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007006 if (LHSI->hasOneUse() &&
7007 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007008 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007009 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007010 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007011 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007012
Evan Chengfb9292a2008-04-23 00:38:06 +00007013 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007014 // Otherwise strength reduce the shift into an and.
7015 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007016 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007017
Chris Lattner5ee84f82008-03-21 05:19:58 +00007018 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00007019 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007020 Mask, LHSI->getName()+".mask");
7021 Value *And = InsertNewInstBefore(AndI, ICI);
Dan Gohmane6803b82009-08-25 23:17:54 +00007022 return new ICmpInst(ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007023 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007024 }
7025 break;
7026 }
7027
7028 case Instruction::SDiv:
7029 case Instruction::UDiv:
7030 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7031 // Fold this div into the comparison, producing a range check.
7032 // Determine, based on the divide type, what the range is being
7033 // checked. If there is an overflow on the low or high side, remember
7034 // it, otherwise compute the range [low, hi) bounding the new value.
7035 // See: InsertRangeTest above for the kinds of replacements possible.
7036 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7037 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7038 DivRHS))
7039 return R;
7040 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007041
7042 case Instruction::Add:
7043 // Fold: icmp pred (add, X, C1), C2
7044
7045 if (!ICI.isEquality()) {
7046 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7047 if (!LHSC) break;
7048 const APInt &LHSV = LHSC->getValue();
7049
7050 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7051 .subtract(LHSV);
7052
7053 if (ICI.isSignedPredicate()) {
7054 if (CR.getLower().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007055 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007056 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007057 } else if (CR.getUpper().isSignBit()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007058 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007059 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007060 }
7061 } else {
7062 if (CR.getLower().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007063 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007064 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007065 } else if (CR.getUpper().isMinValue()) {
Dan Gohmane6803b82009-08-25 23:17:54 +00007066 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007067 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007068 }
7069 }
7070 }
7071 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007072 }
7073
7074 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7075 if (ICI.isEquality()) {
7076 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7077
7078 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7079 // the second operand is a constant, simplify a bit.
7080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7081 switch (BO->getOpcode()) {
7082 case Instruction::SRem:
7083 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7084 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7085 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7086 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7087 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00007088 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007089 BO->getName());
7090 InsertNewInstBefore(NewRem, ICI);
Dan Gohmane6803b82009-08-25 23:17:54 +00007091 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007092 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007093 }
7094 }
7095 break;
7096 case Instruction::Add:
7097 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7098 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7099 if (BO->hasOneUse())
Dan Gohmane6803b82009-08-25 23:17:54 +00007100 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007101 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007102 } else if (RHSV == 0) {
7103 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7104 // efficiently invertible, or if the add has just this one use.
7105 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7106
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007107 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohmane6803b82009-08-25 23:17:54 +00007108 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohmanfe91cd62009-08-12 16:04:34 +00007109 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohmane6803b82009-08-25 23:17:54 +00007110 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007111 else if (BO->hasOneUse()) {
Dan Gohmancdff2122009-08-12 16:23:25 +00007112 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007113 InsertNewInstBefore(Neg, ICI);
7114 Neg->takeName(BO);
Dan Gohmane6803b82009-08-25 23:17:54 +00007115 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007116 }
7117 }
7118 break;
7119 case Instruction::Xor:
7120 // For the xor case, we can xor two constants together, eliminating
7121 // the explicit xor.
7122 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohmane6803b82009-08-25 23:17:54 +00007123 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007124 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007125
7126 // FALLTHROUGH
7127 case Instruction::Sub:
7128 // Replace (([sub|xor] A, B) != 0) with (A != B)
7129 if (RHSV == 0)
Dan Gohmane6803b82009-08-25 23:17:54 +00007130 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007131 BO->getOperand(1));
7132 break;
7133
7134 case Instruction::Or:
7135 // If bits are being or'd in that are not present in the constant we
7136 // are comparing against, then the comparison could never succeed!
7137 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007138 Constant *NotCI = ConstantExpr::getNot(RHS);
7139 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007140 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007141 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007142 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143 }
7144 break;
7145
7146 case Instruction::And:
7147 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7148 // If bits are being compared against that are and'd out, then the
7149 // comparison can never succeed!
7150 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007151 return ReplaceInstUsesWith(ICI,
Owen Anderson35b47072009-08-13 21:58:54 +00007152 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Anderson24be4c12009-07-03 00:17:18 +00007153 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007154
7155 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7156 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohmane6803b82009-08-25 23:17:54 +00007157 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007159 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007160
7161 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007162 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007163 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007164 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007165 ICmpInst::Predicate pred = isICMP_NE ?
7166 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohmane6803b82009-08-25 23:17:54 +00007167 return new ICmpInst(pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007168 }
7169
7170 // ((X & ~7) == 0) --> X < 8
7171 if (RHSV == 0 && isHighOnes(BOC)) {
7172 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007173 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007174 ICmpInst::Predicate pred = isICMP_NE ?
7175 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohmane6803b82009-08-25 23:17:54 +00007176 return new ICmpInst(pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007177 }
7178 }
7179 default: break;
7180 }
7181 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7182 // Handle icmp {eq|ne} <intrinsic>, intcst.
7183 if (II->getIntrinsicID() == Intrinsic::bswap) {
7184 AddToWorkList(II);
7185 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007186 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007187 return &ICI;
7188 }
7189 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007190 }
7191 return 0;
7192}
7193
7194/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7195/// We only handle extending casts so far.
7196///
7197Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7198 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7199 Value *LHSCIOp = LHSCI->getOperand(0);
7200 const Type *SrcTy = LHSCIOp->getType();
7201 const Type *DestTy = LHSCI->getType();
7202 Value *RHSCIOp;
7203
7204 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7205 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007206 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7207 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007208 cast<IntegerType>(DestTy)->getBitWidth()) {
7209 Value *RHSOp = 0;
7210 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007211 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007212 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7213 RHSOp = RHSC->getOperand(0);
7214 // If the pointer types don't match, insert a bitcast.
7215 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007216 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007217 }
7218
7219 if (RHSOp)
Dan Gohmane6803b82009-08-25 23:17:54 +00007220 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007221 }
7222
7223 // The code below only handles extension cast instructions, so far.
7224 // Enforce this.
7225 if (LHSCI->getOpcode() != Instruction::ZExt &&
7226 LHSCI->getOpcode() != Instruction::SExt)
7227 return 0;
7228
7229 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7230 bool isSignedCmp = ICI.isSignedPredicate();
7231
7232 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7233 // Not an extension from the same type?
7234 RHSCIOp = CI->getOperand(0);
7235 if (RHSCIOp->getType() != LHSCIOp->getType())
7236 return 0;
7237
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007238 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007239 // and the other is a zext), then we can't handle this.
7240 if (CI->getOpcode() != LHSCI->getOpcode())
7241 return 0;
7242
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007243 // Deal with equality cases early.
7244 if (ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007245 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007246
7247 // A signed comparison of sign extended values simplifies into a
7248 // signed comparison.
7249 if (isSignedCmp && isSignedExt)
Dan Gohmane6803b82009-08-25 23:17:54 +00007250 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007251
7252 // The other three cases all fold into an unsigned comparison.
Dan Gohmane6803b82009-08-25 23:17:54 +00007253 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007254 }
7255
7256 // If we aren't dealing with a constant on the RHS, exit early
7257 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7258 if (!CI)
7259 return 0;
7260
7261 // Compute the constant that would happen if we truncated to SrcTy then
7262 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007263 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7264 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007265 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007266
7267 // If the re-extended constant didn't change...
7268 if (Res2 == CI) {
7269 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7270 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007271 // %A = sext i16 %X to i32
7272 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007273 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007274 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007275 // because %A may have negative value.
7276 //
Chris Lattner3d816532008-07-11 04:09:09 +00007277 // However, we allow this when the compare is EQ/NE, because they are
7278 // signless.
7279 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmane6803b82009-08-25 23:17:54 +00007280 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007281 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007282 }
7283
7284 // The re-extended constant changed so the constant cannot be represented
7285 // in the shorter type. Consequently, we cannot emit a simple comparison.
7286
7287 // First, handle some easy cases. We know the result cannot be equal at this
7288 // point so handle the ICI.isEquality() cases
7289 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007290 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007291 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007292 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007293
7294 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7295 // should have been folded away previously and not enter in here.
7296 Value *Result;
7297 if (isSignedCmp) {
7298 // We're performing a signed comparison.
7299 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007300 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007301 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007302 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007303 } else {
7304 // We're performing an unsigned comparison.
7305 if (isSignedExt) {
7306 // We're performing an unsigned comp with a sign extended value.
7307 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007308 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Dan Gohmane6803b82009-08-25 23:17:54 +00007309 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
Owen Anderson6601fcd2009-07-09 23:48:35 +00007310 LHSCIOp, NegOne, ICI.getName()), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007311 } else {
7312 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007313 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007314 }
7315 }
7316
7317 // Finally, return the value computed.
7318 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007319 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007320 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007321
7322 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7323 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7324 "ICmp should be folded!");
7325 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007326 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohmancdff2122009-08-12 16:23:25 +00007327 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007328}
7329
7330Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7331 return commonShiftTransforms(I);
7332}
7333
7334Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7335 return commonShiftTransforms(I);
7336}
7337
7338Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007339 if (Instruction *R = commonShiftTransforms(I))
7340 return R;
7341
7342 Value *Op0 = I.getOperand(0);
7343
7344 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7345 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7346 if (CSI->isAllOnesValue())
7347 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007348
Dan Gohman2526aea2009-06-16 19:55:29 +00007349 // See if we can turn a signed shr into an unsigned shr.
7350 if (MaskedValueIsZero(Op0,
7351 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7352 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7353
7354 // Arithmetic shifting an all-sign-bit value is a no-op.
7355 unsigned NumSignBits = ComputeNumSignBits(Op0);
7356 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7357 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007358
Chris Lattnere3c504f2007-12-06 01:59:46 +00007359 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007360}
7361
7362Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7363 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7364 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7365
7366 // shl X, 0 == X and shr X, 0 == X
7367 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007368 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7369 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007370 return ReplaceInstUsesWith(I, Op0);
7371
7372 if (isa<UndefValue>(Op0)) {
7373 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7374 return ReplaceInstUsesWith(I, Op0);
7375 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007377 }
7378 if (isa<UndefValue>(Op1)) {
7379 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7380 return ReplaceInstUsesWith(I, Op0);
7381 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007382 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007383 }
7384
Dan Gohman2bc21562009-05-21 02:28:33 +00007385 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007386 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007387 return &I;
7388
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007389 // Try to fold constant and into select arguments.
7390 if (isa<Constant>(Op0))
7391 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7392 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7393 return R;
7394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007395 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7396 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7397 return Res;
7398 return 0;
7399}
7400
7401Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7402 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007403 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007404
7405 // See if we can simplify any instructions used by the instruction whose sole
7406 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007407 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007408
Dan Gohman9e1657f2009-06-14 23:30:43 +00007409 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7410 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007411 //
7412 if (Op1->uge(TypeBits)) {
7413 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007414 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007415 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007416 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007417 return &I;
7418 }
7419 }
7420
7421 // ((X*C1) << C2) == (X * (C1 << C2))
7422 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7423 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7424 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007425 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007426 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007427
7428 // Try to fold constant and into select arguments.
7429 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7430 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7431 return R;
7432 if (isa<PHINode>(Op0))
7433 if (Instruction *NV = FoldOpIntoPhi(I))
7434 return NV;
7435
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007436 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7437 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7438 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7439 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7440 // place. Don't try to do this transformation in this case. Also, we
7441 // require that the input operand is a shift-by-constant so that we have
7442 // confidence that the shifts will get folded together. We could do this
7443 // xform in more cases, but it is unlikely to be profitable.
7444 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7445 isa<ConstantInt>(TrOp->getOperand(1))) {
7446 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007447 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007448 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007449 I.getName());
7450 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7451
7452 // For logical shifts, the truncation has the effect of making the high
7453 // part of the register be zeros. Emulate this by inserting an AND to
7454 // clear the top bits as needed. This 'and' will usually be zapped by
7455 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007456 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7457 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007458 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7459
7460 // The mask we constructed says what the trunc would do if occurring
7461 // between the shifts. We want to know the effect *after* the second
7462 // shift. We know that it is a logical shift by a constant, so adjust the
7463 // mask as appropriate.
7464 if (I.getOpcode() == Instruction::Shl)
7465 MaskV <<= Op1->getZExtValue();
7466 else {
7467 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7468 MaskV = MaskV.lshr(Op1->getZExtValue());
7469 }
7470
Owen Anderson24be4c12009-07-03 00:17:18 +00007471 Instruction *And =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007472 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Anderson24be4c12009-07-03 00:17:18 +00007473 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007474 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7475
7476 // Return the value truncated to the interesting size.
7477 return new TruncInst(And, I.getType());
7478 }
7479 }
7480
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007481 if (Op0->hasOneUse()) {
7482 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7483 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7484 Value *V1, *V2;
7485 ConstantInt *CC;
7486 switch (Op0BO->getOpcode()) {
7487 default: break;
7488 case Instruction::Add:
7489 case Instruction::And:
7490 case Instruction::Or:
7491 case Instruction::Xor: {
7492 // These operators commute.
7493 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7494 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007495 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007496 m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007497 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007498 Op0BO->getOperand(0), Op1,
7499 Op0BO->getName());
7500 InsertNewInstBefore(YS, I); // (Y << C)
7501 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007502 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007503 Op0BO->getOperand(1)->getName());
7504 InsertNewInstBefore(X, I); // (X + (Y << C))
7505 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007506 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007507 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7508 }
7509
7510 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7511 Value *Op0BOOp1 = Op0BO->getOperand(1);
7512 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7513 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007514 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007515 m_ConstantInt(CC))) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007516 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007517 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007518 Op0BO->getOperand(0), Op1,
7519 Op0BO->getName());
7520 InsertNewInstBefore(YS, I); // (Y << C)
7521 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007522 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007523 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007524 V1->getName()+".mask");
7525 InsertNewInstBefore(XM, I); // X & (CC << C)
7526
Gabor Greifa645dd32008-05-16 19:29:10 +00007527 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007528 }
7529 }
7530
7531 // FALL THROUGH.
7532 case Instruction::Sub: {
7533 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7534 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007535 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohmancdff2122009-08-12 16:23:25 +00007536 m_Specific(Op1)))) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007537 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007538 Op0BO->getOperand(1), Op1,
7539 Op0BO->getName());
7540 InsertNewInstBefore(YS, I); // (Y << C)
7541 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007542 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007543 Op0BO->getOperand(0)->getName());
7544 InsertNewInstBefore(X, I); // (X + (Y << C))
7545 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007546 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007547 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7548 }
7549
7550 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7551 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7552 match(Op0BO->getOperand(0),
7553 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohmancdff2122009-08-12 16:23:25 +00007554 m_ConstantInt(CC))) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007555 cast<BinaryOperator>(Op0BO->getOperand(0))
7556 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007557 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007558 Op0BO->getOperand(1), Op1,
7559 Op0BO->getName());
7560 InsertNewInstBefore(YS, I); // (Y << C)
7561 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007562 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007563 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007564 V1->getName()+".mask");
7565 InsertNewInstBefore(XM, I); // X & (CC << C)
7566
Gabor Greifa645dd32008-05-16 19:29:10 +00007567 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007568 }
7569
7570 break;
7571 }
7572 }
7573
7574
7575 // If the operand is an bitwise operator with a constant RHS, and the
7576 // shift is the only use, we can pull it out of the shift.
7577 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7578 bool isValid = true; // Valid only for And, Or, Xor
7579 bool highBitSet = false; // Transform if high bit of constant set?
7580
7581 switch (Op0BO->getOpcode()) {
7582 default: isValid = false; break; // Do not perform transform!
7583 case Instruction::Add:
7584 isValid = isLeftShift;
7585 break;
7586 case Instruction::Or:
7587 case Instruction::Xor:
7588 highBitSet = false;
7589 break;
7590 case Instruction::And:
7591 highBitSet = true;
7592 break;
7593 }
7594
7595 // If this is a signed shift right, and the high bit is modified
7596 // by the logical operation, do not perform the transformation.
7597 // The highBitSet boolean indicates the value of the high bit of
7598 // the constant which would cause it to be modified for this
7599 // operation.
7600 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007601 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007602 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007603
7604 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007605 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007606
7607 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007608 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007609 InsertNewInstBefore(NewShift, I);
7610 NewShift->takeName(Op0BO);
7611
Gabor Greifa645dd32008-05-16 19:29:10 +00007612 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007613 NewRHS);
7614 }
7615 }
7616 }
7617 }
7618
7619 // Find out if this is a shift of a shift by a constant.
7620 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7621 if (ShiftOp && !ShiftOp->isShift())
7622 ShiftOp = 0;
7623
7624 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7625 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7626 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7627 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7628 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7629 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7630 Value *X = ShiftOp->getOperand(0);
7631
7632 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007633
7634 const IntegerType *Ty = cast<IntegerType>(I.getType());
7635
7636 // Check for (X << c1) << c2 and (X >> c1) >> c2
7637 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007638 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7639 // saturates.
7640 if (AmtSum >= TypeBits) {
7641 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007642 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007643 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7644 }
7645
Gabor Greifa645dd32008-05-16 19:29:10 +00007646 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007647 ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007648 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7649 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007650 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007651 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007652
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007653 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007654 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7656 I.getOpcode() == Instruction::LShr) {
7657 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007658 if (AmtSum >= TypeBits)
7659 AmtSum = TypeBits-1;
7660
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007661 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007662 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007663 InsertNewInstBefore(Shift, I);
7664
7665 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007666 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007667 }
7668
7669 // Okay, if we get here, one shift must be left, and the other shift must be
7670 // right. See if the amounts are equal.
7671 if (ShiftAmt1 == ShiftAmt2) {
7672 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7673 if (I.getOpcode() == Instruction::Shl) {
7674 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007675 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007676 }
7677 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7678 if (I.getOpcode() == Instruction::LShr) {
7679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007680 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007681 }
7682 // We can simplify ((X << C) >>s C) into a trunc + sext.
7683 // NOTE: we could do this for any C, but that would make 'unusual' integer
7684 // types. For now, just stick to ones well-supported by the code
7685 // generators.
7686 const Type *SExtType = 0;
7687 switch (Ty->getBitWidth() - ShiftAmt1) {
7688 case 1 :
7689 case 8 :
7690 case 16 :
7691 case 32 :
7692 case 64 :
7693 case 128:
Owen Anderson35b47072009-08-13 21:58:54 +00007694 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007695 break;
7696 default: break;
7697 }
7698 if (SExtType) {
7699 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7700 InsertNewInstBefore(NewTrunc, I);
7701 return new SExtInst(NewTrunc, Ty);
7702 }
7703 // Otherwise, we can't handle it yet.
7704 } else if (ShiftAmt1 < ShiftAmt2) {
7705 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7706
7707 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7708 if (I.getOpcode() == Instruction::Shl) {
7709 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7710 ShiftOp->getOpcode() == Instruction::AShr);
7711 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007712 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007713 InsertNewInstBefore(Shift, I);
7714
7715 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007716 return BinaryOperator::CreateAnd(Shift,
7717 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007718 }
7719
7720 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7721 if (I.getOpcode() == Instruction::LShr) {
7722 assert(ShiftOp->getOpcode() == Instruction::Shl);
7723 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007724 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007725 InsertNewInstBefore(Shift, I);
7726
7727 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007728 return BinaryOperator::CreateAnd(Shift,
7729 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007730 }
7731
7732 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7733 } else {
7734 assert(ShiftAmt2 < ShiftAmt1);
7735 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7736
7737 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7738 if (I.getOpcode() == Instruction::Shl) {
7739 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7740 ShiftOp->getOpcode() == Instruction::AShr);
7741 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007742 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007743 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007744 InsertNewInstBefore(Shift, I);
7745
7746 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007747 return BinaryOperator::CreateAnd(Shift,
7748 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007749 }
7750
7751 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7752 if (I.getOpcode() == Instruction::LShr) {
7753 assert(ShiftOp->getOpcode() == Instruction::Shl);
7754 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007755 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007756 InsertNewInstBefore(Shift, I);
7757
7758 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007759 return BinaryOperator::CreateAnd(Shift,
7760 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007761 }
7762
7763 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7764 }
7765 }
7766 return 0;
7767}
7768
7769
7770/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7771/// expression. If so, decompose it, returning some value X, such that Val is
7772/// X*Scale+Offset.
7773///
7774static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007775 int &Offset, LLVMContext *Context) {
Owen Anderson35b47072009-08-13 21:58:54 +00007776 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007777 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7778 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007779 Scale = 0;
Owen Anderson35b47072009-08-13 21:58:54 +00007780 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007781 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7782 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7783 if (I->getOpcode() == Instruction::Shl) {
7784 // This is a value scaled by '1 << the shift amt'.
7785 Scale = 1U << RHS->getZExtValue();
7786 Offset = 0;
7787 return I->getOperand(0);
7788 } else if (I->getOpcode() == Instruction::Mul) {
7789 // This value is scaled by 'RHS'.
7790 Scale = RHS->getZExtValue();
7791 Offset = 0;
7792 return I->getOperand(0);
7793 } else if (I->getOpcode() == Instruction::Add) {
7794 // We have X+C. Check to see if we really have (X*C2)+C1,
7795 // where C1 is divisible by C2.
7796 unsigned SubScale;
7797 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007798 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7799 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007800 Offset += RHS->getZExtValue();
7801 Scale = SubScale;
7802 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007803 }
7804 }
7805 }
7806
7807 // Otherwise, we can't look past this.
7808 Scale = 1;
7809 Offset = 0;
7810 return Val;
7811}
7812
7813
7814/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7815/// try to eliminate the cast by moving the type information into the alloc.
7816Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7817 AllocationInst &AI) {
7818 const PointerType *PTy = cast<PointerType>(CI.getType());
7819
7820 // Remove any uses of AI that are dead.
7821 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7822
7823 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7824 Instruction *User = cast<Instruction>(*UI++);
7825 if (isInstructionTriviallyDead(User)) {
7826 while (UI != E && *UI == User)
7827 ++UI; // If this instruction uses AI more than once, don't break UI.
7828
7829 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00007830 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007831 EraseInstFromFunction(*User);
7832 }
7833 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007834
7835 // This requires TargetData to get the alloca alignment and size information.
7836 if (!TD) return 0;
7837
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007838 // Get the type really allocated and the type casted to.
7839 const Type *AllocElTy = AI.getAllocatedType();
7840 const Type *CastElTy = PTy->getElementType();
7841 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7842
7843 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7844 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7845 if (CastElTyAlign < AllocElTyAlign) return 0;
7846
7847 // If the allocation has multiple uses, only promote it if we are strictly
7848 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007849 // same, we open the door to infinite loops of various kinds. (A reference
7850 // from a dbg.declare doesn't count as a use for this purpose.)
7851 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7852 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007853
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007854 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7855 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007856 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7857
7858 // See if we can satisfy the modulus by pulling a scale out of the array
7859 // size argument.
7860 unsigned ArraySizeScale;
7861 int ArrayOffset;
7862 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007863 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7864 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007865
7866 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7867 // do the xform.
7868 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7869 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7870
7871 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7872 Value *Amt = 0;
7873 if (Scale == 1) {
7874 Amt = NumElements;
7875 } else {
7876 // If the allocation size is constant, form a constant mul expression
Owen Anderson35b47072009-08-13 21:58:54 +00007877 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007878 if (isa<ConstantInt>(NumElements))
Owen Anderson02b48c32009-07-29 18:55:55 +00007879 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman8fd520a2009-06-15 22:12:54 +00007880 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007881 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007882 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007883 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007884 Amt = InsertNewInstBefore(Tmp, AI);
7885 }
7886 }
7887
7888 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson35b47072009-08-13 21:58:54 +00007889 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007890 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007891 Amt = InsertNewInstBefore(Tmp, AI);
7892 }
7893
7894 AllocationInst *New;
7895 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +00007896 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007897 else
Owen Anderson140166d2009-07-15 23:53:25 +00007898 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007899 InsertNewInstBefore(New, AI);
7900 New->takeName(&AI);
7901
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007902 // If the allocation has one real use plus a dbg.declare, just remove the
7903 // declare.
7904 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7905 EraseInstFromFunction(*DI);
7906 }
7907 // If the allocation has multiple real uses, insert a cast and change all
7908 // things that used it to use the new cast. This will also hack on CI, but it
7909 // will die soon.
7910 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007911 AddUsesToWorkList(AI);
7912 // New is the allocation instruction, pointer typed. AI is the original
7913 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7914 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7915 InsertNewInstBefore(NewCast, AI);
7916 AI.replaceAllUsesWith(NewCast);
7917 }
7918 return ReplaceInstUsesWith(CI, New);
7919}
7920
7921/// CanEvaluateInDifferentType - Return true if we can take the specified value
7922/// and return it as type Ty without inserting any new casts and without
7923/// changing the computed value. This is used by code that tries to decide
7924/// whether promoting or shrinking integer operations to wider or smaller types
7925/// will allow us to eliminate a truncate or extend.
7926///
7927/// This is a truncation operation if Ty is smaller than V->getType(), or an
7928/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007929///
7930/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7931/// should return true if trunc(V) can be computed by computing V in the smaller
7932/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7933/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7934/// efficiently truncated.
7935///
7936/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7937/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7938/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007939bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007940 unsigned CastOpc,
7941 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007942 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007943 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007944 return true;
7945
7946 Instruction *I = dyn_cast<Instruction>(V);
7947 if (!I) return false;
7948
Dan Gohman8fd520a2009-06-15 22:12:54 +00007949 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007950
Chris Lattneref70bb82007-08-02 06:11:14 +00007951 // If this is an extension or truncate, we can often eliminate it.
7952 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7953 // If this is a cast from the destination type, we can trivially eliminate
7954 // it, and this will remove a cast overall.
7955 if (I->getOperand(0)->getType() == Ty) {
7956 // If the first operand is itself a cast, and is eliminable, do not count
7957 // this as an eliminable cast. We would prefer to eliminate those two
7958 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007959 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007960 ++NumCastsRemoved;
7961 return true;
7962 }
7963 }
7964
7965 // We can't extend or shrink something that has multiple uses: doing so would
7966 // require duplicating the instruction in general, which isn't profitable.
7967 if (!I->hasOneUse()) return false;
7968
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007969 unsigned Opc = I->getOpcode();
7970 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007971 case Instruction::Add:
7972 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007973 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007974 case Instruction::And:
7975 case Instruction::Or:
7976 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007977 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007978 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007979 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007980 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007981 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007982
Eli Friedman08c45bc2009-07-13 22:46:01 +00007983 case Instruction::UDiv:
7984 case Instruction::URem: {
7985 // UDiv and URem can be truncated if all the truncated bits are zero.
7986 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7987 uint32_t BitWidth = Ty->getScalarSizeInBits();
7988 if (BitWidth < OrigBitWidth) {
7989 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7990 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7991 MaskedValueIsZero(I->getOperand(1), Mask)) {
7992 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7993 NumCastsRemoved) &&
7994 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7995 NumCastsRemoved);
7996 }
7997 }
7998 break;
7999 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008000 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008001 // If we are truncating the result of this SHL, and if it's a shift of a
8002 // constant amount, we can always perform a SHL in a smaller type.
8003 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008004 uint32_t BitWidth = Ty->getScalarSizeInBits();
8005 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008006 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00008007 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008008 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008009 }
8010 break;
8011 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008012 // If this is a truncate of a logical shr, we can truncate it to a smaller
8013 // lshr iff we know that the bits we would otherwise be shifting in are
8014 // already zeros.
8015 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008016 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8017 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008018 if (BitWidth < OrigBitWidth &&
8019 MaskedValueIsZero(I->getOperand(0),
8020 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8021 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008022 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008023 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008024 }
8025 }
8026 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008027 case Instruction::ZExt:
8028 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008029 case Instruction::Trunc:
8030 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008031 // can safely replace it. Note that replacing it does not reduce the number
8032 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008033 if (Opc == CastOpc)
8034 return true;
8035
8036 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008037 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008038 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008039 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008040 case Instruction::Select: {
8041 SelectInst *SI = cast<SelectInst>(I);
8042 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008043 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008044 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008045 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008046 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008047 case Instruction::PHI: {
8048 // We can change a phi if we can change all operands.
8049 PHINode *PN = cast<PHINode>(I);
8050 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8051 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008052 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008053 return false;
8054 return true;
8055 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008056 default:
8057 // TODO: Can handle more cases here.
8058 break;
8059 }
8060
8061 return false;
8062}
8063
8064/// EvaluateInDifferentType - Given an expression that
8065/// CanEvaluateInDifferentType returns true for, actually insert the code to
8066/// evaluate the expression.
8067Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8068 bool isSigned) {
8069 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00008070 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00008071 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008072
8073 // Otherwise, it must be an instruction.
8074 Instruction *I = cast<Instruction>(V);
8075 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008076 unsigned Opc = I->getOpcode();
8077 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008078 case Instruction::Add:
8079 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008080 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008081 case Instruction::And:
8082 case Instruction::Or:
8083 case Instruction::Xor:
8084 case Instruction::AShr:
8085 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008086 case Instruction::Shl:
8087 case Instruction::UDiv:
8088 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008089 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8090 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008091 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008092 break;
8093 }
8094 case Instruction::Trunc:
8095 case Instruction::ZExt:
8096 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008097 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008098 // just return the source. There's no need to insert it because it is not
8099 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008100 if (I->getOperand(0)->getType() == Ty)
8101 return I->getOperand(0);
8102
Chris Lattner4200c2062008-06-18 04:00:49 +00008103 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008104 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008105 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008106 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008107 case Instruction::Select: {
8108 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8109 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8110 Res = SelectInst::Create(I->getOperand(0), True, False);
8111 break;
8112 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008113 case Instruction::PHI: {
8114 PHINode *OPN = cast<PHINode>(I);
8115 PHINode *NPN = PHINode::Create(Ty);
8116 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8117 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8118 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8119 }
8120 Res = NPN;
8121 break;
8122 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008123 default:
8124 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008125 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008126 break;
8127 }
8128
Chris Lattner4200c2062008-06-18 04:00:49 +00008129 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008130 return InsertNewInstBefore(Res, *I);
8131}
8132
8133/// @brief Implement the transforms common to all CastInst visitors.
8134Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8135 Value *Src = CI.getOperand(0);
8136
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008137 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8138 // eliminate it now.
8139 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8140 if (Instruction::CastOps opc =
8141 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8142 // The first cast (CSrc) is eliminable so we need to fix up or replace
8143 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008144 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008145 }
8146 }
8147
8148 // If we are casting a select then fold the cast into the select
8149 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8150 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8151 return NV;
8152
8153 // If we are casting a PHI then fold the cast into the PHI
8154 if (isa<PHINode>(Src))
8155 if (Instruction *NV = FoldOpIntoPhi(CI))
8156 return NV;
8157
8158 return 0;
8159}
8160
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008161/// FindElementAtOffset - Given a type and a constant offset, determine whether
8162/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008163/// the specified offset. If so, fill them into NewIndices and return the
8164/// resultant element type, otherwise return null.
8165static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8166 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008167 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008168 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008169 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008170 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008171
8172 // Start with the index over the outer type. Note that the type size
8173 // might be zero (even if the offset isn't zero) if the indexed type
8174 // is something like [0 x {int, int}]
Owen Anderson35b47072009-08-13 21:58:54 +00008175 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008176 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008177 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008178 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008179 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008180
Chris Lattnerce48c462009-01-11 20:15:20 +00008181 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008182 if (Offset < 0) {
8183 --FirstIdx;
8184 Offset += TySize;
8185 assert(Offset >= 0);
8186 }
8187 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8188 }
8189
Owen Andersoneacb44d2009-07-24 23:12:02 +00008190 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008191
8192 // Index into the types. If we fail, set OrigBase to null.
8193 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008194 // Indexing into tail padding between struct/array elements.
8195 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008196 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008197
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008198 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8199 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008200 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8201 "Offset must stay within the indexed type");
8202
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008203 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson35b47072009-08-13 21:58:54 +00008204 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008205
8206 Offset -= SL->getElementOffset(Elt);
8207 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008208 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008209 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008210 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008211 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008212 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008213 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008214 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008215 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008216 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008217 }
8218 }
8219
Chris Lattner54dddc72009-01-24 01:00:13 +00008220 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008221}
8222
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008223/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8224Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8225 Value *Src = CI.getOperand(0);
8226
8227 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8228 // If casting the result of a getelementptr instruction with no offset, turn
8229 // this into a cast of the original pointer!
8230 if (GEP->hasAllZeroIndices()) {
8231 // Changing the cast operand is usually not a good idea but it is safe
8232 // here because the pointer operand is being replaced with another
8233 // pointer operand so the opcode doesn't need to change.
8234 AddToWorkList(GEP);
8235 CI.setOperand(0, GEP->getOperand(0));
8236 return &CI;
8237 }
8238
8239 // If the GEP has a single use, and the base pointer is a bitcast, and the
8240 // GEP computes a constant offset, see if we can convert these three
8241 // instructions into fewer. This typically happens with unions and other
8242 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008243 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008244 if (GEP->hasAllConstantIndices()) {
8245 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008246 ConstantInt *OffsetV =
8247 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008248 int64_t Offset = OffsetV->getSExtValue();
8249
8250 // Get the base pointer input of the bitcast, and the type it points to.
8251 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8252 const Type *GEPIdxTy =
8253 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008254 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008255 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008256 // If we were able to index down into an element, create the GEP
8257 // and bitcast the result. This eliminates one bitcast, potentially
8258 // two.
8259 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8260 NewIndices.begin(),
8261 NewIndices.end(), "");
8262 InsertNewInstBefore(NGEP, CI);
8263 NGEP->takeName(GEP);
Dan Gohman17f46f72009-07-28 01:40:03 +00008264 if (cast<GEPOperator>(GEP)->isInBounds())
8265 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008266
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008267 if (isa<BitCastInst>(CI))
8268 return new BitCastInst(NGEP, CI.getType());
8269 assert(isa<PtrToIntInst>(CI));
8270 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008271 }
8272 }
8273 }
8274 }
8275
8276 return commonCastTransforms(CI);
8277}
8278
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008279/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8280/// type like i42. We don't want to introduce operations on random non-legal
8281/// integer types where they don't already exist in the code. In the future,
8282/// we should consider making this based off target-data, so that 32-bit targets
8283/// won't get i64 operations etc.
8284static bool isSafeIntegerType(const Type *Ty) {
8285 switch (Ty->getPrimitiveSizeInBits()) {
8286 case 8:
8287 case 16:
8288 case 32:
8289 case 64:
8290 return true;
8291 default:
8292 return false;
8293 }
8294}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008295
Eli Friedman827e37a2009-07-13 20:58:59 +00008296/// commonIntCastTransforms - This function implements the common transforms
8297/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008298Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8299 if (Instruction *Result = commonCastTransforms(CI))
8300 return Result;
8301
8302 Value *Src = CI.getOperand(0);
8303 const Type *SrcTy = Src->getType();
8304 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008305 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8306 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008307
8308 // See if we can simplify any instructions used by the LHS whose sole
8309 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008310 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008311 return &CI;
8312
8313 // If the source isn't an instruction or has more than one use then we
8314 // can't do anything more.
8315 Instruction *SrcI = dyn_cast<Instruction>(Src);
8316 if (!SrcI || !Src->hasOneUse())
8317 return 0;
8318
8319 // Attempt to propagate the cast into the instruction for int->int casts.
8320 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008321 // Only do this if the dest type is a simple type, don't convert the
8322 // expression tree to something weird like i93 unless the source is also
8323 // strange.
8324 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008325 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8326 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008327 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008328 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008329 // eliminates the cast, so it is always a win. If this is a zero-extension,
8330 // we need to do an AND to maintain the clear top-part of the computation,
8331 // so we require that the input have eliminated at least one cast. If this
8332 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008333 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008334 bool DoXForm = false;
8335 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008336 switch (CI.getOpcode()) {
8337 default:
8338 // All the others use floating point so we shouldn't actually
8339 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008340 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008341 case Instruction::Trunc:
8342 DoXForm = true;
8343 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008344 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008345 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008346 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008347 // If it's unnecessary to issue an AND to clear the high bits, it's
8348 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008349 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008350 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8351 if (MaskedValueIsZero(TryRes, Mask))
8352 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008353
8354 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008355 if (TryI->use_empty())
8356 EraseInstFromFunction(*TryI);
8357 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008358 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008359 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008360 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008361 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008362 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008363 // If we do not have to emit the truncate + sext pair, then it's always
8364 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008365 //
8366 // It's not safe to eliminate the trunc + sext pair if one of the
8367 // eliminated cast is a truncate. e.g.
8368 // t2 = trunc i32 t1 to i16
8369 // t3 = sext i16 t2 to i32
8370 // !=
8371 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008372 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008373 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8374 if (NumSignBits > (DestBitSize - SrcBitSize))
8375 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008376
8377 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008378 if (TryI->use_empty())
8379 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008380 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008381 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008382 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008384
8385 if (DoXForm) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00008386 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8387 " to avoid cast: " << CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008388 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8389 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008390 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008391 // Just replace this cast with the result.
8392 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008393
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008394 assert(Res->getType() == DestTy);
8395 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008396 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008397 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008398 // Just replace this cast with the result.
8399 return ReplaceInstUsesWith(CI, Res);
8400 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008401 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008402
8403 // If the high bits are already zero, just replace this cast with the
8404 // result.
8405 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8406 if (MaskedValueIsZero(Res, Mask))
8407 return ReplaceInstUsesWith(CI, Res);
8408
8409 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008410 Constant *C = ConstantInt::get(*Context,
8411 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008412 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008414 case Instruction::SExt: {
8415 // If the high bits are already filled with sign bit, just replace this
8416 // cast with the result.
8417 unsigned NumSignBits = ComputeNumSignBits(Res);
8418 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008419 return ReplaceInstUsesWith(CI, Res);
8420
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008421 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008422 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008423 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8424 CI), DestTy);
8425 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008427 }
8428 }
8429
8430 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8431 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8432
8433 switch (SrcI->getOpcode()) {
8434 case Instruction::Add:
8435 case Instruction::Mul:
8436 case Instruction::And:
8437 case Instruction::Or:
8438 case Instruction::Xor:
8439 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008440 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8441 // Don't insert two casts unless at least one can be eliminated.
8442 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008443 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008444 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8445 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008446 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008447 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8448 }
8449 }
8450
8451 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8452 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8453 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008454 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008455 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008456 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008457 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008458 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008459 }
8460 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008461
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008462 case Instruction::Shl: {
8463 // Canonicalize trunc inside shl, if we can.
8464 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8465 if (CI && DestBitSize < SrcBitSize &&
8466 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8467 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8468 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008469 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008470 }
8471 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008472 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008473 }
8474 return 0;
8475}
8476
8477Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8478 if (Instruction *Result = commonIntCastTransforms(CI))
8479 return Result;
8480
8481 Value *Src = CI.getOperand(0);
8482 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008483 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8484 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008485
8486 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008487 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008488 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner32177f82009-03-24 18:15:30 +00008489 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersonaac28372009-07-31 20:28:14 +00008490 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohmane6803b82009-08-25 23:17:54 +00008491 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008492 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008493
Chris Lattner32177f82009-03-24 18:15:30 +00008494 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8495 ConstantInt *ShAmtV = 0;
8496 Value *ShiftOp = 0;
8497 if (Src->hasOneUse() &&
Dan Gohmancdff2122009-08-12 16:23:25 +00008498 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner32177f82009-03-24 18:15:30 +00008499 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8500
8501 // Get a mask for the bits shifting in.
8502 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8503 if (MaskedValueIsZero(ShiftOp, Mask)) {
8504 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008505 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008506
8507 // Okay, we can shrink this. Truncate the input, then return a new
8508 // shift.
8509 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Anderson02b48c32009-07-29 18:55:55 +00008510 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008511 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008512 }
8513 }
8514
8515 return 0;
8516}
8517
Evan Chenge3779cf2008-03-24 00:21:34 +00008518/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8519/// in order to eliminate the icmp.
8520Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8521 bool DoXform) {
8522 // If we are just checking for a icmp eq of a single bit and zext'ing it
8523 // to an integer, then shift the bit to the appropriate place and then
8524 // cast to integer to avoid the comparison.
8525 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8526 const APInt &Op1CV = Op1C->getValue();
8527
8528 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8529 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8530 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8531 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8532 if (!DoXform) return ICI;
8533
8534 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008535 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008536 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008537 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008538 In->getName()+".lobit"),
8539 CI);
8540 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008541 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008542 false/*ZExt*/, "tmp", &CI);
8543
8544 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008545 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008546 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008547 In->getName()+".not"),
8548 CI);
8549 }
8550
8551 return ReplaceInstUsesWith(CI, In);
8552 }
8553
8554
8555
8556 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8557 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8558 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8559 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8560 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8561 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8562 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8563 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8564 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8565 // This only works for EQ and NE
8566 ICI->isEquality()) {
8567 // If Op1C some other power of two, convert:
8568 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8569 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8570 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8571 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8572
8573 APInt KnownZeroMask(~KnownZero);
8574 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8575 if (!DoXform) return ICI;
8576
8577 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8578 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8579 // (X&4) == 2 --> false
8580 // (X&4) != 2 --> true
Owen Anderson35b47072009-08-13 21:58:54 +00008581 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008582 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008583 return ReplaceInstUsesWith(CI, Res);
8584 }
8585
8586 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8587 Value *In = ICI->getOperand(0);
8588 if (ShiftAmt) {
8589 // Perform a logical shr by shiftamt.
8590 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008591 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008592 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chenge3779cf2008-03-24 00:21:34 +00008593 In->getName()+".lobit"), CI);
8594 }
8595
8596 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008597 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008598 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008599 InsertNewInstBefore(cast<Instruction>(In), CI);
8600 }
8601
8602 if (CI.getType() == In->getType())
8603 return ReplaceInstUsesWith(CI, In);
8604 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008605 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008606 }
8607 }
8608 }
8609
8610 return 0;
8611}
8612
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008613Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8614 // If one of the common conversion will work ..
8615 if (Instruction *Result = commonIntCastTransforms(CI))
8616 return Result;
8617
8618 Value *Src = CI.getOperand(0);
8619
Chris Lattner215d56e2009-02-17 20:47:23 +00008620 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8621 // types and if the sizes are just right we can convert this into a logical
8622 // 'and' which will be much cheaper than the pair of casts.
8623 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8624 // Get the sizes of the types involved. We know that the intermediate type
8625 // will be smaller than A or C, but don't know the relation between A and C.
8626 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008627 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8628 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8629 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008630 // If we're actually extending zero bits, then if
8631 // SrcSize < DstSize: zext(a & mask)
8632 // SrcSize == DstSize: a & mask
8633 // SrcSize > DstSize: trunc(a) & mask
8634 if (SrcSize < DstSize) {
8635 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008636 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008637 Instruction *And =
8638 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8639 InsertNewInstBefore(And, CI);
8640 return new ZExtInst(And, CI.getType());
8641 } else if (SrcSize == DstSize) {
8642 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008643 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008644 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008645 } else if (SrcSize > DstSize) {
8646 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8647 InsertNewInstBefore(Trunc, CI);
8648 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008649 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008650 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008651 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008652 }
8653 }
8654
Evan Chenge3779cf2008-03-24 00:21:34 +00008655 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8656 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008657
Evan Chenge3779cf2008-03-24 00:21:34 +00008658 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8659 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8660 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8661 // of the (zext icmp) will be transformed.
8662 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8663 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8664 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8665 (transformZExtICmp(LHS, CI, false) ||
8666 transformZExtICmp(RHS, CI, false))) {
8667 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8668 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008669 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008670 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008671 }
8672
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008673 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008674 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8675 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8676 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8677 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008678 if (TI0->getType() == CI.getType())
8679 return
8680 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008681 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008682 }
8683
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008684 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8685 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8686 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8687 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8688 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8689 And->getOperand(1) == C)
8690 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8691 Value *TI0 = TI->getOperand(0);
8692 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008693 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008694 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8695 InsertNewInstBefore(NewAnd, *And);
8696 return BinaryOperator::CreateXor(NewAnd, ZC);
8697 }
8698 }
8699
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008700 return 0;
8701}
8702
8703Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8704 if (Instruction *I = commonIntCastTransforms(CI))
8705 return I;
8706
8707 Value *Src = CI.getOperand(0);
8708
Dan Gohman35b76162008-10-30 20:40:10 +00008709 // Canonicalize sign-extend from i1 to a select.
Owen Anderson35b47072009-08-13 21:58:54 +00008710 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman35b76162008-10-30 20:40:10 +00008711 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008712 Constant::getAllOnesValue(CI.getType()),
8713 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008714
8715 // See if the value being truncated is already sign extended. If so, just
8716 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008717 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008718 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008719 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8720 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8721 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008722 unsigned NumSignBits = ComputeNumSignBits(Op);
8723
8724 if (OpBits == DestBits) {
8725 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8726 // bits, it is already ready.
8727 if (NumSignBits > DestBits-MidBits)
8728 return ReplaceInstUsesWith(CI, Op);
8729 } else if (OpBits < DestBits) {
8730 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8731 // bits, just sext from i32.
8732 if (NumSignBits > OpBits-MidBits)
8733 return new SExtInst(Op, CI.getType(), "tmp");
8734 } else {
8735 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8736 // bits, just truncate to i32.
8737 if (NumSignBits > OpBits-MidBits)
8738 return new TruncInst(Op, CI.getType(), "tmp");
8739 }
8740 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008741
8742 // If the input is a shl/ashr pair of a same constant, then this is a sign
8743 // extension from a smaller value. If we could trust arbitrary bitwidth
8744 // integers, we could turn this into a truncate to the smaller bit and then
8745 // use a sext for the whole extension. Since we don't, look deeper and check
8746 // for a truncate. If the source and dest are the same type, eliminate the
8747 // trunc and extend and just do shifts. For example, turn:
8748 // %a = trunc i32 %i to i8
8749 // %b = shl i8 %a, 6
8750 // %c = ashr i8 %b, 6
8751 // %d = sext i8 %c to i32
8752 // into:
8753 // %a = shl i32 %i, 30
8754 // %d = ashr i32 %a, 30
8755 Value *A = 0;
8756 ConstantInt *BA = 0, *CA = 0;
8757 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohmancdff2122009-08-12 16:23:25 +00008758 m_ConstantInt(CA))) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008759 BA == CA && isa<TruncInst>(A)) {
8760 Value *I = cast<TruncInst>(A)->getOperand(0);
8761 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008762 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8763 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008764 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008765 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner8a2d0592008-08-06 07:35:52 +00008766 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8767 CI.getName()), CI);
8768 return BinaryOperator::CreateAShr(I, ShAmtV);
8769 }
8770 }
8771
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008772 return 0;
8773}
8774
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008775/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8776/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008777static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008778 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008779 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008780 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008781 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8782 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008783 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008784 return 0;
8785}
8786
8787/// LookThroughFPExtensions - If this is an fp extension instruction, look
8788/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008789static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008790 if (Instruction *I = dyn_cast<Instruction>(V))
8791 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008792 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008793
8794 // If this value is a constant, return the constant in the smallest FP type
8795 // that can accurately represent it. This allows us to turn
8796 // (float)((double)X+2.0) into x+2.0f.
8797 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +00008798 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008799 return V; // No constant folding of this.
8800 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008801 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008802 return V;
Owen Anderson35b47072009-08-13 21:58:54 +00008803 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008804 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008805 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008806 return V;
8807 // Don't try to shrink to various long double types.
8808 }
8809
8810 return V;
8811}
8812
8813Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8814 if (Instruction *I = commonCastTransforms(CI))
8815 return I;
8816
Dan Gohman7ce405e2009-06-04 22:49:04 +00008817 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008818 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008819 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008820 // many builtins (sqrt, etc).
8821 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8822 if (OpI && OpI->hasOneUse()) {
8823 switch (OpI->getOpcode()) {
8824 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008825 case Instruction::FAdd:
8826 case Instruction::FSub:
8827 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008828 case Instruction::FDiv:
8829 case Instruction::FRem:
8830 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008831 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8832 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008833 if (LHSTrunc->getType() != SrcTy &&
8834 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008835 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008836 // If the source types were both smaller than the destination type of
8837 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008838 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8839 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008840 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8841 CI.getType(), CI);
8842 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8843 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008844 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008845 }
8846 }
8847 break;
8848 }
8849 }
8850 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008851}
8852
8853Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8854 return commonCastTransforms(CI);
8855}
8856
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008857Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008858 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8859 if (OpI == 0)
8860 return commonCastTransforms(FI);
8861
8862 // fptoui(uitofp(X)) --> X
8863 // fptoui(sitofp(X)) --> X
8864 // This is safe if the intermediate type has enough bits in its mantissa to
8865 // accurately represent all values of X. For example, do not do this with
8866 // i64->float->i64. This is also safe for sitofp case, because any negative
8867 // 'X' value would cause an undefined result for the fptoui.
8868 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8869 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008870 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008871 OpI->getType()->getFPMantissaWidth())
8872 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008873
8874 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008875}
8876
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008877Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008878 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8879 if (OpI == 0)
8880 return commonCastTransforms(FI);
8881
8882 // fptosi(sitofp(X)) --> X
8883 // fptosi(uitofp(X)) --> X
8884 // This is safe if the intermediate type has enough bits in its mantissa to
8885 // accurately represent all values of X. For example, do not do this with
8886 // i64->float->i64. This is also safe for sitofp case, because any negative
8887 // 'X' value would cause an undefined result for the fptoui.
8888 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8889 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008890 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008891 OpI->getType()->getFPMantissaWidth())
8892 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008893
8894 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008895}
8896
8897Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8898 return commonCastTransforms(CI);
8899}
8900
8901Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8902 return commonCastTransforms(CI);
8903}
8904
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008905Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8906 // If the destination integer type is smaller than the intptr_t type for
8907 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8908 // trunc to be exposed to other transforms. Don't do this for extending
8909 // ptrtoint's, because we don't know if the target sign or zero extends its
8910 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008911 if (TD &&
8912 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008913 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
Owen Anderson35b47072009-08-13 21:58:54 +00008914 TD->getIntPtrType(CI.getContext()),
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008915 "tmp"), CI);
8916 return new TruncInst(P, CI.getType());
8917 }
8918
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008919 return commonPointerCastTransforms(CI);
8920}
8921
Chris Lattner7c1626482008-01-08 07:23:51 +00008922Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008923 // If the source integer type is larger than the intptr_t type for
8924 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8925 // allows the trunc to be exposed to other transforms. Don't do this for
8926 // extending inttoptr's, because we don't know if the target sign or zero
8927 // extends to pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008928 if (TD &&
8929 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008930 TD->getPointerSizeInBits()) {
8931 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
Owen Anderson35b47072009-08-13 21:58:54 +00008932 TD->getIntPtrType(CI.getContext()),
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008933 "tmp"), CI);
8934 return new IntToPtrInst(P, CI.getType());
8935 }
8936
Chris Lattner7c1626482008-01-08 07:23:51 +00008937 if (Instruction *I = commonCastTransforms(CI))
8938 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008939
Chris Lattner7c1626482008-01-08 07:23:51 +00008940 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008941}
8942
8943Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8944 // If the operands are integer typed then apply the integer transforms,
8945 // otherwise just apply the common ones.
8946 Value *Src = CI.getOperand(0);
8947 const Type *SrcTy = Src->getType();
8948 const Type *DestTy = CI.getType();
8949
Eli Friedman5013d3f2009-07-13 20:53:00 +00008950 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008951 if (Instruction *I = commonPointerCastTransforms(CI))
8952 return I;
8953 } else {
8954 if (Instruction *Result = commonCastTransforms(CI))
8955 return Result;
8956 }
8957
8958
8959 // Get rid of casts from one type to the same type. These are useless and can
8960 // be replaced by the operand.
8961 if (DestTy == Src->getType())
8962 return ReplaceInstUsesWith(CI, Src);
8963
8964 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8965 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8966 const Type *DstElTy = DstPTy->getElementType();
8967 const Type *SrcElTy = SrcPTy->getElementType();
8968
Nate Begemandf5b3612008-03-31 00:22:16 +00008969 // If the address spaces don't match, don't eliminate the bitcast, which is
8970 // required for changing types.
8971 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8972 return 0;
8973
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008974 // If we are casting a malloc or alloca to a pointer to a type of the same
8975 // size, rewrite the allocation instruction to allocate the "right" type.
8976 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8977 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8978 return V;
8979
8980 // If the source and destination are pointers, and this cast is equivalent
8981 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8982 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson35b47072009-08-13 21:58:54 +00008983 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008984 unsigned NumZeros = 0;
8985 while (SrcElTy != DstElTy &&
8986 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8987 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8988 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8989 ++NumZeros;
8990 }
8991
8992 // If we found a path from the src to dest, create the getelementptr now.
8993 if (SrcElTy == DstElTy) {
8994 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohman17f46f72009-07-28 01:40:03 +00008995 Instruction *GEP = GetElementPtrInst::Create(Src,
8996 Idxs.begin(), Idxs.end(), "",
8997 ((Instruction*) NULL));
8998 cast<GEPOperator>(GEP)->setIsInBounds(true);
8999 return GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009000 }
9001 }
9002
Eli Friedman1d31dee2009-07-18 23:06:53 +00009003 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9004 if (DestVTy->getNumElements() == 1) {
9005 if (!isa<VectorType>(SrcTy)) {
9006 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9007 DestVTy->getElementType(), CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00009008 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson35b47072009-08-13 21:58:54 +00009009 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009010 }
9011 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9012 }
9013 }
9014
9015 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9016 if (SrcVTy->getNumElements() == 1) {
9017 if (!isa<VectorType>(DestTy)) {
9018 Instruction *Elem =
Owen Anderson35b47072009-08-13 21:58:54 +00009019 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009020 InsertNewInstBefore(Elem, CI);
9021 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9022 }
9023 }
9024 }
9025
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009026 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9027 if (SVI->hasOneUse()) {
9028 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9029 // a bitconvert to a vector with the same # elts.
9030 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009031 cast<VectorType>(DestTy)->getNumElements() ==
9032 SVI->getType()->getNumElements() &&
9033 SVI->getType()->getNumElements() ==
9034 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009035 CastInst *Tmp;
9036 // If either of the operands is a cast from CI.getType(), then
9037 // evaluating the shuffle in the casted destination's type will allow
9038 // us to eliminate at least one cast.
9039 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9040 Tmp->getOperand(0)->getType() == DestTy) ||
9041 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9042 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00009043 Value *LHS = InsertCastBefore(Instruction::BitCast,
9044 SVI->getOperand(0), DestTy, CI);
9045 Value *RHS = InsertCastBefore(Instruction::BitCast,
9046 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009047 // Return a new shuffle vector. Use the same element ID's, as we
9048 // know the vector types match #elts.
9049 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9050 }
9051 }
9052 }
9053 }
9054 return 0;
9055}
9056
9057/// GetSelectFoldableOperands - We want to turn code that looks like this:
9058/// %C = or %A, %B
9059/// %D = select %cond, %C, %A
9060/// into:
9061/// %C = select %cond, %B, 0
9062/// %D = or %A, %C
9063///
9064/// Assuming that the specified instruction is an operand to the select, return
9065/// a bitmask indicating which operands of this instruction are foldable if they
9066/// equal the other incoming value of the select.
9067///
9068static unsigned GetSelectFoldableOperands(Instruction *I) {
9069 switch (I->getOpcode()) {
9070 case Instruction::Add:
9071 case Instruction::Mul:
9072 case Instruction::And:
9073 case Instruction::Or:
9074 case Instruction::Xor:
9075 return 3; // Can fold through either operand.
9076 case Instruction::Sub: // Can only fold on the amount subtracted.
9077 case Instruction::Shl: // Can only fold on the shift amount.
9078 case Instruction::LShr:
9079 case Instruction::AShr:
9080 return 1;
9081 default:
9082 return 0; // Cannot fold
9083 }
9084}
9085
9086/// GetSelectFoldableConstant - For the same transformation as the previous
9087/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009088static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009089 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009090 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009091 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009092 case Instruction::Add:
9093 case Instruction::Sub:
9094 case Instruction::Or:
9095 case Instruction::Xor:
9096 case Instruction::Shl:
9097 case Instruction::LShr:
9098 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009099 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009100 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009101 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009102 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009103 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009104 }
9105}
9106
9107/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9108/// have the same opcode and only one use each. Try to simplify this.
9109Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9110 Instruction *FI) {
9111 if (TI->getNumOperands() == 1) {
9112 // If this is a non-volatile load or a cast from the same type,
9113 // merge.
9114 if (TI->isCast()) {
9115 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9116 return 0;
9117 } else {
9118 return 0; // unknown unary op.
9119 }
9120
9121 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009122 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009123 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009124 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009125 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009126 TI->getType());
9127 }
9128
9129 // Only handle binary operators here.
9130 if (!isa<BinaryOperator>(TI))
9131 return 0;
9132
9133 // Figure out if the operations have any operands in common.
9134 Value *MatchOp, *OtherOpT, *OtherOpF;
9135 bool MatchIsOpZero;
9136 if (TI->getOperand(0) == FI->getOperand(0)) {
9137 MatchOp = TI->getOperand(0);
9138 OtherOpT = TI->getOperand(1);
9139 OtherOpF = FI->getOperand(1);
9140 MatchIsOpZero = true;
9141 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9142 MatchOp = TI->getOperand(1);
9143 OtherOpT = TI->getOperand(0);
9144 OtherOpF = FI->getOperand(0);
9145 MatchIsOpZero = false;
9146 } else if (!TI->isCommutative()) {
9147 return 0;
9148 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9149 MatchOp = TI->getOperand(0);
9150 OtherOpT = TI->getOperand(1);
9151 OtherOpF = FI->getOperand(0);
9152 MatchIsOpZero = true;
9153 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9154 MatchOp = TI->getOperand(1);
9155 OtherOpT = TI->getOperand(0);
9156 OtherOpF = FI->getOperand(1);
9157 MatchIsOpZero = true;
9158 } else {
9159 return 0;
9160 }
9161
9162 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009163 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9164 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009165 InsertNewInstBefore(NewSI, SI);
9166
9167 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9168 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009169 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009170 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009171 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009172 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009173 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009174 return 0;
9175}
9176
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009177static bool isSelect01(Constant *C1, Constant *C2) {
9178 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9179 if (!C1I)
9180 return false;
9181 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9182 if (!C2I)
9183 return false;
9184 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9185}
9186
9187/// FoldSelectIntoOp - Try fold the select into one of the operands to
9188/// facilitate further optimization.
9189Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9190 Value *FalseVal) {
9191 // See the comment above GetSelectFoldableOperands for a description of the
9192 // transformation we are doing here.
9193 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9194 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9195 !isa<Constant>(FalseVal)) {
9196 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9197 unsigned OpToFold = 0;
9198 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9199 OpToFold = 1;
9200 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9201 OpToFold = 2;
9202 }
9203
9204 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009205 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009206 Value *OOp = TVI->getOperand(2-OpToFold);
9207 // Avoid creating select between 2 constants unless it's selecting
9208 // between 0 and 1.
9209 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9210 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9211 InsertNewInstBefore(NewSel, SI);
9212 NewSel->takeName(TVI);
9213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9214 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009215 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009216 }
9217 }
9218 }
9219 }
9220 }
9221
9222 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9223 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9224 !isa<Constant>(TrueVal)) {
9225 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9226 unsigned OpToFold = 0;
9227 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9228 OpToFold = 1;
9229 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9230 OpToFold = 2;
9231 }
9232
9233 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009234 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009235 Value *OOp = FVI->getOperand(2-OpToFold);
9236 // Avoid creating select between 2 constants unless it's selecting
9237 // between 0 and 1.
9238 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9239 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9240 InsertNewInstBefore(NewSel, SI);
9241 NewSel->takeName(FVI);
9242 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9243 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009244 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009245 }
9246 }
9247 }
9248 }
9249 }
9250
9251 return 0;
9252}
9253
Dan Gohman58c09632008-09-16 18:46:06 +00009254/// visitSelectInstWithICmp - Visit a SelectInst that has an
9255/// ICmpInst as its first operand.
9256///
9257Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9258 ICmpInst *ICI) {
9259 bool Changed = false;
9260 ICmpInst::Predicate Pred = ICI->getPredicate();
9261 Value *CmpLHS = ICI->getOperand(0);
9262 Value *CmpRHS = ICI->getOperand(1);
9263 Value *TrueVal = SI.getTrueValue();
9264 Value *FalseVal = SI.getFalseValue();
9265
9266 // Check cases where the comparison is with a constant that
9267 // can be adjusted to fit the min/max idiom. We may edit ICI in
9268 // place here, so make sure the select is the only user.
9269 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009270 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009271 switch (Pred) {
9272 default: break;
9273 case ICmpInst::ICMP_ULT:
9274 case ICmpInst::ICMP_SLT: {
9275 // X < MIN ? T : F --> F
9276 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9277 return ReplaceInstUsesWith(SI, FalseVal);
9278 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009279 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009280 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9281 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9282 Pred = ICmpInst::getSwappedPredicate(Pred);
9283 CmpRHS = AdjustedRHS;
9284 std::swap(FalseVal, TrueVal);
9285 ICI->setPredicate(Pred);
9286 ICI->setOperand(1, CmpRHS);
9287 SI.setOperand(1, TrueVal);
9288 SI.setOperand(2, FalseVal);
9289 Changed = true;
9290 }
9291 break;
9292 }
9293 case ICmpInst::ICMP_UGT:
9294 case ICmpInst::ICMP_SGT: {
9295 // X > MAX ? T : F --> F
9296 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9297 return ReplaceInstUsesWith(SI, FalseVal);
9298 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohmanfe91cd62009-08-12 16:04:34 +00009299 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman58c09632008-09-16 18:46:06 +00009300 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9301 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9302 Pred = ICmpInst::getSwappedPredicate(Pred);
9303 CmpRHS = AdjustedRHS;
9304 std::swap(FalseVal, TrueVal);
9305 ICI->setPredicate(Pred);
9306 ICI->setOperand(1, CmpRHS);
9307 SI.setOperand(1, TrueVal);
9308 SI.setOperand(2, FalseVal);
9309 Changed = true;
9310 }
9311 break;
9312 }
9313 }
9314
Dan Gohman35b76162008-10-30 20:40:10 +00009315 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9316 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009317 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohmancdff2122009-08-12 16:23:25 +00009318 if (match(TrueVal, m_ConstantInt<-1>()) &&
9319 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009320 Pred = ICI->getPredicate();
Dan Gohmancdff2122009-08-12 16:23:25 +00009321 else if (match(TrueVal, m_ConstantInt<0>()) &&
9322 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009323 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9324
Dan Gohman35b76162008-10-30 20:40:10 +00009325 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9326 // If we are just checking for a icmp eq of a single bit and zext'ing it
9327 // to an integer, then shift the bit to the appropriate place and then
9328 // cast to integer to avoid the comparison.
9329 const APInt &Op1CV = CI->getValue();
9330
9331 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9332 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9333 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009334 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009335 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009336 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009337 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009338 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009339 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009340 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009341 if (In->getType() != SI.getType())
9342 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009343 true/*SExt*/, "tmp", ICI);
9344
9345 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohmancdff2122009-08-12 16:23:25 +00009346 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman35b76162008-10-30 20:40:10 +00009347 In->getName()+".not"), *ICI);
9348
9349 return ReplaceInstUsesWith(SI, In);
9350 }
9351 }
9352 }
9353
Dan Gohman58c09632008-09-16 18:46:06 +00009354 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9355 // Transform (X == Y) ? X : Y -> Y
9356 if (Pred == ICmpInst::ICMP_EQ)
9357 return ReplaceInstUsesWith(SI, FalseVal);
9358 // Transform (X != Y) ? X : Y -> X
9359 if (Pred == ICmpInst::ICMP_NE)
9360 return ReplaceInstUsesWith(SI, TrueVal);
9361 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9362
9363 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9364 // Transform (X == Y) ? Y : X -> X
9365 if (Pred == ICmpInst::ICMP_EQ)
9366 return ReplaceInstUsesWith(SI, FalseVal);
9367 // Transform (X != Y) ? Y : X -> Y
9368 if (Pred == ICmpInst::ICMP_NE)
9369 return ReplaceInstUsesWith(SI, TrueVal);
9370 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9371 }
9372
9373 /// NOTE: if we wanted to, this is where to detect integer ABS
9374
9375 return Changed ? &SI : 0;
9376}
9377
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009378Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9379 Value *CondVal = SI.getCondition();
9380 Value *TrueVal = SI.getTrueValue();
9381 Value *FalseVal = SI.getFalseValue();
9382
9383 // select true, X, Y -> X
9384 // select false, X, Y -> Y
9385 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9386 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9387
9388 // select C, X, X -> X
9389 if (TrueVal == FalseVal)
9390 return ReplaceInstUsesWith(SI, TrueVal);
9391
9392 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9393 return ReplaceInstUsesWith(SI, FalseVal);
9394 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9395 return ReplaceInstUsesWith(SI, TrueVal);
9396 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9397 if (isa<Constant>(TrueVal))
9398 return ReplaceInstUsesWith(SI, TrueVal);
9399 else
9400 return ReplaceInstUsesWith(SI, FalseVal);
9401 }
9402
Owen Anderson35b47072009-08-13 21:58:54 +00009403 if (SI.getType() == Type::getInt1Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009404 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9405 if (C->getZExtValue()) {
9406 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009407 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009408 } else {
9409 // Change: A = select B, false, C --> A = and !B, C
9410 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009411 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009412 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009413 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009414 }
9415 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9416 if (C->getZExtValue() == false) {
9417 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009418 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009419 } else {
9420 // Change: A = select B, C, true --> A = or !B, C
9421 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009422 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009423 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009424 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009425 }
9426 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009427
9428 // select a, b, a -> a&b
9429 // select a, a, b -> a|b
9430 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009431 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009432 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009433 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009434 }
9435
9436 // Selecting between two integer constants?
9437 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9438 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9439 // select C, 1, 0 -> zext C to int
9440 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009441 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009442 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9443 // select C, 0, 1 -> zext !C to int
9444 Value *NotCond =
Dan Gohmancdff2122009-08-12 16:23:25 +00009445 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009446 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009447 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009448 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449
9450 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009451 // If one of the constants is zero (we know they can't both be) and we
9452 // have an icmp instruction with zero, and we have an 'and' with the
9453 // non-constant value, eliminate this whole mess. This corresponds to
9454 // cases like this: ((X & 27) ? 27 : 0)
9455 if (TrueValC->isZero() || FalseValC->isZero())
9456 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9457 cast<Constant>(IC->getOperand(1))->isNullValue())
9458 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9459 if (ICA->getOpcode() == Instruction::And &&
9460 isa<ConstantInt>(ICA->getOperand(1)) &&
9461 (ICA->getOperand(1) == TrueValC ||
9462 ICA->getOperand(1) == FalseValC) &&
9463 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9464 // Okay, now we know that everything is set up, we just don't
9465 // know whether we have a icmp_ne or icmp_eq and whether the
9466 // true or false val is the zero.
9467 bool ShouldNotVal = !TrueValC->isZero();
9468 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9469 Value *V = ICA;
9470 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009471 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009472 Instruction::Xor, V, ICA->getOperand(1)), SI);
9473 return ReplaceInstUsesWith(SI, V);
9474 }
9475 }
9476 }
9477
9478 // See if we are selecting two values based on a comparison of the two values.
9479 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9480 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9481 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009482 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9483 // This is not safe in general for floating point:
9484 // consider X== -0, Y== +0.
9485 // It becomes safe if either operand is a nonzero constant.
9486 ConstantFP *CFPt, *CFPf;
9487 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9488 !CFPt->getValueAPF().isZero()) ||
9489 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9490 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009491 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009492 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009493 // Transform (X != Y) ? X : Y -> X
9494 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9495 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009496 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009497
9498 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9499 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009500 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9501 // This is not safe in general for floating point:
9502 // consider X== -0, Y== +0.
9503 // It becomes safe if either operand is a nonzero constant.
9504 ConstantFP *CFPt, *CFPf;
9505 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9506 !CFPt->getValueAPF().isZero()) ||
9507 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9508 !CFPf->getValueAPF().isZero()))
9509 return ReplaceInstUsesWith(SI, FalseVal);
9510 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009511 // Transform (X != Y) ? Y : X -> Y
9512 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9513 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009514 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009515 }
Dan Gohman58c09632008-09-16 18:46:06 +00009516 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009517 }
9518
9519 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009520 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9521 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9522 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009523
9524 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9525 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9526 if (TI->hasOneUse() && FI->hasOneUse()) {
9527 Instruction *AddOp = 0, *SubOp = 0;
9528
9529 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9530 if (TI->getOpcode() == FI->getOpcode())
9531 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9532 return IV;
9533
9534 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9535 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009536 if ((TI->getOpcode() == Instruction::Sub &&
9537 FI->getOpcode() == Instruction::Add) ||
9538 (TI->getOpcode() == Instruction::FSub &&
9539 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009540 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009541 } else if ((FI->getOpcode() == Instruction::Sub &&
9542 TI->getOpcode() == Instruction::Add) ||
9543 (FI->getOpcode() == Instruction::FSub &&
9544 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009545 AddOp = TI; SubOp = FI;
9546 }
9547
9548 if (AddOp) {
9549 Value *OtherAddOp = 0;
9550 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9551 OtherAddOp = AddOp->getOperand(1);
9552 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9553 OtherAddOp = AddOp->getOperand(0);
9554 }
9555
9556 if (OtherAddOp) {
9557 // So at this point we know we have (Y -> OtherAddOp):
9558 // select C, (add X, Y), (sub X, Z)
9559 Value *NegVal; // Compute -Z
9560 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009561 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009562 } else {
9563 NegVal = InsertNewInstBefore(
Dan Gohmancdff2122009-08-12 16:23:25 +00009564 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson15b39322009-07-13 04:09:18 +00009565 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009566 }
9567
9568 Value *NewTrueOp = OtherAddOp;
9569 Value *NewFalseOp = NegVal;
9570 if (AddOp != TI)
9571 std::swap(NewTrueOp, NewFalseOp);
9572 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009573 SelectInst::Create(CondVal, NewTrueOp,
9574 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009575
9576 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009577 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009578 }
9579 }
9580 }
9581
9582 // See if we can fold the select into one of our operands.
9583 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009584 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9585 if (FoldI)
9586 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009587 }
9588
9589 if (BinaryOperator::isNot(CondVal)) {
9590 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9591 SI.setOperand(1, FalseVal);
9592 SI.setOperand(2, TrueVal);
9593 return &SI;
9594 }
9595
9596 return 0;
9597}
9598
Dan Gohman2d648bb2008-04-10 18:43:06 +00009599/// EnforceKnownAlignment - If the specified pointer points to an object that
9600/// we control, modify the object's alignment to PrefAlign. This isn't
9601/// often possible though. If alignment is important, a more reliable approach
9602/// is to simply align all global variables and allocation instructions to
9603/// their preferred alignment from the beginning.
9604///
9605static unsigned EnforceKnownAlignment(Value *V,
9606 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009607
Dan Gohman2d648bb2008-04-10 18:43:06 +00009608 User *U = dyn_cast<User>(V);
9609 if (!U) return Align;
9610
Dan Gohman9545fb02009-07-17 20:47:02 +00009611 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009612 default: break;
9613 case Instruction::BitCast:
9614 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9615 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009616 // If all indexes are zero, it is just the alignment of the base pointer.
9617 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009618 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009619 if (!isa<Constant>(*i) ||
9620 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009621 AllZeroOperands = false;
9622 break;
9623 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009624
9625 if (AllZeroOperands) {
9626 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009627 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009628 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009629 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009630 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009631 }
9632
9633 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9634 // If there is a large requested alignment and we can, bump up the alignment
9635 // of the global.
9636 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009637 if (GV->getAlignment() >= PrefAlign)
9638 Align = GV->getAlignment();
9639 else {
9640 GV->setAlignment(PrefAlign);
9641 Align = PrefAlign;
9642 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009643 }
9644 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9645 // If there is a requested alignment and if this is an alloca, round up. We
9646 // don't do this for malloc, because some systems can't respect the request.
9647 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009648 if (AI->getAlignment() >= PrefAlign)
9649 Align = AI->getAlignment();
9650 else {
9651 AI->setAlignment(PrefAlign);
9652 Align = PrefAlign;
9653 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009654 }
9655 }
9656
9657 return Align;
9658}
9659
9660/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9661/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9662/// and it is more than the alignment of the ultimate object, see if we can
9663/// increase the alignment of the ultimate object, making this check succeed.
9664unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9665 unsigned PrefAlign) {
9666 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9667 sizeof(PrefAlign) * CHAR_BIT;
9668 APInt Mask = APInt::getAllOnesValue(BitWidth);
9669 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9670 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9671 unsigned TrailZ = KnownZero.countTrailingOnes();
9672 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9673
9674 if (PrefAlign > Align)
9675 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9676
9677 // We don't need to make any adjustment.
9678 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009679}
9680
Chris Lattner00ae5132008-01-13 23:50:23 +00009681Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009682 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009683 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009684 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009685 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009686
9687 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009688 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009689 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009690 return MI;
9691 }
9692
9693 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9694 // load/store.
9695 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9696 if (MemOpLength == 0) return 0;
9697
Chris Lattnerc669fb62008-01-14 00:28:35 +00009698 // Source and destination pointer types are always "i8*" for intrinsic. See
9699 // if the size is something we can handle with a single primitive load/store.
9700 // A single load+store correctly handles overlapping memory in the memmove
9701 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009702 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009703 if (Size == 0) return MI; // Delete this mem transfer.
9704
9705 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009706 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009707
Chris Lattnerc669fb62008-01-14 00:28:35 +00009708 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009709 Type *NewPtrTy =
Owen Anderson35b47072009-08-13 21:58:54 +00009710 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009711
9712 // Memcpy forces the use of i8* for the source and destination. That means
9713 // that if you're using memcpy to move one double around, you'll get a cast
9714 // from double* to i8*. We'd much rather use a double load+store rather than
9715 // an i64 load+store, here because this improves the odds that the source or
9716 // dest address will be promotable. See if we can find a better type than the
9717 // integer datatype.
9718 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9719 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009720 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009721 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9722 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009723 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009724 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9725 if (STy->getNumElements() == 1)
9726 SrcETy = STy->getElementType(0);
9727 else
9728 break;
9729 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9730 if (ATy->getNumElements() == 1)
9731 SrcETy = ATy->getElementType();
9732 else
9733 break;
9734 } else
9735 break;
9736 }
9737
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009738 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009739 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009740 }
9741 }
9742
9743
Chris Lattner00ae5132008-01-13 23:50:23 +00009744 // If the memcpy/memmove provides better alignment info than we can
9745 // infer, use it.
9746 SrcAlign = std::max(SrcAlign, CopyAlign);
9747 DstAlign = std::max(DstAlign, CopyAlign);
9748
9749 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9750 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009751 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9752 InsertNewInstBefore(L, *MI);
9753 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9754
9755 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009756 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009757 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009758}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009759
Chris Lattner5af8a912008-04-30 06:39:11 +00009760Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9761 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009762 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009763 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009764 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009765 return MI;
9766 }
9767
9768 // Extract the length and alignment and fill if they are constant.
9769 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9770 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson35b47072009-08-13 21:58:54 +00009771 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner5af8a912008-04-30 06:39:11 +00009772 return 0;
9773 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009774 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009775
9776 // If the length is zero, this is a no-op
9777 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9778
9779 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9780 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson35b47072009-08-13 21:58:54 +00009781 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009782
9783 Value *Dest = MI->getDest();
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009784 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009785
9786 // Alignment 0 is identity for alignment 1 for memset, but not store.
9787 if (Alignment == 0) Alignment = 1;
9788
9789 // Extract the fill value and store.
9790 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009791 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009792 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009793
9794 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009795 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009796 return MI;
9797 }
9798
9799 return 0;
9800}
9801
9802
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009803/// visitCallInst - CallInst simplification. This mostly only handles folding
9804/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9805/// the heavy lifting.
9806///
9807Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009808 // If the caller function is nounwind, mark the call as nounwind, even if the
9809 // callee isn't.
9810 if (CI.getParent()->getParent()->doesNotThrow() &&
9811 !CI.doesNotThrow()) {
9812 CI.setDoesNotThrow();
9813 return &CI;
9814 }
9815
9816
9817
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009818 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9819 if (!II) return visitCallSite(&CI);
9820
9821 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9822 // visitCallSite.
9823 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9824 bool Changed = false;
9825
9826 // memmove/cpy/set of zero bytes is a noop.
9827 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9828 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9829
9830 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9831 if (CI->getZExtValue() == 1) {
9832 // Replace the instruction with just byte operations. We would
9833 // transform other cases to loads/stores, but we don't know if
9834 // alignment is sufficient.
9835 }
9836 }
9837
9838 // If we have a memmove and the source operation is a constant global,
9839 // then the source and dest pointers can't alias, so we can change this
9840 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009841 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009842 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9843 if (GVSrc->isConstant()) {
9844 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009845 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9846 const Type *Tys[1];
9847 Tys[0] = CI.getOperand(3)->getType();
9848 CI.setOperand(0,
9849 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009850 Changed = true;
9851 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009852
9853 // memmove(x,x,size) -> noop.
9854 if (MMI->getSource() == MMI->getDest())
9855 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009856 }
9857
9858 // If we can determine a pointer alignment that is bigger than currently
9859 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009860 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009861 if (Instruction *I = SimplifyMemTransfer(MI))
9862 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009863 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9864 if (Instruction *I = SimplifyMemSet(MSI))
9865 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009866 }
9867
9868 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009869 }
9870
9871 switch (II->getIntrinsicID()) {
9872 default: break;
9873 case Intrinsic::bswap:
9874 // bswap(bswap(x)) -> x
9875 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9876 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9877 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9878 break;
9879 case Intrinsic::ppc_altivec_lvx:
9880 case Intrinsic::ppc_altivec_lvxl:
9881 case Intrinsic::x86_sse_loadu_ps:
9882 case Intrinsic::x86_sse2_loadu_pd:
9883 case Intrinsic::x86_sse2_loadu_dq:
9884 // Turn PPC lvx -> load if the pointer is known aligned.
9885 // Turn X86 loadups -> load if the pointer is known aligned.
9886 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9887 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009888 PointerType::getUnqual(II->getType()),
Chris Lattner989ba312008-06-18 04:33:20 +00009889 CI);
9890 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009891 }
Chris Lattner989ba312008-06-18 04:33:20 +00009892 break;
9893 case Intrinsic::ppc_altivec_stvx:
9894 case Intrinsic::ppc_altivec_stvxl:
9895 // Turn stvx -> store if the pointer is known aligned.
9896 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9897 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009898 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009899 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9900 return new StoreInst(II->getOperand(1), Ptr);
9901 }
9902 break;
9903 case Intrinsic::x86_sse_storeu_ps:
9904 case Intrinsic::x86_sse2_storeu_pd:
9905 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009906 // Turn X86 storeu -> store if the pointer is known aligned.
9907 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9908 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009909 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009910 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9911 return new StoreInst(II->getOperand(2), Ptr);
9912 }
9913 break;
9914
9915 case Intrinsic::x86_sse_cvttss2si: {
9916 // These intrinsics only demands the 0th element of its input vector. If
9917 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009918 unsigned VWidth =
9919 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9920 APInt DemandedElts(VWidth, 1);
9921 APInt UndefElts(VWidth, 0);
9922 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009923 UndefElts)) {
9924 II->setOperand(1, V);
9925 return II;
9926 }
9927 break;
9928 }
9929
9930 case Intrinsic::ppc_altivec_vperm:
9931 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9932 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9933 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009934
Chris Lattner989ba312008-06-18 04:33:20 +00009935 // Check that all of the elements are integer constants or undefs.
9936 bool AllEltsOk = true;
9937 for (unsigned i = 0; i != 16; ++i) {
9938 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9939 !isa<UndefValue>(Mask->getOperand(i))) {
9940 AllEltsOk = false;
9941 break;
9942 }
9943 }
9944
9945 if (AllEltsOk) {
9946 // Cast the input vectors to byte vectors.
9947 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9948 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00009949 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009950
Chris Lattner989ba312008-06-18 04:33:20 +00009951 // Only extract each element once.
9952 Value *ExtractedElts[32];
9953 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9954
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009955 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009956 if (isa<UndefValue>(Mask->getOperand(i)))
9957 continue;
9958 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9959 Idx &= 31; // Match the hardware behavior.
9960
9961 if (ExtractedElts[Idx] == 0) {
9962 Instruction *Elt =
Eric Christopher1ba36872009-07-25 02:28:41 +00009963 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Anderson35b47072009-08-13 21:58:54 +00009964 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009965 InsertNewInstBefore(Elt, CI);
9966 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009967 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009968
Chris Lattner989ba312008-06-18 04:33:20 +00009969 // Insert this value into the result vector.
9970 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson35b47072009-08-13 21:58:54 +00009971 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00009972 "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009973 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009974 }
Chris Lattner989ba312008-06-18 04:33:20 +00009975 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009976 }
Chris Lattner989ba312008-06-18 04:33:20 +00009977 }
9978 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009979
Chris Lattner989ba312008-06-18 04:33:20 +00009980 case Intrinsic::stackrestore: {
9981 // If the save is right next to the restore, remove the restore. This can
9982 // happen when variable allocas are DCE'd.
9983 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9984 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9985 BasicBlock::iterator BI = SS;
9986 if (&*++BI == II)
9987 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009988 }
Chris Lattner989ba312008-06-18 04:33:20 +00009989 }
9990
9991 // Scan down this block to see if there is another stack restore in the
9992 // same block without an intervening call/alloca.
9993 BasicBlock::iterator BI = II;
9994 TerminatorInst *TI = II->getParent()->getTerminator();
9995 bool CannotRemove = false;
9996 for (++BI; &*BI != TI; ++BI) {
9997 if (isa<AllocaInst>(BI)) {
9998 CannotRemove = true;
9999 break;
10000 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010001 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10002 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10003 // If there is a stackrestore below this one, remove this one.
10004 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10005 return EraseInstFromFunction(CI);
10006 // Otherwise, ignore the intrinsic.
10007 } else {
10008 // If we found a non-intrinsic call, we can't remove the stack
10009 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010010 CannotRemove = true;
10011 break;
10012 }
Chris Lattner989ba312008-06-18 04:33:20 +000010013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010014 }
Chris Lattner989ba312008-06-18 04:33:20 +000010015
10016 // If the stack restore is in a return/unwind block and if there are no
10017 // allocas or calls between the restore and the return, nuke the restore.
10018 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10019 return EraseInstFromFunction(CI);
10020 break;
10021 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010022 }
10023
10024 return visitCallSite(II);
10025}
10026
10027// InvokeInst simplification
10028//
10029Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10030 return visitCallSite(&II);
10031}
10032
Dale Johannesen96021832008-04-25 21:16:07 +000010033/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10034/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010035static bool isSafeToEliminateVarargsCast(const CallSite CS,
10036 const CastInst * const CI,
10037 const TargetData * const TD,
10038 const int ix) {
10039 if (!CI->isLosslessCast())
10040 return false;
10041
10042 // The size of ByVal arguments is derived from the type, so we
10043 // can't change to a type with a different size. If the size were
10044 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010045 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010046 return true;
10047
10048 const Type* SrcTy =
10049 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10050 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10051 if (!SrcTy->isSized() || !DstTy->isSized())
10052 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010053 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010054 return false;
10055 return true;
10056}
10057
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010058// visitCallSite - Improvements for call and invoke instructions.
10059//
10060Instruction *InstCombiner::visitCallSite(CallSite CS) {
10061 bool Changed = false;
10062
10063 // If the callee is a constexpr cast of a function, attempt to move the cast
10064 // to the arguments of the call/invoke.
10065 if (transformConstExprCastCall(CS)) return 0;
10066
10067 Value *Callee = CS.getCalledValue();
10068
10069 if (Function *CalleeF = dyn_cast<Function>(Callee))
10070 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10071 Instruction *OldCall = CS.getInstruction();
10072 // If the call and callee calling conventions don't match, this call must
10073 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010074 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +000010075 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Anderson24be4c12009-07-03 00:17:18 +000010076 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010077 if (!OldCall->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000010078 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010079 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10080 return EraseInstFromFunction(*OldCall);
10081 return 0;
10082 }
10083
10084 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10085 // This instruction is not reachable, just remove it. We insert a store to
10086 // undef so that we know that this code is not reachable, despite the fact
10087 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010088 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +000010089 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010090 CS.getInstruction());
10091
10092 if (!CS.getInstruction()->use_empty())
10093 CS.getInstruction()->
Owen Andersonb99ecca2009-07-30 23:03:37 +000010094 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010095
10096 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10097 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010098 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010099 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010100 }
10101 return EraseInstFromFunction(*CS.getInstruction());
10102 }
10103
Duncan Sands74833f22007-09-17 10:26:40 +000010104 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10105 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10106 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10107 return transformCallThroughTrampoline(CS);
10108
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010109 const PointerType *PTy = cast<PointerType>(Callee->getType());
10110 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10111 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010112 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010113 // See if we can optimize any arguments passed through the varargs area of
10114 // the call.
10115 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010116 E = CS.arg_end(); I != E; ++I, ++ix) {
10117 CastInst *CI = dyn_cast<CastInst>(*I);
10118 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10119 *I = CI->getOperand(0);
10120 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010121 }
Dale Johannesen35615462008-04-23 18:34:37 +000010122 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010123 }
10124
Duncan Sands2937e352007-12-19 21:13:37 +000010125 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010126 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010127 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010128 Changed = true;
10129 }
10130
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010131 return Changed ? CS.getInstruction() : 0;
10132}
10133
10134// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10135// attempt to move the cast to the arguments of the call/invoke.
10136//
10137bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10138 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10139 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10140 if (CE->getOpcode() != Instruction::BitCast ||
10141 !isa<Function>(CE->getOperand(0)))
10142 return false;
10143 Function *Callee = cast<Function>(CE->getOperand(0));
10144 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010145 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010146
10147 // Okay, this is a cast from a function to a different type. Unless doing so
10148 // would cause a type conversion of one of our arguments, change this call to
10149 // be a direct call with arguments casted to the appropriate types.
10150 //
10151 const FunctionType *FT = Callee->getFunctionType();
10152 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010153 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010154
Duncan Sands7901ce12008-06-01 07:38:42 +000010155 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010156 return false; // TODO: Handle multiple return values.
10157
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010158 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010159 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010160 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010161 // Conversion is ok if changing from one pointer type to another or from
10162 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010163 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010164 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000010165 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson35b47072009-08-13 21:58:54 +000010166 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010167 return false; // Cannot transform this return value.
10168
Duncan Sands5c489582008-01-06 10:12:28 +000010169 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010170 // void -> non-void is handled specially
Owen Anderson35b47072009-08-13 21:58:54 +000010171 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010172 return false; // Cannot transform this return value.
10173
Chris Lattner1c8733e2008-03-12 17:45:29 +000010174 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010175 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010176 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010177 return false; // Attribute not compatible with transformed value.
10178 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010179
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010180 // If the callsite is an invoke instruction, and the return value is used by
10181 // a PHI node in a successor, we cannot change the return type of the call
10182 // because there is no place to put the cast instruction (without breaking
10183 // the critical edge). Bail out in this case.
10184 if (!Caller->use_empty())
10185 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10186 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10187 UI != E; ++UI)
10188 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10189 if (PN->getParent() == II->getNormalDest() ||
10190 PN->getParent() == II->getUnwindDest())
10191 return false;
10192 }
10193
10194 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10195 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10196
10197 CallSite::arg_iterator AI = CS.arg_begin();
10198 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10199 const Type *ParamTy = FT->getParamType(i);
10200 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010201
10202 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010203 return false; // Cannot transform this parameter value.
10204
Devang Patelf2a4a922008-09-26 22:53:05 +000010205 if (CallerPAL.getParamAttributes(i + 1)
10206 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010207 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010208
Duncan Sands7901ce12008-06-01 07:38:42 +000010209 // Converting from one pointer type to another or between a pointer and an
10210 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010211 bool isConvertible = ActTy == ParamTy ||
Owen Anderson35b47072009-08-13 21:58:54 +000010212 (TD && ((isa<PointerType>(ParamTy) ||
10213 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10214 (isa<PointerType>(ActTy) ||
10215 ActTy == TD->getIntPtrType(Caller->getContext()))));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010216 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010217 }
10218
10219 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10220 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010221 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010222
Chris Lattner1c8733e2008-03-12 17:45:29 +000010223 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10224 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010225 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010226 // won't be dropping them. Check that these extra arguments have attributes
10227 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010228 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10229 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010230 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010231 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010232 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010233 return false;
10234 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010235
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010236 // Okay, we decided that this is a safe thing to do: go ahead and start
10237 // inserting cast instructions as necessary...
10238 std::vector<Value*> Args;
10239 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010240 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010241 attrVec.reserve(NumCommonArgs);
10242
10243 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010244 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010245
10246 // If the return value is not being used, the type may not be compatible
10247 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010248 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010249
10250 // Add the new return attributes.
10251 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010252 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010253
10254 AI = CS.arg_begin();
10255 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10256 const Type *ParamTy = FT->getParamType(i);
10257 if ((*AI)->getType() == ParamTy) {
10258 Args.push_back(*AI);
10259 } else {
10260 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10261 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010262 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010263 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10264 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010265
10266 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010267 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010268 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010269 }
10270
10271 // If the function takes more arguments than the call was taking, add them
10272 // now...
10273 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010274 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010275
10276 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010277 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010278 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010279 errs() << "WARNING: While resolving call to function '"
10280 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010281 } else {
10282 // Add all of the arguments in their promoted form to the arg list...
10283 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10284 const Type *PTy = getPromotedType((*AI)->getType());
10285 if (PTy != (*AI)->getType()) {
10286 // Must promote to pass through va_arg area!
10287 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10288 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010289 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010290 InsertNewInstBefore(Cast, *Caller);
10291 Args.push_back(Cast);
10292 } else {
10293 Args.push_back(*AI);
10294 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010295
Duncan Sands4ced1f82008-01-13 08:02:44 +000010296 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010297 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010298 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010299 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010300 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010301 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010302
Devang Patelf2a4a922008-09-26 22:53:05 +000010303 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10304 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10305
Owen Anderson35b47072009-08-13 21:58:54 +000010306 if (NewRetTy == Type::getVoidTy(*Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010307 Caller->setName(""); // Void type should not have a name.
10308
Eric Christopher3e7381f2009-07-25 02:45:27 +000010309 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10310 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010311
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010312 Instruction *NC;
10313 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010314 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010315 Args.begin(), Args.end(),
10316 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010317 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010318 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010319 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010320 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10321 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010322 CallInst *CI = cast<CallInst>(Caller);
10323 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010324 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010325 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010326 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010327 }
10328
10329 // Insert a cast of the return type as necessary.
10330 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010331 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson35b47072009-08-13 21:58:54 +000010332 if (NV->getType() != Type::getVoidTy(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010333 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010334 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010335 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010336
10337 // If this is an invoke instruction, we should insert it after the first
10338 // non-phi, instruction in the normal successor block.
10339 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010340 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010341 InsertNewInstBefore(NC, *I);
10342 } else {
10343 // Otherwise, it's a call, just insert cast right after the call instr
10344 InsertNewInstBefore(NC, *Caller);
10345 }
10346 AddUsersToWorkList(*Caller);
10347 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010348 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010349 }
10350 }
10351
Owen Anderson35b47072009-08-13 21:58:54 +000010352 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010353 Caller->replaceAllUsesWith(NV);
10354 Caller->eraseFromParent();
10355 RemoveFromWorkList(Caller);
10356 return true;
10357}
10358
Duncan Sands74833f22007-09-17 10:26:40 +000010359// transformCallThroughTrampoline - Turn a call to a function created by the
10360// init_trampoline intrinsic into a direct call to the underlying function.
10361//
10362Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10363 Value *Callee = CS.getCalledValue();
10364 const PointerType *PTy = cast<PointerType>(Callee->getType());
10365 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010366 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010367
10368 // If the call already has the 'nest' attribute somewhere then give up -
10369 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010370 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010371 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010372
10373 IntrinsicInst *Tramp =
10374 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10375
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010376 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010377 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10378 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10379
Devang Pateld222f862008-09-25 21:00:45 +000010380 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010381 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010382 unsigned NestIdx = 1;
10383 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010384 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010385
10386 // Look for a parameter marked with the 'nest' attribute.
10387 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10388 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010389 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010390 // Record the parameter type and any other attributes.
10391 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010392 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010393 break;
10394 }
10395
10396 if (NestTy) {
10397 Instruction *Caller = CS.getInstruction();
10398 std::vector<Value*> NewArgs;
10399 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10400
Devang Pateld222f862008-09-25 21:00:45 +000010401 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010402 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010403
Duncan Sands74833f22007-09-17 10:26:40 +000010404 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010405 // mean appending it. Likewise for attributes.
10406
Devang Patelf2a4a922008-09-26 22:53:05 +000010407 // Add any result attributes.
10408 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010409 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010410
Duncan Sands74833f22007-09-17 10:26:40 +000010411 {
10412 unsigned Idx = 1;
10413 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10414 do {
10415 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010416 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010417 Value *NestVal = Tramp->getOperand(3);
10418 if (NestVal->getType() != NestTy)
10419 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10420 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010421 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010422 }
10423
10424 if (I == E)
10425 break;
10426
Duncan Sands48b81112008-01-14 19:52:09 +000010427 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010428 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010429 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010430 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010431 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010432
10433 ++Idx, ++I;
10434 } while (1);
10435 }
10436
Devang Patelf2a4a922008-09-26 22:53:05 +000010437 // Add any function attributes.
10438 if (Attributes Attr = Attrs.getFnAttributes())
10439 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10440
Duncan Sands74833f22007-09-17 10:26:40 +000010441 // The trampoline may have been bitcast to a bogus type (FTy).
10442 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010443 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010444
Duncan Sands74833f22007-09-17 10:26:40 +000010445 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010446 NewTypes.reserve(FTy->getNumParams()+1);
10447
Duncan Sands74833f22007-09-17 10:26:40 +000010448 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010449 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010450 {
10451 unsigned Idx = 1;
10452 FunctionType::param_iterator I = FTy->param_begin(),
10453 E = FTy->param_end();
10454
10455 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010456 if (Idx == NestIdx)
10457 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010458 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010459
10460 if (I == E)
10461 break;
10462
Duncan Sands48b81112008-01-14 19:52:09 +000010463 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010464 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010465
10466 ++Idx, ++I;
10467 } while (1);
10468 }
10469
10470 // Replace the trampoline call with a direct call. Let the generic
10471 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010472 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010473 FTy->isVarArg());
10474 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010475 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010476 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010477 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010478 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10479 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010480
10481 Instruction *NewCaller;
10482 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010483 NewCaller = InvokeInst::Create(NewCallee,
10484 II->getNormalDest(), II->getUnwindDest(),
10485 NewArgs.begin(), NewArgs.end(),
10486 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010487 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010488 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010489 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010490 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10491 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010492 if (cast<CallInst>(Caller)->isTailCall())
10493 cast<CallInst>(NewCaller)->setTailCall();
10494 cast<CallInst>(NewCaller)->
10495 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010496 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010497 }
Owen Anderson35b47072009-08-13 21:58:54 +000010498 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sands74833f22007-09-17 10:26:40 +000010499 Caller->replaceAllUsesWith(NewCaller);
10500 Caller->eraseFromParent();
10501 RemoveFromWorkList(Caller);
10502 return 0;
10503 }
10504 }
10505
10506 // Replace the trampoline call with a direct call. Since there is no 'nest'
10507 // parameter, there is no need to adjust the argument list. Let the generic
10508 // code sort out any function type mismatches.
10509 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010510 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010511 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010512 CS.setCalledFunction(NewCallee);
10513 return CS.getInstruction();
10514}
10515
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010516/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10517/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10518/// and a single binop.
10519Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10520 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010521 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010522 unsigned Opc = FirstInst->getOpcode();
10523 Value *LHSVal = FirstInst->getOperand(0);
10524 Value *RHSVal = FirstInst->getOperand(1);
10525
10526 const Type *LHSType = LHSVal->getType();
10527 const Type *RHSType = RHSVal->getType();
10528
10529 // Scan to see if all operands are the same opcode, all have one use, and all
10530 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010531 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010532 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10533 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10534 // Verify type of the LHS matches so we don't fold cmp's of different
10535 // types or GEP's with different index types.
10536 I->getOperand(0)->getType() != LHSType ||
10537 I->getOperand(1)->getType() != RHSType)
10538 return 0;
10539
10540 // If they are CmpInst instructions, check their predicates
10541 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10542 if (cast<CmpInst>(I)->getPredicate() !=
10543 cast<CmpInst>(FirstInst)->getPredicate())
10544 return 0;
10545
10546 // Keep track of which operand needs a phi node.
10547 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10548 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10549 }
10550
Chris Lattner30078012008-12-01 03:42:51 +000010551 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010552
10553 Value *InLHS = FirstInst->getOperand(0);
10554 Value *InRHS = FirstInst->getOperand(1);
10555 PHINode *NewLHS = 0, *NewRHS = 0;
10556 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010557 NewLHS = PHINode::Create(LHSType,
10558 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010559 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10560 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10561 InsertNewInstBefore(NewLHS, PN);
10562 LHSVal = NewLHS;
10563 }
10564
10565 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010566 NewRHS = PHINode::Create(RHSType,
10567 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010568 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10569 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10570 InsertNewInstBefore(NewRHS, PN);
10571 RHSVal = NewRHS;
10572 }
10573
10574 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010575 if (NewLHS || NewRHS) {
10576 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10577 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10578 if (NewLHS) {
10579 Value *NewInLHS = InInst->getOperand(0);
10580 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10581 }
10582 if (NewRHS) {
10583 Value *NewInRHS = InInst->getOperand(1);
10584 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10585 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010586 }
10587 }
10588
10589 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010590 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010591 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohmane6803b82009-08-25 23:17:54 +000010592 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson6601fcd2009-07-09 23:48:35 +000010593 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010594}
10595
Chris Lattner9e1916e2008-12-01 02:34:36 +000010596Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10597 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10598
10599 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10600 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010601 // This is true if all GEP bases are allocas and if all indices into them are
10602 // constants.
10603 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010604
10605 // Scan to see if all operands are the same opcode, all have one use, and all
10606 // kill their operands (i.e. the operands have one use).
10607 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10608 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10609 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10610 GEP->getNumOperands() != FirstInst->getNumOperands())
10611 return 0;
10612
Chris Lattneradf354b2009-02-21 00:46:50 +000010613 // Keep track of whether or not all GEPs are of alloca pointers.
10614 if (AllBasePointersAreAllocas &&
10615 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10616 !GEP->hasAllConstantIndices()))
10617 AllBasePointersAreAllocas = false;
10618
Chris Lattner9e1916e2008-12-01 02:34:36 +000010619 // Compare the operand lists.
10620 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10621 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10622 continue;
10623
10624 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10625 // if one of the PHIs has a constant for the index. The index may be
10626 // substantially cheaper to compute for the constants, so making it a
10627 // variable index could pessimize the path. This also handles the case
10628 // for struct indices, which must always be constant.
10629 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10630 isa<ConstantInt>(GEP->getOperand(op)))
10631 return 0;
10632
10633 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10634 return 0;
10635 FixedOperands[op] = 0; // Needs a PHI.
10636 }
10637 }
10638
Chris Lattneradf354b2009-02-21 00:46:50 +000010639 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010640 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010641 // offset calculation, but all the predecessors will have to materialize the
10642 // stack address into a register anyway. We'd actually rather *clone* the
10643 // load up into the predecessors so that we have a load of a gep of an alloca,
10644 // which can usually all be folded into the load.
10645 if (AllBasePointersAreAllocas)
10646 return 0;
10647
Chris Lattner9e1916e2008-12-01 02:34:36 +000010648 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10649 // that is variable.
10650 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10651
10652 bool HasAnyPHIs = false;
10653 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10654 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10655 Value *FirstOp = FirstInst->getOperand(i);
10656 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10657 FirstOp->getName()+".pn");
10658 InsertNewInstBefore(NewPN, PN);
10659
10660 NewPN->reserveOperandSpace(e);
10661 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10662 OperandPhis[i] = NewPN;
10663 FixedOperands[i] = NewPN;
10664 HasAnyPHIs = true;
10665 }
10666
10667
10668 // Add all operands to the new PHIs.
10669 if (HasAnyPHIs) {
10670 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10671 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10672 BasicBlock *InBB = PN.getIncomingBlock(i);
10673
10674 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10675 if (PHINode *OpPhi = OperandPhis[op])
10676 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10677 }
10678 }
10679
10680 Value *Base = FixedOperands[0];
Dan Gohman17f46f72009-07-28 01:40:03 +000010681 GetElementPtrInst *GEP =
10682 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10683 FixedOperands.end());
10684 if (cast<GEPOperator>(FirstInst)->isInBounds())
10685 cast<GEPOperator>(GEP)->setIsInBounds(true);
10686 return GEP;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010687}
10688
10689
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010690/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10691/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010692/// obvious the value of the load is not changed from the point of the load to
10693/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010694///
10695/// Finally, it is safe, but not profitable, to sink a load targetting a
10696/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10697/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010698static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010699 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10700
10701 for (++BBI; BBI != E; ++BBI)
10702 if (BBI->mayWriteToMemory())
10703 return false;
10704
10705 // Check for non-address taken alloca. If not address-taken already, it isn't
10706 // profitable to do this xform.
10707 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10708 bool isAddressTaken = false;
10709 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10710 UI != E; ++UI) {
10711 if (isa<LoadInst>(UI)) continue;
10712 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10713 // If storing TO the alloca, then the address isn't taken.
10714 if (SI->getOperand(1) == AI) continue;
10715 }
10716 isAddressTaken = true;
10717 break;
10718 }
10719
Chris Lattneradf354b2009-02-21 00:46:50 +000010720 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010721 return false;
10722 }
10723
Chris Lattneradf354b2009-02-21 00:46:50 +000010724 // If this load is a load from a GEP with a constant offset from an alloca,
10725 // then we don't want to sink it. In its present form, it will be
10726 // load [constant stack offset]. Sinking it will cause us to have to
10727 // materialize the stack addresses in each predecessor in a register only to
10728 // do a shared load from register in the successor.
10729 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10730 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10731 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10732 return false;
10733
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010734 return true;
10735}
10736
10737
10738// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10739// operator and they all are only used by the PHI, PHI together their
10740// inputs, and do the operation once, to the result of the PHI.
10741Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10742 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10743
10744 // Scan the instruction, looking for input operations that can be folded away.
10745 // If all input operands to the phi are the same instruction (e.g. a cast from
10746 // the same type or "+42") we can pull the operation through the PHI, reducing
10747 // code size and simplifying code.
10748 Constant *ConstantOp = 0;
10749 const Type *CastSrcTy = 0;
10750 bool isVolatile = false;
10751 if (isa<CastInst>(FirstInst)) {
10752 CastSrcTy = FirstInst->getOperand(0)->getType();
10753 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10754 // Can fold binop, compare or shift here if the RHS is a constant,
10755 // otherwise call FoldPHIArgBinOpIntoPHI.
10756 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10757 if (ConstantOp == 0)
10758 return FoldPHIArgBinOpIntoPHI(PN);
10759 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10760 isVolatile = LI->isVolatile();
10761 // We can't sink the load if the loaded value could be modified between the
10762 // load and the PHI.
10763 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010764 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010765 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010766
10767 // If the PHI is of volatile loads and the load block has multiple
10768 // successors, sinking it would remove a load of the volatile value from
10769 // the path through the other successor.
10770 if (isVolatile &&
10771 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10772 return 0;
10773
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010774 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010775 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010776 } else {
10777 return 0; // Cannot fold this operation.
10778 }
10779
10780 // Check to see if all arguments are the same operation.
10781 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10782 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10783 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10784 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10785 return 0;
10786 if (CastSrcTy) {
10787 if (I->getOperand(0)->getType() != CastSrcTy)
10788 return 0; // Cast operation must match.
10789 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10790 // We can't sink the load if the loaded value could be modified between
10791 // the load and the PHI.
10792 if (LI->isVolatile() != isVolatile ||
10793 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010794 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010795 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010796
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010797 // If the PHI is of volatile loads and the load block has multiple
10798 // successors, sinking it would remove a load of the volatile value from
10799 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010800 if (isVolatile &&
10801 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10802 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010803
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010804 } else if (I->getOperand(1) != ConstantOp) {
10805 return 0;
10806 }
10807 }
10808
10809 // Okay, they are all the same operation. Create a new PHI node of the
10810 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010811 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10812 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010813 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10814
10815 Value *InVal = FirstInst->getOperand(0);
10816 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10817
10818 // Add all operands to the new PHI.
10819 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10820 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10821 if (NewInVal != InVal)
10822 InVal = 0;
10823 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10824 }
10825
10826 Value *PhiVal;
10827 if (InVal) {
10828 // The new PHI unions all of the same values together. This is really
10829 // common, so we handle it intelligently here for compile-time speed.
10830 PhiVal = InVal;
10831 delete NewPN;
10832 } else {
10833 InsertNewInstBefore(NewPN, PN);
10834 PhiVal = NewPN;
10835 }
10836
10837 // Insert and return the new operation.
10838 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010839 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010840 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010841 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010842 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohmane6803b82009-08-25 23:17:54 +000010843 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010844 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010845 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10846
10847 // If this was a volatile load that we are merging, make sure to loop through
10848 // and mark all the input loads as non-volatile. If we don't do this, we will
10849 // insert a new volatile load and the old ones will not be deletable.
10850 if (isVolatile)
10851 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10852 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10853
10854 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010855}
10856
10857/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10858/// that is dead.
10859static bool DeadPHICycle(PHINode *PN,
10860 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10861 if (PN->use_empty()) return true;
10862 if (!PN->hasOneUse()) return false;
10863
10864 // Remember this node, and if we find the cycle, return.
10865 if (!PotentiallyDeadPHIs.insert(PN))
10866 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010867
10868 // Don't scan crazily complex things.
10869 if (PotentiallyDeadPHIs.size() == 16)
10870 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010871
10872 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10873 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10874
10875 return false;
10876}
10877
Chris Lattner27b695d2007-11-06 21:52:06 +000010878/// PHIsEqualValue - Return true if this phi node is always equal to
10879/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10880/// z = some value; x = phi (y, z); y = phi (x, z)
10881static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10882 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10883 // See if we already saw this PHI node.
10884 if (!ValueEqualPHIs.insert(PN))
10885 return true;
10886
10887 // Don't scan crazily complex things.
10888 if (ValueEqualPHIs.size() == 16)
10889 return false;
10890
10891 // Scan the operands to see if they are either phi nodes or are equal to
10892 // the value.
10893 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10894 Value *Op = PN->getIncomingValue(i);
10895 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10896 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10897 return false;
10898 } else if (Op != NonPhiInVal)
10899 return false;
10900 }
10901
10902 return true;
10903}
10904
10905
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010906// PHINode simplification
10907//
10908Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10909 // If LCSSA is around, don't mess with Phi nodes
10910 if (MustPreserveLCSSA) return 0;
10911
10912 if (Value *V = PN.hasConstantValue())
10913 return ReplaceInstUsesWith(PN, V);
10914
10915 // If all PHI operands are the same operation, pull them through the PHI,
10916 // reducing code size.
10917 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010918 isa<Instruction>(PN.getIncomingValue(1)) &&
10919 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10920 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10921 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10922 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010923 PN.getIncomingValue(0)->hasOneUse())
10924 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10925 return Result;
10926
10927 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10928 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10929 // PHI)... break the cycle.
10930 if (PN.hasOneUse()) {
10931 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10932 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10933 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10934 PotentiallyDeadPHIs.insert(&PN);
10935 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010936 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010937 }
10938
10939 // If this phi has a single use, and if that use just computes a value for
10940 // the next iteration of a loop, delete the phi. This occurs with unused
10941 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10942 // common case here is good because the only other things that catch this
10943 // are induction variable analysis (sometimes) and ADCE, which is only run
10944 // late.
10945 if (PHIUser->hasOneUse() &&
10946 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10947 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010948 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010949 }
10950 }
10951
Chris Lattner27b695d2007-11-06 21:52:06 +000010952 // We sometimes end up with phi cycles that non-obviously end up being the
10953 // same value, for example:
10954 // z = some value; x = phi (y, z); y = phi (x, z)
10955 // where the phi nodes don't necessarily need to be in the same block. Do a
10956 // quick check to see if the PHI node only contains a single non-phi value, if
10957 // so, scan to see if the phi cycle is actually equal to that value.
10958 {
10959 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10960 // Scan for the first non-phi operand.
10961 while (InValNo != NumOperandVals &&
10962 isa<PHINode>(PN.getIncomingValue(InValNo)))
10963 ++InValNo;
10964
10965 if (InValNo != NumOperandVals) {
10966 Value *NonPhiInVal = PN.getOperand(InValNo);
10967
10968 // Scan the rest of the operands to see if there are any conflicts, if so
10969 // there is no need to recursively scan other phis.
10970 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10971 Value *OpVal = PN.getIncomingValue(InValNo);
10972 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10973 break;
10974 }
10975
10976 // If we scanned over all operands, then we have one unique value plus
10977 // phi values. Scan PHI nodes to see if they all merge in each other or
10978 // the value.
10979 if (InValNo == NumOperandVals) {
10980 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10981 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10982 return ReplaceInstUsesWith(PN, NonPhiInVal);
10983 }
10984 }
10985 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010986 return 0;
10987}
10988
10989static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10990 Instruction *InsertPoint,
10991 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000010992 unsigned PtrSize = DTy->getScalarSizeInBits();
10993 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010994 // We must cast correctly to the pointer type. Ensure that we
10995 // sign extend the integer value if it is smaller as this is
10996 // used for address computation.
10997 Instruction::CastOps opcode =
10998 (VTySize < PtrSize ? Instruction::SExt :
10999 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11000 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11001}
11002
11003
11004Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11005 Value *PtrOp = GEP.getOperand(0);
11006 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
11007 // If so, eliminate the noop.
11008 if (GEP.getNumOperands() == 1)
11009 return ReplaceInstUsesWith(GEP, PtrOp);
11010
11011 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011012 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011013
11014 bool HasZeroPointerIndex = false;
11015 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11016 HasZeroPointerIndex = C->isNullValue();
11017
11018 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11019 return ReplaceInstUsesWith(GEP, PtrOp);
11020
11021 // Eliminate unneeded casts for indices.
11022 bool MadeChange = false;
11023
11024 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011025 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11026 i != e; ++i, ++GTI) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011027 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000011028 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011029 if (CI->getOpcode() == Instruction::ZExt ||
11030 CI->getOpcode() == Instruction::SExt) {
11031 const Type *SrcTy = CI->getOperand(0)->getType();
11032 // We can eliminate a cast from i32 to i64 iff the target
11033 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000011034 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011035 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000011036 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011037 }
11038 }
11039 }
11040 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000011041 // to what we need. If narrower, sign-extend it to what we need.
11042 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011043 // insert it. This explicit cast can make subsequent optimizations more
11044 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000011045 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011046 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011047 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson35b47072009-08-13 21:58:54 +000011048 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType(GEP.getContext()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011049 MadeChange = true;
11050 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000011051 Op = InsertCastBefore(Instruction::Trunc, Op,
11052 TD->getIntPtrType(GEP.getContext()),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011053 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011054 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011055 MadeChange = true;
11056 }
Eric Christopher3e7381f2009-07-25 02:45:27 +000011057 } else if (TD->getTypeSizeInBits(Op->getType())
11058 < TD->getPointerSizeInBits()) {
Dan Gohman5d639ed2008-09-11 23:06:38 +000011059 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson35b47072009-08-13 21:58:54 +000011060 *i = ConstantExpr::getSExt(C, TD->getIntPtrType(GEP.getContext()));
Dan Gohman5d639ed2008-09-11 23:06:38 +000011061 MadeChange = true;
11062 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000011063 Op = InsertCastBefore(Instruction::SExt, Op,
11064 TD->getIntPtrType(GEP.getContext()), GEP);
Dan Gohman5d639ed2008-09-11 23:06:38 +000011065 *i = Op;
11066 MadeChange = true;
11067 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011068 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011069 }
11070 }
11071 if (MadeChange) return &GEP;
11072
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011073 // Combine Indices - If the source pointer to this getelementptr instruction
11074 // is a getelementptr instruction, combine the indices of the two
11075 // getelementptr instructions into a single instruction.
11076 //
11077 SmallVector<Value*, 8> SrcGEPOperands;
Dan Gohman17f46f72009-07-28 01:40:03 +000011078 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11079 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011080 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011081 if (!Src->isInBounds())
11082 BothInBounds = false;
11083 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011084
11085 if (!SrcGEPOperands.empty()) {
11086 // Note that if our source is a gep chain itself that we wait for that
11087 // chain to be resolved before we perform this transformation. This
11088 // avoids us creating a TON of code in some cases.
11089 //
11090 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11091 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11092 return 0; // Wait until our source is folded to completion.
11093
11094 SmallVector<Value*, 8> Indices;
11095
11096 // Find out whether the last index in the source GEP is a sequential idx.
11097 bool EndsWithSequential = false;
11098 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11099 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11100 EndsWithSequential = !isa<StructType>(*I);
11101
11102 // Can we combine the two pointer arithmetics offsets?
11103 if (EndsWithSequential) {
11104 // Replace: gep (gep %P, long B), long A, ...
11105 // With: T = long A+B; gep %P, T, ...
11106 //
11107 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011108 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011109 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011110 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011111 Sum = SO1;
11112 } else {
11113 // If they aren't the same type, convert both to an integer of the
11114 // target's pointer size.
11115 if (SO1->getType() != GO1->getType()) {
11116 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011117 SO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011118 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011119 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011120 GO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011121 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmana80e2712009-07-21 23:21:54 +000011122 } else if (TD) {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011123 unsigned PS = TD->getPointerSizeInBits();
11124 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011125 // Convert GO1 to SO1's type.
11126 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11127
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011128 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011129 // Convert SO1 to GO1's type.
11130 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11131 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000011132 const Type *PT = TD->getIntPtrType(GEP.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011133 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11134 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11135 }
11136 }
11137 }
11138 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Anderson02b48c32009-07-29 18:55:55 +000011139 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
Owen Anderson24be4c12009-07-03 00:17:18 +000011140 cast<Constant>(GO1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011141 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011142 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011143 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11144 }
11145 }
11146
11147 // Recycle the GEP we already have if possible.
11148 if (SrcGEPOperands.size() == 2) {
11149 GEP.setOperand(0, SrcGEPOperands[0]);
11150 GEP.setOperand(1, Sum);
11151 return &GEP;
11152 } else {
11153 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11154 SrcGEPOperands.end()-1);
11155 Indices.push_back(Sum);
11156 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11157 }
11158 } else if (isa<Constant>(*GEP.idx_begin()) &&
11159 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11160 SrcGEPOperands.size() != 1) {
11161 // Otherwise we can do the fold if the first index of the GEP is a zero
11162 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11163 SrcGEPOperands.end());
11164 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11165 }
11166
Dan Gohman17f46f72009-07-28 01:40:03 +000011167 if (!Indices.empty()) {
11168 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11169 Indices.begin(),
11170 Indices.end(),
11171 GEP.getName());
11172 if (BothInBounds)
11173 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11174 return NewGEP;
11175 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011176
11177 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11178 // GEP of global variable. If all of the indices for this GEP are
11179 // constants, we can promote this to a constexpr instead of an instruction.
11180
11181 // Scan for nonconstants...
11182 SmallVector<Constant*, 8> Indices;
11183 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11184 for (; I != E && isa<Constant>(*I); ++I)
11185 Indices.push_back(cast<Constant>(*I));
11186
11187 if (I == E) { // If they are all constants...
Owen Anderson02b48c32009-07-29 18:55:55 +000011188 Constant *CE = ConstantExpr::getGetElementPtr(GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011189 &Indices[0],Indices.size());
11190
11191 // Replace all uses of the GEP with the new constexpr...
11192 return ReplaceInstUsesWith(GEP, CE);
11193 }
11194 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11195 if (!isa<PointerType>(X->getType())) {
11196 // Not interesting. Source pointer must be a cast from pointer.
11197 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011198 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11199 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011200 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011201 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11202 // into : GEP i8* X, ...
11203 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011204 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011205 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11206 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011207 if (const ArrayType *CATy =
11208 dyn_cast<ArrayType>(CPTy->getElementType())) {
11209 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11210 if (CATy->getElementType() == XTy->getElementType()) {
11211 // -> GEP i8* X, ...
11212 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011213 GetElementPtrInst *NewGEP =
11214 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11215 GEP.getName());
11216 if (cast<GEPOperator>(&GEP)->isInBounds())
11217 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11218 return NewGEP;
Duncan Sandscf866e62009-03-02 09:18:21 +000011219 } else if (const ArrayType *XATy =
11220 dyn_cast<ArrayType>(XTy->getElementType())) {
11221 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011222 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011223 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011224 // At this point, we know that the cast source type is a pointer
11225 // to an array of the same type as the destination pointer
11226 // array. Because the array type is never stepped over (there
11227 // is a leading zero) we can fold the cast into this GEP.
11228 GEP.setOperand(0, X);
11229 return &GEP;
11230 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011231 }
11232 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011233 } else if (GEP.getNumOperands() == 2) {
11234 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011235 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11236 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011237 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11238 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011239 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011240 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11241 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011242 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011243 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011244 Idx[1] = GEP.getOperand(1);
Dan Gohman17f46f72009-07-28 01:40:03 +000011245 GetElementPtrInst *NewGEP =
11246 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11247 if (cast<GEPOperator>(&GEP)->isInBounds())
11248 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11249 Value *V = InsertNewInstBefore(NewGEP, GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011250 // V and GEP are both pointer types --> BitCast
11251 return new BitCastInst(V, GEP.getType());
11252 }
11253
11254 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011255 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011256 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011257 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011258
Owen Anderson35b47072009-08-13 21:58:54 +000011259 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011260 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011261 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011262
11263 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11264 // allow either a mul, shift, or constant here.
11265 Value *NewIdx = 0;
11266 ConstantInt *Scale = 0;
11267 if (ArrayEltSize == 1) {
11268 NewIdx = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011269 Scale =
Owen Andersoneacb44d2009-07-24 23:12:02 +000011270 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011271 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011272 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011273 Scale = CI;
11274 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11275 if (Inst->getOpcode() == Instruction::Shl &&
11276 isa<ConstantInt>(Inst->getOperand(1))) {
11277 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11278 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011279 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011280 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011281 NewIdx = Inst->getOperand(0);
11282 } else if (Inst->getOpcode() == Instruction::Mul &&
11283 isa<ConstantInt>(Inst->getOperand(1))) {
11284 Scale = cast<ConstantInt>(Inst->getOperand(1));
11285 NewIdx = Inst->getOperand(0);
11286 }
11287 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011288
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011289 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011290 // out, perform the transformation. Note, we don't know whether Scale is
11291 // signed or not. We'll use unsigned version of division/modulo
11292 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011293 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011294 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011295 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011296 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011297 if (Scale->getZExtValue() != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011298 Constant *C =
Owen Anderson02b48c32009-07-29 18:55:55 +000011299 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011300 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011301 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011302 NewIdx = InsertNewInstBefore(Sc, GEP);
11303 }
11304
11305 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011306 Value *Idx[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011307 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011308 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011309 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011310 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohman17f46f72009-07-28 01:40:03 +000011311 if (cast<GEPOperator>(&GEP)->isInBounds())
11312 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011313 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11314 // The NewGEP must be pointer typed, so must the old one -> BitCast
11315 return new BitCastInst(NewGEP, GEP.getType());
11316 }
11317 }
11318 }
11319 }
Chris Lattner111ea772009-01-09 04:53:57 +000011320
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011321 /// See if we can simplify:
11322 /// X = bitcast A to B*
11323 /// Y = gep X, <...constant indices...>
11324 /// into a gep of the original struct. This is important for SROA and alias
11325 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011326 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011327 if (TD &&
11328 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011329 // Determine how much the GEP moves the pointer. We are guaranteed to get
11330 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011331 ConstantInt *OffsetV =
11332 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011333 int64_t Offset = OffsetV->getSExtValue();
11334
11335 // If this GEP instruction doesn't move the pointer, just replace the GEP
11336 // with a bitcast of the real input to the dest type.
11337 if (Offset == 0) {
11338 // If the bitcast is of an allocation, and the allocation will be
11339 // converted to match the type of the cast, don't touch this.
11340 if (isa<AllocationInst>(BCI->getOperand(0))) {
11341 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11342 if (Instruction *I = visitBitCast(*BCI)) {
11343 if (I != BCI) {
11344 I->takeName(BCI);
11345 BCI->getParent()->getInstList().insert(BCI, I);
11346 ReplaceInstUsesWith(*BCI, I);
11347 }
11348 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011349 }
Chris Lattner111ea772009-01-09 04:53:57 +000011350 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011351 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011352 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011353
11354 // Otherwise, if the offset is non-zero, we need to find out if there is a
11355 // field at Offset in 'A's type. If so, we can pull the cast through the
11356 // GEP.
11357 SmallVector<Value*, 8> NewIndices;
11358 const Type *InTy =
11359 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011360 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011361 Instruction *NGEP =
11362 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11363 NewIndices.end());
11364 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohman17f46f72009-07-28 01:40:03 +000011365 if (cast<GEPOperator>(&GEP)->isInBounds())
11366 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011367 InsertNewInstBefore(NGEP, GEP);
11368 NGEP->takeName(&GEP);
11369 return new BitCastInst(NGEP, GEP.getType());
11370 }
Chris Lattner111ea772009-01-09 04:53:57 +000011371 }
11372 }
11373
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011374 return 0;
11375}
11376
11377Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11378 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011379 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011380 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11381 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011382 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011383 AllocationInst *New = 0;
11384
11385 // Create and insert the replacement instruction...
11386 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +000011387 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011388 else {
11389 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson140166d2009-07-15 23:53:25 +000011390 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011391 }
11392
11393 InsertNewInstBefore(New, AI);
11394
11395 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011396 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011397 //
11398 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011399 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011400
11401 // Now that I is pointing to the first non-allocation-inst in the block,
11402 // insert our getelementptr instruction...
11403 //
Owen Anderson35b47072009-08-13 21:58:54 +000011404 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greene393be882007-09-04 15:46:09 +000011405 Value *Idx[2];
11406 Idx[0] = NullIdx;
11407 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011408 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11409 New->getName()+".sub", It);
Dan Gohman17f46f72009-07-28 01:40:03 +000011410 cast<GEPOperator>(V)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011411
11412 // Now make everything use the getelementptr instead of the original
11413 // allocation.
11414 return ReplaceInstUsesWith(AI, V);
11415 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011416 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011417 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011418 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011419
Dan Gohmana80e2712009-07-21 23:21:54 +000011420 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011421 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011422 // Note that we only do this for alloca's, because malloc should allocate
11423 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011424 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011425 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011426
11427 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11428 if (AI.getAlignment() == 0)
11429 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11430 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011431
11432 return 0;
11433}
11434
11435Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11436 Value *Op = FI.getOperand(0);
11437
11438 // free undef -> unreachable.
11439 if (isa<UndefValue>(Op)) {
11440 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011441 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson35b47072009-08-13 21:58:54 +000011442 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011443 return EraseInstFromFunction(FI);
11444 }
11445
11446 // If we have 'free null' delete the instruction. This can happen in stl code
11447 // when lots of inlining happens.
11448 if (isa<ConstantPointerNull>(Op))
11449 return EraseInstFromFunction(FI);
11450
11451 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11452 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11453 FI.setOperand(0, CI->getOperand(0));
11454 return &FI;
11455 }
11456
11457 // Change free (gep X, 0,0,0,0) into free(X)
11458 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11459 if (GEPI->hasAllZeroIndices()) {
11460 AddToWorkList(GEPI);
11461 FI.setOperand(0, GEPI->getOperand(0));
11462 return &FI;
11463 }
11464 }
11465
11466 // Change free(malloc) into nothing, if the malloc has a single use.
11467 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11468 if (MI->hasOneUse()) {
11469 EraseInstFromFunction(FI);
11470 return EraseInstFromFunction(*MI);
11471 }
11472
11473 return 0;
11474}
11475
11476
11477/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011478static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011479 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011480 User *CI = cast<User>(LI.getOperand(0));
11481 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011482 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011483
Nick Lewycky291c5942009-05-08 06:47:37 +000011484 if (TD) {
11485 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11486 // Instead of loading constant c string, use corresponding integer value
11487 // directly if string length is small enough.
11488 std::string Str;
11489 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11490 unsigned len = Str.length();
11491 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11492 unsigned numBits = Ty->getPrimitiveSizeInBits();
11493 // Replace LI with immediate integer store.
11494 if ((numBits >> 3) == len + 1) {
11495 APInt StrVal(numBits, 0);
11496 APInt SingleChar(numBits, 0);
11497 if (TD->isLittleEndian()) {
11498 for (signed i = len-1; i >= 0; i--) {
11499 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11500 StrVal = (StrVal << 8) | SingleChar;
11501 }
11502 } else {
11503 for (unsigned i = 0; i < len; i++) {
11504 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11505 StrVal = (StrVal << 8) | SingleChar;
11506 }
11507 // Append NULL at the end.
11508 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011509 StrVal = (StrVal << 8) | SingleChar;
11510 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011511 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011512 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011513 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011514 }
11515 }
11516 }
11517
Mon P Wangbd05ed82009-02-07 22:19:29 +000011518 const PointerType *DestTy = cast<PointerType>(CI->getType());
11519 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011520 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011521
11522 // If the address spaces don't match, don't eliminate the cast.
11523 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11524 return 0;
11525
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011526 const Type *SrcPTy = SrcTy->getElementType();
11527
11528 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11529 isa<VectorType>(DestPTy)) {
11530 // If the source is an array, the code below will not succeed. Check to
11531 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11532 // constants.
11533 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11534 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11535 if (ASrcTy->getNumElements() != 0) {
11536 Value *Idxs[2];
Owen Anderson35b47072009-08-13 21:58:54 +000011537 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Anderson02b48c32009-07-29 18:55:55 +000011538 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011539 SrcTy = cast<PointerType>(CastOp->getType());
11540 SrcPTy = SrcTy->getElementType();
11541 }
11542
Dan Gohmana80e2712009-07-21 23:21:54 +000011543 if (IC.getTargetData() &&
11544 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011545 isa<VectorType>(SrcPTy)) &&
11546 // Do not allow turning this into a load of an integer, which is then
11547 // casted to a pointer, this pessimizes pointer analysis a lot.
11548 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011549 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11550 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011551
11552 // Okay, we are casting from one integer or pointer type to another of
11553 // the same size. Instead of casting the pointer before the load, cast
11554 // the result of the loaded value.
11555 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11556 CI->getName(),
11557 LI.isVolatile()),LI);
11558 // Now cast the result of the load.
11559 return new BitCastInst(NewLoad, LI.getType());
11560 }
11561 }
11562 }
11563 return 0;
11564}
11565
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011566Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11567 Value *Op = LI.getOperand(0);
11568
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011569 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011570 if (TD) {
11571 unsigned KnownAlign =
11572 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11573 if (KnownAlign >
11574 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11575 LI.getAlignment()))
11576 LI.setAlignment(KnownAlign);
11577 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011578
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011579 // load (cast X) --> cast (load X) iff safe
11580 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011581 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011582 return Res;
11583
11584 // None of the following transforms are legal for volatile loads.
11585 if (LI.isVolatile()) return 0;
11586
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011587 // Do really simple store-to-load forwarding and load CSE, to catch cases
11588 // where there are several consequtive memory accesses to the same location,
11589 // separated by a few arithmetic operations.
11590 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011591 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11592 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011593
Christopher Lamb2c175392007-12-29 07:56:53 +000011594 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11595 const Value *GEPI0 = GEPI->getOperand(0);
11596 // TODO: Consider a target hook for valid address spaces for this xform.
11597 if (isa<ConstantPointerNull>(GEPI0) &&
11598 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011599 // Insert a new store to null instruction before the load to indicate
11600 // that this code is not reachable. We do this instead of inserting
11601 // an unreachable instruction directly because we cannot modify the
11602 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011603 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011604 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011605 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011606 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011607 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011608
11609 if (Constant *C = dyn_cast<Constant>(Op)) {
11610 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011611 // TODO: Consider a target hook for valid address spaces for this xform.
11612 if (isa<UndefValue>(C) || (C->isNullValue() &&
11613 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011614 // Insert a new store to null instruction before the load to indicate that
11615 // this code is not reachable. We do this instead of inserting an
11616 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011617 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011618 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011619 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011620 }
11621
11622 // Instcombine load (constant global) into the value loaded.
11623 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011624 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011625 return ReplaceInstUsesWith(LI, GV->getInitializer());
11626
11627 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011628 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011629 if (CE->getOpcode() == Instruction::GetElementPtr) {
11630 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011631 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011632 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011633 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Anderson175b6542009-07-22 00:24:57 +000011634 *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011635 return ReplaceInstUsesWith(LI, V);
11636 if (CE->getOperand(0)->isNullValue()) {
11637 // Insert a new store to null instruction before the load to indicate
11638 // that this code is not reachable. We do this instead of inserting
11639 // an unreachable instruction directly because we cannot modify the
11640 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011641 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011642 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011643 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011644 }
11645
11646 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011647 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011648 return Res;
11649 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011650 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011651 }
Chris Lattner0270a112007-08-11 18:48:48 +000011652
11653 // If this load comes from anywhere in a constant global, and if the global
11654 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011655 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011656 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011657 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011658 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011659 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011660 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011661 }
11662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011663
11664 if (Op->hasOneUse()) {
11665 // Change select and PHI nodes to select values instead of addresses: this
11666 // helps alias analysis out a lot, allows many others simplifications, and
11667 // exposes redundancy in the code.
11668 //
11669 // Note that we cannot do the transformation unless we know that the
11670 // introduced loads cannot trap! Something like this is valid as long as
11671 // the condition is always false: load (select bool %C, int* null, int* %G),
11672 // but it would not be valid if we transformed it to load from null
11673 // unconditionally.
11674 //
11675 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11676 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11677 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11678 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11679 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11680 SI->getOperand(1)->getName()+".val"), LI);
11681 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11682 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011683 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011684 }
11685
11686 // load (select (cond, null, P)) -> load P
11687 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11688 if (C->isNullValue()) {
11689 LI.setOperand(0, SI->getOperand(2));
11690 return &LI;
11691 }
11692
11693 // load (select (cond, P, null)) -> load P
11694 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11695 if (C->isNullValue()) {
11696 LI.setOperand(0, SI->getOperand(1));
11697 return &LI;
11698 }
11699 }
11700 }
11701 return 0;
11702}
11703
11704/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011705/// when possible. This makes it generally easy to do alias analysis and/or
11706/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011707static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11708 User *CI = cast<User>(SI.getOperand(1));
11709 Value *CastOp = CI->getOperand(0);
11710
11711 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011712 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11713 if (SrcTy == 0) return 0;
11714
11715 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011716
Chris Lattnera032c0e2009-01-16 20:08:59 +000011717 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11718 return 0;
11719
Chris Lattner54dddc72009-01-24 01:00:13 +000011720 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11721 /// to its first element. This allows us to handle things like:
11722 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11723 /// on 32-bit hosts.
11724 SmallVector<Value*, 4> NewGEPIndices;
11725
Chris Lattnera032c0e2009-01-16 20:08:59 +000011726 // If the source is an array, the code below will not succeed. Check to
11727 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11728 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011729 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11730 // Index through pointer.
Owen Anderson35b47072009-08-13 21:58:54 +000011731 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner54dddc72009-01-24 01:00:13 +000011732 NewGEPIndices.push_back(Zero);
11733
11734 while (1) {
11735 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011736 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011737 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011738 NewGEPIndices.push_back(Zero);
11739 SrcPTy = STy->getElementType(0);
11740 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11741 NewGEPIndices.push_back(Zero);
11742 SrcPTy = ATy->getElementType();
11743 } else {
11744 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011745 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011746 }
11747
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011748 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011749 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011750
11751 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11752 return 0;
11753
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011754 // If the pointers point into different address spaces or if they point to
11755 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011756 if (!IC.getTargetData() ||
11757 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011758 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011759 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11760 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011761 return 0;
11762
11763 // Okay, we are casting from one integer or pointer type to another of
11764 // the same size. Instead of casting the pointer before
11765 // the store, cast the value to be stored.
11766 Value *NewCast;
11767 Value *SIOp0 = SI.getOperand(0);
11768 Instruction::CastOps opcode = Instruction::BitCast;
11769 const Type* CastSrcTy = SIOp0->getType();
11770 const Type* CastDstTy = SrcPTy;
11771 if (isa<PointerType>(CastDstTy)) {
11772 if (CastSrcTy->isInteger())
11773 opcode = Instruction::IntToPtr;
11774 } else if (isa<IntegerType>(CastDstTy)) {
11775 if (isa<PointerType>(SIOp0->getType()))
11776 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011777 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011778
11779 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11780 // emit a GEP to index into its first field.
11781 if (!NewGEPIndices.empty()) {
11782 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Anderson02b48c32009-07-29 18:55:55 +000011783 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner54dddc72009-01-24 01:00:13 +000011784 NewGEPIndices.size());
11785 else
11786 CastOp = IC.InsertNewInstBefore(
11787 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11788 NewGEPIndices.end()), SI);
Dan Gohman17f46f72009-07-28 01:40:03 +000011789 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner54dddc72009-01-24 01:00:13 +000011790 }
11791
Chris Lattnera032c0e2009-01-16 20:08:59 +000011792 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Anderson02b48c32009-07-29 18:55:55 +000011793 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnera032c0e2009-01-16 20:08:59 +000011794 else
11795 NewCast = IC.InsertNewInstBefore(
11796 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11797 SI);
11798 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011799}
11800
Chris Lattner6fd8c802008-11-27 08:56:30 +000011801/// equivalentAddressValues - Test if A and B will obviously have the same
11802/// value. This includes recognizing that %t0 and %t1 will have the same
11803/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011804/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011805/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011806/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011807/// %t2 = load i32* %t1
11808///
11809static bool equivalentAddressValues(Value *A, Value *B) {
11810 // Test if the values are trivially equivalent.
11811 if (A == B) return true;
11812
11813 // Test if the values come form identical arithmetic instructions.
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011814 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11815 // its only used to compare two uses within the same basic block, which
11816 // means that they'll always either have the same value or one of them
11817 // will have an undefined value.
Chris Lattner6fd8c802008-11-27 08:56:30 +000011818 if (isa<BinaryOperator>(A) ||
11819 isa<CastInst>(A) ||
11820 isa<PHINode>(A) ||
11821 isa<GetElementPtrInst>(A))
11822 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohmanfc00c4a2009-08-25 22:11:20 +000011823 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner6fd8c802008-11-27 08:56:30 +000011824 return true;
11825
11826 // Otherwise they may not be equivalent.
11827 return false;
11828}
11829
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011830// If this instruction has two uses, one of which is a llvm.dbg.declare,
11831// return the llvm.dbg.declare.
11832DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11833 if (!V->hasNUses(2))
11834 return 0;
11835 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11836 UI != E; ++UI) {
11837 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11838 return DI;
11839 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11840 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11841 return DI;
11842 }
11843 }
11844 return 0;
11845}
11846
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011847Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11848 Value *Val = SI.getOperand(0);
11849 Value *Ptr = SI.getOperand(1);
11850
11851 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11852 EraseInstFromFunction(SI);
11853 ++NumCombined;
11854 return 0;
11855 }
11856
11857 // If the RHS is an alloca with a single use, zapify the store, making the
11858 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011859 // If the RHS is an alloca with a two uses, the other one being a
11860 // llvm.dbg.declare, zapify the store and the declare, making the
11861 // alloca dead. We must do this to prevent declare's from affecting
11862 // codegen.
11863 if (!SI.isVolatile()) {
11864 if (Ptr->hasOneUse()) {
11865 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011866 EraseInstFromFunction(SI);
11867 ++NumCombined;
11868 return 0;
11869 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011870 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11871 if (isa<AllocaInst>(GEP->getOperand(0))) {
11872 if (GEP->getOperand(0)->hasOneUse()) {
11873 EraseInstFromFunction(SI);
11874 ++NumCombined;
11875 return 0;
11876 }
11877 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11878 EraseInstFromFunction(*DI);
11879 EraseInstFromFunction(SI);
11880 ++NumCombined;
11881 return 0;
11882 }
11883 }
11884 }
11885 }
11886 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11887 EraseInstFromFunction(*DI);
11888 EraseInstFromFunction(SI);
11889 ++NumCombined;
11890 return 0;
11891 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011892 }
11893
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011894 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011895 if (TD) {
11896 unsigned KnownAlign =
11897 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11898 if (KnownAlign >
11899 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11900 SI.getAlignment()))
11901 SI.setAlignment(KnownAlign);
11902 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011903
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011904 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011905 // stores to the same location, separated by a few arithmetic operations. This
11906 // situation often occurs with bitfield accesses.
11907 BasicBlock::iterator BBI = &SI;
11908 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11909 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011910 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011911 // Don't count debug info directives, lest they affect codegen,
11912 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11913 // It is necessary for correctness to skip those that feed into a
11914 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011915 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011916 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011917 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011918 continue;
11919 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011920
11921 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11922 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011923 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11924 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011925 ++NumDeadStore;
11926 ++BBI;
11927 EraseInstFromFunction(*PrevSI);
11928 continue;
11929 }
11930 break;
11931 }
11932
11933 // If this is a load, we have to stop. However, if the loaded value is from
11934 // the pointer we're loading and is producing the pointer we're storing,
11935 // then *this* store is dead (X = load P; store X -> P).
11936 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011937 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11938 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011939 EraseInstFromFunction(SI);
11940 ++NumCombined;
11941 return 0;
11942 }
11943 // Otherwise, this is a load from some other location. Stores before it
11944 // may not be dead.
11945 break;
11946 }
11947
11948 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011949 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011950 break;
11951 }
11952
11953
11954 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11955
11956 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011957 if (isa<ConstantPointerNull>(Ptr) &&
11958 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011959 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011960 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011961 if (Instruction *U = dyn_cast<Instruction>(Val))
11962 AddToWorkList(U); // Dropped a use.
11963 ++NumCombined;
11964 }
11965 return 0; // Do not modify these!
11966 }
11967
11968 // store undef, Ptr -> noop
11969 if (isa<UndefValue>(Val)) {
11970 EraseInstFromFunction(SI);
11971 ++NumCombined;
11972 return 0;
11973 }
11974
11975 // If the pointer destination is a cast, see if we can fold the cast into the
11976 // source instead.
11977 if (isa<CastInst>(Ptr))
11978 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11979 return Res;
11980 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11981 if (CE->isCast())
11982 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11983 return Res;
11984
11985
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011986 // If this store is the last instruction in the basic block (possibly
11987 // excepting debug info instructions and the pointer bitcasts that feed
11988 // into them), and if the block ends with an unconditional branch, try
11989 // to move it to the successor block.
11990 BBI = &SI;
11991 do {
11992 ++BBI;
11993 } while (isa<DbgInfoIntrinsic>(BBI) ||
11994 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011995 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11996 if (BI->isUnconditional())
11997 if (SimplifyStoreAtEndOfBlock(SI))
11998 return 0; // xform done!
11999
12000 return 0;
12001}
12002
12003/// SimplifyStoreAtEndOfBlock - Turn things like:
12004/// if () { *P = v1; } else { *P = v2 }
12005/// into a phi node with a store in the successor.
12006///
12007/// Simplify things like:
12008/// *P = v1; if () { *P = v2; }
12009/// into a phi node with a store in the successor.
12010///
12011bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12012 BasicBlock *StoreBB = SI.getParent();
12013
12014 // Check to see if the successor block has exactly two incoming edges. If
12015 // so, see if the other predecessor contains a store to the same location.
12016 // if so, insert a PHI node (if needed) and move the stores down.
12017 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12018
12019 // Determine whether Dest has exactly two predecessors and, if so, compute
12020 // the other predecessor.
12021 pred_iterator PI = pred_begin(DestBB);
12022 BasicBlock *OtherBB = 0;
12023 if (*PI != StoreBB)
12024 OtherBB = *PI;
12025 ++PI;
12026 if (PI == pred_end(DestBB))
12027 return false;
12028
12029 if (*PI != StoreBB) {
12030 if (OtherBB)
12031 return false;
12032 OtherBB = *PI;
12033 }
12034 if (++PI != pred_end(DestBB))
12035 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012036
12037 // Bail out if all the relevant blocks aren't distinct (this can happen,
12038 // for example, if SI is in an infinite loop)
12039 if (StoreBB == DestBB || OtherBB == DestBB)
12040 return false;
12041
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012042 // Verify that the other block ends in a branch and is not otherwise empty.
12043 BasicBlock::iterator BBI = OtherBB->getTerminator();
12044 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12045 if (!OtherBr || BBI == OtherBB->begin())
12046 return false;
12047
12048 // If the other block ends in an unconditional branch, check for the 'if then
12049 // else' case. there is an instruction before the branch.
12050 StoreInst *OtherStore = 0;
12051 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012052 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012053 // Skip over debugging info.
12054 while (isa<DbgInfoIntrinsic>(BBI) ||
12055 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12056 if (BBI==OtherBB->begin())
12057 return false;
12058 --BBI;
12059 }
12060 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012061 OtherStore = dyn_cast<StoreInst>(BBI);
12062 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12063 return false;
12064 } else {
12065 // Otherwise, the other block ended with a conditional branch. If one of the
12066 // destinations is StoreBB, then we have the if/then case.
12067 if (OtherBr->getSuccessor(0) != StoreBB &&
12068 OtherBr->getSuccessor(1) != StoreBB)
12069 return false;
12070
12071 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12072 // if/then triangle. See if there is a store to the same ptr as SI that
12073 // lives in OtherBB.
12074 for (;; --BBI) {
12075 // Check to see if we find the matching store.
12076 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12077 if (OtherStore->getOperand(1) != SI.getOperand(1))
12078 return false;
12079 break;
12080 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012081 // If we find something that may be using or overwriting the stored
12082 // value, or if we run out of instructions, we can't do the xform.
12083 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012084 BBI == OtherBB->begin())
12085 return false;
12086 }
12087
12088 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012089 // make sure nothing reads or overwrites the stored value in
12090 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012091 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12092 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012093 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012094 return false;
12095 }
12096 }
12097
12098 // Insert a PHI node now if we need it.
12099 Value *MergedVal = OtherStore->getOperand(0);
12100 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012101 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012102 PN->reserveOperandSpace(2);
12103 PN->addIncoming(SI.getOperand(0), SI.getParent());
12104 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12105 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12106 }
12107
12108 // Advance to a place where it is safe to insert the new store and
12109 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012110 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012111 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12112 OtherStore->isVolatile()), *BBI);
12113
12114 // Nuke the old stores.
12115 EraseInstFromFunction(SI);
12116 EraseInstFromFunction(*OtherStore);
12117 ++NumCombined;
12118 return true;
12119}
12120
12121
12122Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12123 // Change br (not X), label True, label False to: br X, label False, True
12124 Value *X = 0;
12125 BasicBlock *TrueDest;
12126 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +000012127 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012128 !isa<Constant>(X)) {
12129 // Swap Destinations and condition...
12130 BI.setCondition(X);
12131 BI.setSuccessor(0, FalseDest);
12132 BI.setSuccessor(1, TrueDest);
12133 return &BI;
12134 }
12135
12136 // Cannonicalize fcmp_one -> fcmp_oeq
12137 FCmpInst::Predicate FPred; Value *Y;
12138 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Dan Gohmancdff2122009-08-12 16:23:25 +000012139 TrueDest, FalseDest)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012140 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12141 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12142 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12143 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012144 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012145 NewSCC->takeName(I);
12146 // Swap Destinations and condition...
12147 BI.setCondition(NewSCC);
12148 BI.setSuccessor(0, FalseDest);
12149 BI.setSuccessor(1, TrueDest);
12150 RemoveFromWorkList(I);
12151 I->eraseFromParent();
12152 AddToWorkList(NewSCC);
12153 return &BI;
12154 }
12155
12156 // Cannonicalize icmp_ne -> icmp_eq
12157 ICmpInst::Predicate IPred;
12158 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Dan Gohmancdff2122009-08-12 16:23:25 +000012159 TrueDest, FalseDest)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012160 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12161 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12162 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12163 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12164 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012165 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012166 NewSCC->takeName(I);
12167 // Swap Destinations and condition...
12168 BI.setCondition(NewSCC);
12169 BI.setSuccessor(0, FalseDest);
12170 BI.setSuccessor(1, TrueDest);
12171 RemoveFromWorkList(I);
12172 I->eraseFromParent();;
12173 AddToWorkList(NewSCC);
12174 return &BI;
12175 }
12176
12177 return 0;
12178}
12179
12180Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12181 Value *Cond = SI.getCondition();
12182 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12183 if (I->getOpcode() == Instruction::Add)
12184 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12185 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12186 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012187 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012188 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012189 AddRHS));
12190 SI.setOperand(0, I->getOperand(0));
12191 AddToWorkList(I);
12192 return &SI;
12193 }
12194 }
12195 return 0;
12196}
12197
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012198Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012199 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012200
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012201 if (!EV.hasIndices())
12202 return ReplaceInstUsesWith(EV, Agg);
12203
12204 if (Constant *C = dyn_cast<Constant>(Agg)) {
12205 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012206 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012207
12208 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012209 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012210
12211 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12212 // Extract the element indexed by the first index out of the constant
12213 Value *V = C->getOperand(*EV.idx_begin());
12214 if (EV.getNumIndices() > 1)
12215 // Extract the remaining indices out of the constant indexed by the
12216 // first index
12217 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12218 else
12219 return ReplaceInstUsesWith(EV, V);
12220 }
12221 return 0; // Can't handle other constants
12222 }
12223 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12224 // We're extracting from an insertvalue instruction, compare the indices
12225 const unsigned *exti, *exte, *insi, *inse;
12226 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12227 exte = EV.idx_end(), inse = IV->idx_end();
12228 exti != exte && insi != inse;
12229 ++exti, ++insi) {
12230 if (*insi != *exti)
12231 // The insert and extract both reference distinctly different elements.
12232 // This means the extract is not influenced by the insert, and we can
12233 // replace the aggregate operand of the extract with the aggregate
12234 // operand of the insert. i.e., replace
12235 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12236 // %E = extractvalue { i32, { i32 } } %I, 0
12237 // with
12238 // %E = extractvalue { i32, { i32 } } %A, 0
12239 return ExtractValueInst::Create(IV->getAggregateOperand(),
12240 EV.idx_begin(), EV.idx_end());
12241 }
12242 if (exti == exte && insi == inse)
12243 // Both iterators are at the end: Index lists are identical. Replace
12244 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12245 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12246 // with "i32 42"
12247 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12248 if (exti == exte) {
12249 // The extract list is a prefix of the insert list. i.e. replace
12250 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12251 // %E = extractvalue { i32, { i32 } } %I, 1
12252 // with
12253 // %X = extractvalue { i32, { i32 } } %A, 1
12254 // %E = insertvalue { i32 } %X, i32 42, 0
12255 // by switching the order of the insert and extract (though the
12256 // insertvalue should be left in, since it may have other uses).
12257 Value *NewEV = InsertNewInstBefore(
12258 ExtractValueInst::Create(IV->getAggregateOperand(),
12259 EV.idx_begin(), EV.idx_end()),
12260 EV);
12261 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12262 insi, inse);
12263 }
12264 if (insi == inse)
12265 // The insert list is a prefix of the extract list
12266 // We can simply remove the common indices from the extract and make it
12267 // operate on the inserted value instead of the insertvalue result.
12268 // i.e., replace
12269 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12270 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12271 // with
12272 // %E extractvalue { i32 } { i32 42 }, 0
12273 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12274 exti, exte);
12275 }
12276 // Can't simplify extracts from other values. Note that nested extracts are
12277 // already simplified implicitely by the above (extract ( extract (insert) )
12278 // will be translated into extract ( insert ( extract ) ) first and then just
12279 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012280 return 0;
12281}
12282
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012283/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12284/// is to leave as a vector operation.
12285static bool CheapToScalarize(Value *V, bool isConstant) {
12286 if (isa<ConstantAggregateZero>(V))
12287 return true;
12288 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12289 if (isConstant) return true;
12290 // If all elts are the same, we can extract.
12291 Constant *Op0 = C->getOperand(0);
12292 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12293 if (C->getOperand(i) != Op0)
12294 return false;
12295 return true;
12296 }
12297 Instruction *I = dyn_cast<Instruction>(V);
12298 if (!I) return false;
12299
12300 // Insert element gets simplified to the inserted element or is deleted if
12301 // this is constant idx extract element and its a constant idx insertelt.
12302 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12303 isa<ConstantInt>(I->getOperand(2)))
12304 return true;
12305 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12306 return true;
12307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12308 if (BO->hasOneUse() &&
12309 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12310 CheapToScalarize(BO->getOperand(1), isConstant)))
12311 return true;
12312 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12313 if (CI->hasOneUse() &&
12314 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12315 CheapToScalarize(CI->getOperand(1), isConstant)))
12316 return true;
12317
12318 return false;
12319}
12320
12321/// Read and decode a shufflevector mask.
12322///
12323/// It turns undef elements into values that are larger than the number of
12324/// elements in the input.
12325static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12326 unsigned NElts = SVI->getType()->getNumElements();
12327 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12328 return std::vector<unsigned>(NElts, 0);
12329 if (isa<UndefValue>(SVI->getOperand(2)))
12330 return std::vector<unsigned>(NElts, 2*NElts);
12331
12332 std::vector<unsigned> Result;
12333 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012334 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12335 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012336 Result.push_back(NElts*2); // undef -> 8
12337 else
Gabor Greif17396002008-06-12 21:37:33 +000012338 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012339 return Result;
12340}
12341
12342/// FindScalarElement - Given a vector and an element number, see if the scalar
12343/// value is already around as a register, for example if it were inserted then
12344/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012345static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012346 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012347 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12348 const VectorType *PTy = cast<VectorType>(V->getType());
12349 unsigned Width = PTy->getNumElements();
12350 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012351 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012352
12353 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012354 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012355 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012356 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012357 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12358 return CP->getOperand(EltNo);
12359 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12360 // If this is an insert to a variable element, we don't know what it is.
12361 if (!isa<ConstantInt>(III->getOperand(2)))
12362 return 0;
12363 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12364
12365 // If this is an insert to the element we are looking for, return the
12366 // inserted value.
12367 if (EltNo == IIElt)
12368 return III->getOperand(1);
12369
12370 // Otherwise, the insertelement doesn't modify the value, recurse on its
12371 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012372 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012373 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012374 unsigned LHSWidth =
12375 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012376 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012377 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012378 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012379 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012380 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012381 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012382 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012383 }
12384
12385 // Otherwise, we don't know.
12386 return 0;
12387}
12388
12389Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012390 // If vector val is undef, replace extract with scalar undef.
12391 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012392 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012393
12394 // If vector val is constant 0, replace extract with scalar 0.
12395 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012396 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012397
12398 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012399 // If vector val is constant with all elements the same, replace EI with
12400 // that element. When the elements are not identical, we cannot replace yet
12401 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012402 Constant *op0 = C->getOperand(0);
12403 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12404 if (C->getOperand(i) != op0) {
12405 op0 = 0;
12406 break;
12407 }
12408 if (op0)
12409 return ReplaceInstUsesWith(EI, op0);
12410 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012411
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012412 // If extracting a specified index from the vector, see if we can recursively
12413 // find a previously computed scalar that was inserted into the vector.
12414 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12415 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedmanf34209b2009-07-18 19:04:16 +000012416 unsigned VectorWidth =
12417 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012418
12419 // If this is extracting an invalid index, turn this into undef, to avoid
12420 // crashing the code below.
12421 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012422 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012423
12424 // This instruction only demands the single element from the input vector.
12425 // If the input vector has a single use, simplify it based on this use
12426 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012427 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012428 APInt UndefElts(VectorWidth, 0);
12429 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012430 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012431 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012432 EI.setOperand(0, V);
12433 return &EI;
12434 }
12435 }
12436
Owen Anderson24be4c12009-07-03 00:17:18 +000012437 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012438 return ReplaceInstUsesWith(EI, Elt);
12439
12440 // If the this extractelement is directly using a bitcast from a vector of
12441 // the same number of elements, see if we can find the source element from
12442 // it. In this case, we will end up needing to bitcast the scalars.
12443 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12444 if (const VectorType *VT =
12445 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12446 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012447 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12448 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012449 return new BitCastInst(Elt, EI.getType());
12450 }
12451 }
12452
12453 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12454 if (I->hasOneUse()) {
12455 // Push extractelement into predecessor operation if legal and
12456 // profitable to do so
12457 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12458 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12459 if (CheapToScalarize(BO, isConstantElt)) {
12460 ExtractElementInst *newEI0 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012461 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012462 EI.getName()+".lhs");
12463 ExtractElementInst *newEI1 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012464 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012465 EI.getName()+".rhs");
12466 InsertNewInstBefore(newEI0, EI);
12467 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012468 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012469 }
12470 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012471 unsigned AS =
12472 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012473 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Mon P Wangcb737b22009-08-13 05:12:13 +000012474 PointerType::get(EI.getType(), AS),*I);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012475 GetElementPtrInst *GEP =
12476 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohman17f46f72009-07-28 01:40:03 +000012477 cast<GEPOperator>(GEP)->setIsInBounds(true);
Mon P Wangcb737b22009-08-13 05:12:13 +000012478 InsertNewInstBefore(GEP, *I);
12479 LoadInst* Load = new LoadInst(GEP, "tmp");
12480 InsertNewInstBefore(Load, *I);
12481 return ReplaceInstUsesWith(EI, Load);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012482 }
12483 }
12484 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12485 // Extracting the inserted element?
12486 if (IE->getOperand(2) == EI.getOperand(1))
12487 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12488 // If the inserted and extracted elements are constants, they must not
12489 // be the same value, extract from the pre-inserted value instead.
12490 if (isa<Constant>(IE->getOperand(2)) &&
12491 isa<Constant>(EI.getOperand(1))) {
12492 AddUsesToWorkList(EI);
12493 EI.setOperand(0, IE->getOperand(0));
12494 return &EI;
12495 }
12496 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12497 // If this is extracting an element from a shufflevector, figure out where
12498 // it came from and extract from the appropriate input element instead.
12499 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12500 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12501 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012502 unsigned LHSWidth =
12503 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12504
12505 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012506 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012507 else if (SrcIdx < LHSWidth*2) {
12508 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012509 Src = SVI->getOperand(1);
12510 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012511 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012512 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012513 return ExtractElementInst::Create(Src,
Owen Anderson35b47072009-08-13 21:58:54 +000012514 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012515 }
12516 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012517 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012518 }
12519 return 0;
12520}
12521
12522/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12523/// elements from either LHS or RHS, return the shuffle mask and true.
12524/// Otherwise, return false.
12525static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012526 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012527 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012528 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12529 "Invalid CollectSingleShuffleElements");
12530 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12531
12532 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012533 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012534 return true;
12535 } else if (V == LHS) {
12536 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012537 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012538 return true;
12539 } else if (V == RHS) {
12540 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012541 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012542 return true;
12543 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12544 // If this is an insert of an extract from some other vector, include it.
12545 Value *VecOp = IEI->getOperand(0);
12546 Value *ScalarOp = IEI->getOperand(1);
12547 Value *IdxOp = IEI->getOperand(2);
12548
12549 if (!isa<ConstantInt>(IdxOp))
12550 return false;
12551 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12552
12553 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12554 // Okay, we can handle this if the vector we are insertinting into is
12555 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012556 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012557 // If so, update the mask to reflect the inserted undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012558 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012559 return true;
12560 }
12561 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12562 if (isa<ConstantInt>(EI->getOperand(1)) &&
12563 EI->getOperand(0)->getType() == V->getType()) {
12564 unsigned ExtractedIdx =
12565 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12566
12567 // This must be extracting from either LHS or RHS.
12568 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12569 // Okay, we can handle this if the vector we are insertinting into is
12570 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012571 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012572 // If so, update the mask to reflect the inserted value.
12573 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012574 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012575 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012576 } else {
12577 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012578 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012579 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012580
12581 }
12582 return true;
12583 }
12584 }
12585 }
12586 }
12587 }
12588 // TODO: Handle shufflevector here!
12589
12590 return false;
12591}
12592
12593/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12594/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12595/// that computes V and the LHS value of the shuffle.
12596static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012597 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012598 assert(isa<VectorType>(V->getType()) &&
12599 (RHS == 0 || V->getType() == RHS->getType()) &&
12600 "Invalid shuffle!");
12601 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12602
12603 if (isa<UndefValue>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012604 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012605 return V;
12606 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson35b47072009-08-13 21:58:54 +000012607 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012608 return V;
12609 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12610 // If this is an insert of an extract from some other vector, include it.
12611 Value *VecOp = IEI->getOperand(0);
12612 Value *ScalarOp = IEI->getOperand(1);
12613 Value *IdxOp = IEI->getOperand(2);
12614
12615 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12616 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12617 EI->getOperand(0)->getType() == V->getType()) {
12618 unsigned ExtractedIdx =
12619 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12620 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12621
12622 // Either the extracted from or inserted into vector must be RHSVec,
12623 // otherwise we'd end up with a shuffle of three inputs.
12624 if (EI->getOperand(0) == RHS || RHS == 0) {
12625 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012626 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012627 Mask[InsertedIdx % NumElts] =
Owen Anderson35b47072009-08-13 21:58:54 +000012628 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012629 return V;
12630 }
12631
12632 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012633 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12634 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012635 // Everything but the extracted element is replaced with the RHS.
12636 for (unsigned i = 0; i != NumElts; ++i) {
12637 if (i != InsertedIdx)
Owen Anderson35b47072009-08-13 21:58:54 +000012638 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012639 }
12640 return V;
12641 }
12642
12643 // If this insertelement is a chain that comes from exactly these two
12644 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012645 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12646 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012647 return EI->getOperand(0);
12648
12649 }
12650 }
12651 }
12652 // TODO: Handle shufflevector here!
12653
12654 // Otherwise, can't do anything fancy. Return an identity vector.
12655 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson35b47072009-08-13 21:58:54 +000012656 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012657 return V;
12658}
12659
12660Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12661 Value *VecOp = IE.getOperand(0);
12662 Value *ScalarOp = IE.getOperand(1);
12663 Value *IdxOp = IE.getOperand(2);
12664
12665 // Inserting an undef or into an undefined place, remove this.
12666 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12667 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012668
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012669 // If the inserted element was extracted from some other vector, and if the
12670 // indexes are constant, try to turn this into a shufflevector operation.
12671 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12672 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12673 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012674 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012675 unsigned ExtractedIdx =
12676 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12677 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12678
12679 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12680 return ReplaceInstUsesWith(IE, VecOp);
12681
12682 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012683 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012684
12685 // If we are extracting a value from a vector, then inserting it right
12686 // back into the same place, just use the input vector.
12687 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12688 return ReplaceInstUsesWith(IE, VecOp);
12689
12690 // We could theoretically do this for ANY input. However, doing so could
12691 // turn chains of insertelement instructions into a chain of shufflevector
12692 // instructions, and right now we do not merge shufflevectors. As such,
12693 // only do this in a situation where it is clear that there is benefit.
12694 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12695 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12696 // the values of VecOp, except then one read from EIOp0.
12697 // Build a new shuffle mask.
12698 std::vector<Constant*> Mask;
12699 if (isa<UndefValue>(VecOp))
Owen Anderson35b47072009-08-13 21:58:54 +000012700 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012701 else {
12702 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson35b47072009-08-13 21:58:54 +000012703 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012704 NumVectorElts));
12705 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012706 Mask[InsertedIdx] =
Owen Anderson35b47072009-08-13 21:58:54 +000012707 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012708 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson2f422e02009-07-28 21:19:26 +000012709 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012710 }
12711
12712 // If this insertelement isn't used by some other insertelement, turn it
12713 // (and any insertelements it points to), into one big shuffle.
12714 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12715 std::vector<Constant*> Mask;
12716 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012717 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012718 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012719 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012720 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012721 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012722 }
12723 }
12724 }
12725
Eli Friedmanbefee262009-06-06 20:08:03 +000012726 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12727 APInt UndefElts(VWidth, 0);
12728 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12729 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12730 return &IE;
12731
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012732 return 0;
12733}
12734
12735
12736Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12737 Value *LHS = SVI.getOperand(0);
12738 Value *RHS = SVI.getOperand(1);
12739 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12740
12741 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012742
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012743 // Undefined shuffle mask -> undefined value.
12744 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012745 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012746
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012747 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012748
12749 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12750 return 0;
12751
Evan Cheng63295ab2009-02-03 10:05:09 +000012752 APInt UndefElts(VWidth, 0);
12753 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12754 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012755 LHS = SVI.getOperand(0);
12756 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012757 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012758 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012759
12760 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12761 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12762 if (LHS == RHS || isa<UndefValue>(LHS)) {
12763 if (isa<UndefValue>(LHS) && LHS == RHS) {
12764 // shuffle(undef,undef,mask) -> undef.
12765 return ReplaceInstUsesWith(SVI, LHS);
12766 }
12767
12768 // Remap any references to RHS to use LHS.
12769 std::vector<Constant*> Elts;
12770 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12771 if (Mask[i] >= 2*e)
Owen Anderson35b47072009-08-13 21:58:54 +000012772 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012773 else {
12774 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012775 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012776 Mask[i] = 2*e; // Turn into undef.
Owen Anderson35b47072009-08-13 21:58:54 +000012777 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012778 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012779 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson35b47072009-08-13 21:58:54 +000012780 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012781 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012782 }
12783 }
12784 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012785 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012786 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012787 LHS = SVI.getOperand(0);
12788 RHS = SVI.getOperand(1);
12789 MadeChange = true;
12790 }
12791
12792 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12793 bool isLHSID = true, isRHSID = true;
12794
12795 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12796 if (Mask[i] >= e*2) continue; // Ignore undef values.
12797 // Is this an identity shuffle of the LHS value?
12798 isLHSID &= (Mask[i] == i);
12799
12800 // Is this an identity shuffle of the RHS value?
12801 isRHSID &= (Mask[i]-e == i);
12802 }
12803
12804 // Eliminate identity shuffles.
12805 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12806 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12807
12808 // If the LHS is a shufflevector itself, see if we can combine it with this
12809 // one without producing an unusual shuffle. Here we are really conservative:
12810 // we are absolutely afraid of producing a shuffle mask not in the input
12811 // program, because the code gen may not be smart enough to turn a merged
12812 // shuffle into two specific shuffles: it may produce worse code. As such,
12813 // we only merge two shuffles if the result is one of the two input shuffle
12814 // masks. In this case, merging the shuffles just removes one instruction,
12815 // which we know is safe. This is good for things like turning:
12816 // (splat(splat)) -> splat.
12817 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12818 if (isa<UndefValue>(RHS)) {
12819 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12820
12821 std::vector<unsigned> NewMask;
12822 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12823 if (Mask[i] >= 2*e)
12824 NewMask.push_back(2*e);
12825 else
12826 NewMask.push_back(LHSMask[Mask[i]]);
12827
12828 // If the result mask is equal to the src shuffle or this shuffle mask, do
12829 // the replacement.
12830 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012831 unsigned LHSInNElts =
12832 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012833 std::vector<Constant*> Elts;
12834 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012835 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson35b47072009-08-13 21:58:54 +000012836 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012837 } else {
Owen Anderson35b47072009-08-13 21:58:54 +000012838 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012839 }
12840 }
12841 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12842 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012843 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012844 }
12845 }
12846 }
12847
12848 return MadeChange ? &SVI : 0;
12849}
12850
12851
12852
12853
12854/// TryToSinkInstruction - Try to move the specified instruction from its
12855/// current block into the beginning of DestBlock, which can only happen if it's
12856/// safe to move the instruction past all of the instructions between it and the
12857/// end of its block.
12858static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12859 assert(I->hasOneUse() && "Invariants didn't hold!");
12860
12861 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012862 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012863 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012864
12865 // Do not sink alloca instructions out of the entry block.
12866 if (isa<AllocaInst>(I) && I->getParent() ==
12867 &DestBlock->getParent()->getEntryBlock())
12868 return false;
12869
12870 // We can only sink load instructions if there is nothing between the load and
12871 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012872 if (I->mayReadFromMemory()) {
12873 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012874 Scan != E; ++Scan)
12875 if (Scan->mayWriteToMemory())
12876 return false;
12877 }
12878
Dan Gohman514277c2008-05-23 21:05:58 +000012879 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012880
Dale Johannesen24339f12009-03-03 01:09:07 +000012881 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012882 I->moveBefore(InsertPos);
12883 ++NumSunkInst;
12884 return true;
12885}
12886
12887
12888/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12889/// all reachable code to the worklist.
12890///
12891/// This has a couple of tricks to make the code faster and more powerful. In
12892/// particular, we constant fold and DCE instructions as we go, to avoid adding
12893/// them to the worklist (this significantly speeds up instcombine on code where
12894/// many instructions are dead or constant). Additionally, if we find a branch
12895/// whose condition is a known constant, we only visit the reachable successors.
12896///
12897static void AddReachableCodeToWorklist(BasicBlock *BB,
12898 SmallPtrSet<BasicBlock*, 64> &Visited,
12899 InstCombiner &IC,
12900 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012901 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012902 Worklist.push_back(BB);
12903
12904 while (!Worklist.empty()) {
12905 BB = Worklist.back();
12906 Worklist.pop_back();
12907
12908 // We have now visited this block! If we've already been here, ignore it.
12909 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012910
12911 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012912 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12913 Instruction *Inst = BBI++;
12914
12915 // DCE instruction if trivially dead.
12916 if (isInstructionTriviallyDead(Inst)) {
12917 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +000012918 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012919 Inst->eraseFromParent();
12920 continue;
12921 }
12922
12923 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012924 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000012925 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12926 << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012927 Inst->replaceAllUsesWith(C);
12928 ++NumConstProp;
12929 Inst->eraseFromParent();
12930 continue;
12931 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012932
Devang Patel794140c2008-11-19 18:56:50 +000012933 // If there are two consecutive llvm.dbg.stoppoint calls then
12934 // it is likely that the optimizer deleted code in between these
12935 // two intrinsics.
12936 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12937 if (DBI_Next) {
12938 if (DBI_Prev
12939 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12940 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12941 IC.RemoveFromWorkList(DBI_Prev);
12942 DBI_Prev->eraseFromParent();
12943 }
12944 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012945 } else {
12946 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012947 }
12948
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012949 IC.AddToWorkList(Inst);
12950 }
12951
12952 // Recursively visit successors. If this is a branch or switch on a
12953 // constant, only visit the reachable successor.
12954 TerminatorInst *TI = BB->getTerminator();
12955 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12956 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12957 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012958 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012959 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012960 continue;
12961 }
12962 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12963 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12964 // See if this is an explicit destination.
12965 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12966 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012967 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012968 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012969 continue;
12970 }
12971
12972 // Otherwise it is the default destination.
12973 Worklist.push_back(SI->getSuccessor(0));
12974 continue;
12975 }
12976 }
12977
12978 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12979 Worklist.push_back(TI->getSuccessor(i));
12980 }
12981}
12982
12983bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12984 bool Changed = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012985 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012986
Daniel Dunbar005975c2009-07-25 00:23:56 +000012987 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12988 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012989
12990 {
12991 // Do a depth-first traversal of the function, populate the worklist with
12992 // the reachable instructions. Ignore blocks that are not reachable. Keep
12993 // track of which blocks we visit.
12994 SmallPtrSet<BasicBlock*, 64> Visited;
12995 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12996
12997 // Do a quick scan over the function. If we find any blocks that are
12998 // unreachable, remove any instructions inside of them. This prevents
12999 // the instcombine code from having to deal with some bad special cases.
13000 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13001 if (!Visited.count(BB)) {
13002 Instruction *Term = BB->getTerminator();
13003 while (Term != BB->begin()) { // Remove instrs bottom-up
13004 BasicBlock::iterator I = Term; --I;
13005
Chris Lattner8a6411c2009-08-23 04:37:46 +000013006 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +000013007 // A debug intrinsic shouldn't force another iteration if we weren't
13008 // going to do one without it.
13009 if (!isa<DbgInfoIntrinsic>(I)) {
13010 ++NumDeadInst;
13011 Changed = true;
13012 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013013 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000013014 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013015 I->eraseFromParent();
13016 }
13017 }
13018 }
13019
13020 while (!Worklist.empty()) {
13021 Instruction *I = RemoveOneFromWorkList();
13022 if (I == 0) continue; // skip null values.
13023
13024 // Check to see if we can DCE the instruction.
13025 if (isInstructionTriviallyDead(I)) {
13026 // Add operands to the worklist.
13027 if (I->getNumOperands() < 4)
13028 AddUsesToWorkList(*I);
13029 ++NumDeadInst;
13030
Chris Lattner8a6411c2009-08-23 04:37:46 +000013031 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013032
13033 I->eraseFromParent();
13034 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013035 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013036 continue;
13037 }
13038
13039 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000013040 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013041 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013042
13043 // Add operands to the worklist.
13044 AddUsesToWorkList(*I);
13045 ReplaceInstUsesWith(*I, C);
13046
13047 ++NumConstProp;
13048 I->eraseFromParent();
13049 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013050 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013051 continue;
13052 }
13053
Eli Friedman5c619182009-07-15 22:13:34 +000013054 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000013055 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000013056 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13057 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000013058 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13059 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000013060 if (NewC != CE) {
13061 i->set(NewC);
13062 Changed = true;
13063 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000013064 }
13065
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013066 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013067 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013068 BasicBlock *BB = I->getParent();
13069 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13070 if (UserParent != BB) {
13071 bool UserIsSuccessor = false;
13072 // See if the user is one of our successors.
13073 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13074 if (*SI == UserParent) {
13075 UserIsSuccessor = true;
13076 break;
13077 }
13078
13079 // If the user is one of our immediate successors, and if that successor
13080 // only has us as a predecessors (we'd have to split the critical edge
13081 // otherwise), we can keep going.
13082 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13083 next(pred_begin(UserParent)) == pred_end(UserParent))
13084 // Okay, the CFG is simple enough, try to sink this instruction.
13085 Changed |= TryToSinkInstruction(I, UserParent);
13086 }
13087 }
13088
13089 // Now that we have an instruction, try combining it to simplify it...
13090#ifndef NDEBUG
13091 std::string OrigI;
13092#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +000013093 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013094 if (Instruction *Result = visit(*I)) {
13095 ++NumCombined;
13096 // Should we replace the old instruction with a new one?
13097 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +000013098 DEBUG(errs() << "IC: Old = " << *I << '\n'
13099 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013100
13101 // Everything uses the new instruction now.
13102 I->replaceAllUsesWith(Result);
13103
13104 // Push the new instruction and any users onto the worklist.
13105 AddToWorkList(Result);
13106 AddUsersToWorkList(*Result);
13107
13108 // Move the name to the new instruction first.
13109 Result->takeName(I);
13110
13111 // Insert the new instruction into the basic block...
13112 BasicBlock *InstParent = I->getParent();
13113 BasicBlock::iterator InsertPos = I;
13114
13115 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13116 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13117 ++InsertPos;
13118
13119 InstParent->getInstList().insert(InsertPos, Result);
13120
13121 // Make sure that we reprocess all operands now that we reduced their
13122 // use counts.
13123 AddUsesToWorkList(*I);
13124
13125 // Instructions can end up on the worklist more than once. Make sure
13126 // we do not process an instruction that has been deleted.
13127 RemoveFromWorkList(I);
13128
13129 // Erase the old instruction.
13130 InstParent->getInstList().erase(I);
13131 } else {
13132#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +000013133 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13134 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013135#endif
13136
13137 // If the instruction was modified, it's possible that it is now dead.
13138 // if so, remove it.
13139 if (isInstructionTriviallyDead(I)) {
13140 // Make sure we process all operands now that we are reducing their
13141 // use counts.
13142 AddUsesToWorkList(*I);
13143
13144 // Instructions may end up in the worklist more than once. Erase all
13145 // occurrences of this instruction.
13146 RemoveFromWorkList(I);
13147 I->eraseFromParent();
13148 } else {
13149 AddToWorkList(I);
13150 AddUsersToWorkList(*I);
13151 }
13152 }
13153 Changed = true;
13154 }
13155 }
13156
13157 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013158
13159 // Do an explicit clear, this shrinks the map if needed.
13160 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013161 return Changed;
13162}
13163
13164
13165bool InstCombiner::runOnFunction(Function &F) {
13166 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013167 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013168
13169 bool EverMadeChange = false;
13170
13171 // Iterate while there is work to do.
13172 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013173 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013174 EverMadeChange = true;
13175 return EverMadeChange;
13176}
13177
13178FunctionPass *llvm::createInstructionCombiningPass() {
13179 return new InstCombiner();
13180}