blob: b9b4ccb6cfb82a66fabec4cab970357cac7acc48 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
Dan Gohman9545fb02009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
49#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
54#include "llvm/Support/InstVisitor.h"
55#include "llvm/Support/MathExtras.h"
56#include "llvm/Support/PatternMatch.h"
57#include "llvm/Support/Compiler.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000058#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059#include "llvm/ADT/DenseMap.h"
60#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/SmallPtrSet.h"
62#include "llvm/ADT/Statistic.h"
63#include "llvm/ADT/STLExtras.h"
64#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000065#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066#include <sstream>
67using namespace llvm;
68using namespace llvm::PatternMatch;
69
70STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76namespace {
77 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
80 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000081 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 DenseMap<Instruction*, unsigned> WorklistMap;
83 TargetData *TD;
84 bool MustPreserveLCSSA;
85 public:
86 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000087 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Owen Anderson175b6542009-07-22 00:24:57 +000089 LLVMContext *Context;
90 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +000091
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096 Worklist.push_back(I);
97 }
98
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
103
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
106
107 WorklistMap.erase(It);
108 }
109
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
112 Worklist.pop_back();
113 WorklistMap.erase(I);
114 return I;
115 }
116
117
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
122 void AddUsersToWorkList(Value &I) {
123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
124 UI != UE; ++UI)
125 AddToWorkList(cast<Instruction>(*UI));
126 }
127
128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
130 ///
131 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 AddToWorkList(Op);
135 }
136
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
140 ///
141 /// Return the specified operand before it is turned into an undef.
142 ///
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
145
Gabor Greif17396002008-06-12 21:37:33 +0000146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 AddToWorkList(Op);
149 // Set the operand to undef to drop the use.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000150 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 }
152
153 return R;
154 }
155
156 public:
157 virtual bool runOnFunction(Function &F);
158
159 bool DoOneIteration(Function &F, unsigned ItNum);
160
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 AU.addPreservedID(LCSSAID);
163 AU.setPreservesCFG();
164 }
165
Dan Gohmana80e2712009-07-21 23:21:54 +0000166 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
170 // Return Value:
171 // null - No change was made
172 // I - Change was made, I is still valid, I may be dead though
173 // otherwise - Change was made, replace I with returned instruction
174 //
175 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000176 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000178 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000180 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner57e66fa2009-07-23 05:46:22 +0000196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000198 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
211 Instruction *LHS,
212 ConstantInt *RHS);
213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
215
Dan Gohman17f46f72009-07-28 01:40:03 +0000216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 ICmpInst::Predicate Cond, Instruction &I);
218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
219 BinaryOperator &I);
220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
222 Instruction *commonPointerCastTransforms(CastInst &CI);
223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000226 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000232 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000233 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 Instruction *visitBitCast(BitCastInst &CI);
235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
236 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
244 Instruction *visitAllocationInst(AllocationInst &AI);
245 Instruction *visitFreeInst(FreeInst &FI);
246 Instruction *visitLoadInst(LoadInst &LI);
247 Instruction *visitStoreInst(StoreInst &SI);
248 Instruction *visitBranchInst(BranchInst &BI);
249 Instruction *visitSwitchInst(SwitchInst &SI);
250 Instruction *visitInsertElementInst(InsertElementInst &IE);
251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254
255 // visitInstruction - Specify what to return for unhandled instructions...
256 Instruction *visitInstruction(Instruction &I) { return 0; }
257
258 private:
259 Instruction *visitCallSite(CallSite CS);
260 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000261 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
266
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267
268 public:
269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
271 //
272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
277 AddToWorkList(New);
278 return New;
279 }
280
281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
283 /// cast.
284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
285 Instruction &Pos) {
286 if (V->getType() == Ty) return V;
287
288 if (Constant *CV = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000289 return ConstantExpr::getCast(opc, CV, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290
Gabor Greifa645dd32008-05-16 19:29:10 +0000291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 AddToWorkList(C);
293 return C;
294 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000295
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
298 }
299
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
305 // modified.
306 //
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
308 AddUsersToWorkList(I); // Add all modified instrs to worklist
309 if (&I != V) {
310 I.replaceAllUsesWith(V);
311 return &I;
312 } else {
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
Owen Andersonb99ecca2009-07-30 23:03:37 +0000315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 return &I;
317 }
318 }
319
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
323 // this function.
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
327 RemoveFromWorkList(&I);
328 I.eraseFromParent();
329 return 0; // Don't do anything with FI
330 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000331
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 }
336
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
340 }
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344
345 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346
347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
349 bool SimplifyCommutative(BinaryOperator &I);
350
351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
354
Chris Lattner676c78e2009-01-31 08:15:18 +0000355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
359 unsigned Depth);
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000362 unsigned Depth=0);
363
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
368
Evan Cheng63295ab2009-02-03 10:05:09 +0000369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
376
377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
383
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
387
388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
389 bool isSub, Instruction &I);
390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
391 bool isSigned, bool Inside, Instruction &IB);
392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
393 Instruction *MatchBSwap(BinaryOperator &I);
394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000396 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398
399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000400
Dan Gohman8fd520a2009-06-15 22:12:54 +0000401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000402 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000405
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000407}
408
Dan Gohman089efff2008-05-13 00:00:25 +0000409char InstCombiner::ID = 0;
410static RegisterPass<InstCombiner>
411X("instcombine", "Combine redundant instructions");
412
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413// getComplexity: Assign a complexity or rank value to LLVM Values...
414// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson15b39322009-07-13 04:09:18 +0000415static unsigned getComplexity(LLVMContext *Context, Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000416 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000419 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 return 3;
421 return 4;
422 }
423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
425}
426
427// isOnlyUse - Return true if this instruction will be deleted if we stop using
428// it.
429static bool isOnlyUse(Value *V) {
430 return V->hasOneUse() || isa<Constant>(V);
431}
432
433// getPromotedType - Return the specified type promoted as it would be to pass
434// though a va_arg area...
435static const Type *getPromotedType(const Type *Ty) {
436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
438 return Type::Int32Ty;
439 }
440 return Ty;
441}
442
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 return 0;
455}
456
457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000466
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
469
470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
473
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000475 DstTy,
476 TD ? TD->getIntPtrType() : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
480 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
481 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
482 Res = 0;
483
484 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485}
486
487/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
488/// in any code being generated. It does not require codegen if V is simple
489/// enough or if the cast can be folded into other casts.
490static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
491 const Type *Ty, TargetData *TD) {
492 if (V->getType() == Ty || isa<Constant>(V)) return false;
493
494 // If this is another cast that can be eliminated, it isn't codegen either.
495 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000496 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 return false;
498 return true;
499}
500
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501// SimplifyCommutative - This performs a few simplifications for commutative
502// operators:
503//
504// 1. Order operands such that they are listed from right (least complex) to
505// left (most complex). This puts constants before unary operators before
506// binary operators.
507//
508// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
509// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
510//
511bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
512 bool Changed = false;
Owen Anderson15b39322009-07-13 04:09:18 +0000513 if (getComplexity(Context, I.getOperand(0)) <
514 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 Changed = !I.swapOperands();
516
517 if (!I.isAssociative()) return Changed;
518 Instruction::BinaryOps Opcode = I.getOpcode();
519 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
520 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
521 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000522 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 cast<Constant>(I.getOperand(1)),
524 cast<Constant>(Op->getOperand(1)));
525 I.setOperand(0, Op->getOperand(0));
526 I.setOperand(1, Folded);
527 return true;
528 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
529 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
530 isOnlyUse(Op) && isOnlyUse(Op1)) {
531 Constant *C1 = cast<Constant>(Op->getOperand(1));
532 Constant *C2 = cast<Constant>(Op1->getOperand(1));
533
534 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000535 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000536 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 Op1->getOperand(0),
538 Op1->getName(), &I);
539 AddToWorkList(New);
540 I.setOperand(0, New);
541 I.setOperand(1, Folded);
542 return true;
543 }
544 }
545 return Changed;
546}
547
548/// SimplifyCompare - For a CmpInst this function just orders the operands
549/// so that theyare listed from right (least complex) to left (most complex).
550/// This puts constants before unary operators before binary operators.
551bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson15b39322009-07-13 04:09:18 +0000552 if (getComplexity(Context, I.getOperand(0)) >=
553 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
562//
Owen Anderson5349f052009-07-06 23:00:19 +0000563static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Anderson76f49252009-07-13 22:18:28 +0000564 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 return BinaryOperator::getNegArgument(V);
566
567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000569 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000573 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000574
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 return 0;
576}
577
Dan Gohman7ce405e2009-06-04 22:49:04 +0000578// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
579// instruction if the LHS is a constant negative zero (which is the 'negate'
580// form).
581//
Owen Anderson5349f052009-07-06 23:00:19 +0000582static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Anderson76f49252009-07-13 22:18:28 +0000583 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000584 return BinaryOperator::getFNegArgument(V);
585
586 // Constants can be considered to be negated values if they can be folded.
587 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000588 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000589
590 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
591 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000592 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000593
594 return 0;
595}
596
Owen Anderson5349f052009-07-06 23:00:19 +0000597static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598 if (BinaryOperator::isNot(V))
599 return BinaryOperator::getNotArgument(V);
600
601 // Constants can be considered to be not'ed values...
602 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersoneacb44d2009-07-24 23:12:02 +0000603 return ConstantInt::get(*Context, ~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 return 0;
605}
606
607// dyn_castFoldableMul - If this value is a multiply that can be folded into
608// other computations (because it has a constant operand), return the
609// non-constant operand of the multiply, and set CST to point to the multiplier.
610// Otherwise, return null.
611//
Owen Anderson24be4c12009-07-03 00:17:18 +0000612static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson5349f052009-07-06 23:00:19 +0000613 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 if (V->hasOneUse() && V->getType()->isInteger())
615 if (Instruction *I = dyn_cast<Instruction>(V)) {
616 if (I->getOpcode() == Instruction::Mul)
617 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
618 return I->getOperand(0);
619 if (I->getOpcode() == Instruction::Shl)
620 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
621 // The multiplier is really 1 << CST.
622 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
623 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersoneacb44d2009-07-24 23:12:02 +0000624 CST = ConstantInt::get(*Context, APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 return I->getOperand(0);
626 }
627 }
628 return 0;
629}
630
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631/// AddOne - Add one to a ConstantInt
Owen Anderson5349f052009-07-06 23:00:19 +0000632static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000633 return ConstantExpr::getAdd(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000634 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635}
636/// SubOne - Subtract one from a ConstantInt
Owen Anderson5349f052009-07-06 23:00:19 +0000637static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000638 return ConstantExpr::getSub(C,
Owen Andersoneacb44d2009-07-24 23:12:02 +0000639 ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
Owen Anderson24be4c12009-07-03 00:17:18 +0000643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson5349f052009-07-06 23:00:19 +0000644 LLVMContext *Context) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000645 uint32_t W = C1->getBitWidth();
646 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
647 if (sign) {
648 LHSExt.sext(W * 2);
649 RHSExt.sext(W * 2);
650 } else {
651 LHSExt.zext(W * 2);
652 RHSExt.zext(W * 2);
653 }
654
655 APInt MulExt = LHSExt * RHSExt;
656
657 if (sign) {
658 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
659 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
660 return MulExt.slt(Min) || MulExt.sgt(Max);
661 } else
662 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
663}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665
666/// ShrinkDemandedConstant - Check to see if the specified operand of the
667/// specified instruction is a constant integer. If so, check to see if there
668/// are any bits set in the constant that are not demanded. If so, shrink the
669/// constant and return true.
670static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson5349f052009-07-06 23:00:19 +0000671 APInt Demanded, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 assert(I && "No instruction?");
673 assert(OpNo < I->getNumOperands() && "Operand index too large");
674
675 // If the operand is not a constant integer, nothing to do.
676 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
677 if (!OpC) return false;
678
679 // If there are no bits set that aren't demanded, nothing to do.
680 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
681 if ((~Demanded & OpC->getValue()) == 0)
682 return false;
683
684 // This instruction is producing bits that are not demanded. Shrink the RHS.
685 Demanded &= OpC->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +0000686 I->setOperand(OpNo, ConstantInt::get(*Context, Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 return true;
688}
689
690// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
691// set of known zero and one bits, compute the maximum and minimum values that
692// could have the specified known zero and known one bits, returning them in
693// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000694static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 const APInt& KnownOne,
696 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000697 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
698 KnownZero.getBitWidth() == Min.getBitWidth() &&
699 KnownZero.getBitWidth() == Max.getBitWidth() &&
700 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701 APInt UnknownBits = ~(KnownZero|KnownOne);
702
703 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
704 // bit if it is unknown.
705 Min = KnownOne;
706 Max = KnownOne|UnknownBits;
707
Dan Gohman7934d592009-04-25 17:12:48 +0000708 if (UnknownBits.isNegative()) { // Sign bit is unknown
709 Min.set(Min.getBitWidth()-1);
710 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711 }
712}
713
714// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
715// a set of known zero and one bits, compute the maximum and minimum values that
716// could have the specified known zero and known one bits, returning them in
717// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000718static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000719 const APInt &KnownOne,
720 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000721 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
722 KnownZero.getBitWidth() == Min.getBitWidth() &&
723 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
725 APInt UnknownBits = ~(KnownZero|KnownOne);
726
727 // The minimum value is when the unknown bits are all zeros.
728 Min = KnownOne;
729 // The maximum value is when the unknown bits are all ones.
730 Max = KnownOne|UnknownBits;
731}
732
Chris Lattner676c78e2009-01-31 08:15:18 +0000733/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
734/// SimplifyDemandedBits knows about. See if the instruction has any
735/// properties that allow us to simplify its operands.
736bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000737 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000738 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
739 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
740
741 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
742 KnownZero, KnownOne, 0);
743 if (V == 0) return false;
744 if (V == &Inst) return true;
745 ReplaceInstUsesWith(Inst, V);
746 return true;
747}
748
749/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
750/// specified instruction operand if possible, updating it in place. It returns
751/// true if it made any change and false otherwise.
752bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
753 APInt &KnownZero, APInt &KnownOne,
754 unsigned Depth) {
755 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
756 KnownZero, KnownOne, Depth);
757 if (NewVal == 0) return false;
758 U.set(NewVal);
759 return true;
760}
761
762
763/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
764/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765/// that only the bits set in DemandedMask of the result of V are ever used
766/// downstream. Consequently, depending on the mask and V, it may be possible
767/// to replace V with a constant or one of its operands. In such cases, this
768/// function does the replacement and returns true. In all other cases, it
769/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000770/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771/// to be zero in the expression. These are provided to potentially allow the
772/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
773/// the expression. KnownOne and KnownZero always follow the invariant that
774/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
775/// the bits in KnownOne and KnownZero may only be accurate for those bits set
776/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
777/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000778///
779/// This returns null if it did not change anything and it permits no
780/// simplification. This returns V itself if it did some simplification of V's
781/// operands based on the information about what bits are demanded. This returns
782/// some other non-null value if it found out that V is equal to another value
783/// in the context where the specified bits are demanded, but not for all users.
784Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
785 APInt &KnownZero, APInt &KnownOne,
786 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 assert(V != 0 && "Null pointer of Value???");
788 assert(Depth <= 6 && "Limit Search Depth");
789 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000790 const Type *VTy = V->getType();
791 assert((TD || !isa<PointerType>(VTy)) &&
792 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000793 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
794 (!VTy->isIntOrIntVector() ||
795 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000796 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000798 "Value *V, DemandedMask, KnownZero and KnownOne "
799 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
801 // We know all of the bits for a constant!
802 KnownOne = CI->getValue() & DemandedMask;
803 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000804 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 }
Dan Gohman7934d592009-04-25 17:12:48 +0000806 if (isa<ConstantPointerNull>(V)) {
807 // We know all of the bits for a constant!
808 KnownOne.clear();
809 KnownZero = DemandedMask;
810 return 0;
811 }
812
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000813 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000815 if (DemandedMask == 0) { // Not demanding any bits from V.
816 if (isa<UndefValue>(V))
817 return 0;
Owen Andersonb99ecca2009-07-30 23:03:37 +0000818 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 }
820
Chris Lattner08817332009-01-31 08:24:16 +0000821 if (Depth == 6) // Limit search depth.
822 return 0;
823
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000824 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
825 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
826
Dan Gohman7934d592009-04-25 17:12:48 +0000827 Instruction *I = dyn_cast<Instruction>(V);
828 if (!I) {
829 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
830 return 0; // Only analyze instructions.
831 }
832
Chris Lattner08817332009-01-31 08:24:16 +0000833 // If there are multiple uses of this value and we aren't at the root, then
834 // we can't do any simplifications of the operands, because DemandedMask
835 // only reflects the bits demanded by *one* of the users.
836 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000837 // Despite the fact that we can't simplify this instruction in all User's
838 // context, we can at least compute the knownzero/knownone bits, and we can
839 // do simplifications that apply to *just* the one user if we know that
840 // this instruction has a simpler value in that context.
841 if (I->getOpcode() == Instruction::And) {
842 // If either the LHS or the RHS are Zero, the result is zero.
843 ComputeMaskedBits(I->getOperand(1), DemandedMask,
844 RHSKnownZero, RHSKnownOne, Depth+1);
845 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
846 LHSKnownZero, LHSKnownOne, Depth+1);
847
848 // If all of the demanded bits are known 1 on one side, return the other.
849 // These bits cannot contribute to the result of the 'and' in this
850 // context.
851 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
852 (DemandedMask & ~LHSKnownZero))
853 return I->getOperand(0);
854 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
855 (DemandedMask & ~RHSKnownZero))
856 return I->getOperand(1);
857
858 // If all of the demanded bits in the inputs are known zeros, return zero.
859 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000860 return Constant::getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000861
862 } else if (I->getOpcode() == Instruction::Or) {
863 // We can simplify (X|Y) -> X or Y in the user's context if we know that
864 // only bits from X or Y are demanded.
865
866 // If either the LHS or the RHS are One, the result is One.
867 ComputeMaskedBits(I->getOperand(1), DemandedMask,
868 RHSKnownZero, RHSKnownOne, Depth+1);
869 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
870 LHSKnownZero, LHSKnownOne, Depth+1);
871
872 // If all of the demanded bits are known zero on one side, return the
873 // other. These bits cannot contribute to the result of the 'or' in this
874 // context.
875 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
876 (DemandedMask & ~LHSKnownOne))
877 return I->getOperand(0);
878 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
879 (DemandedMask & ~RHSKnownOne))
880 return I->getOperand(1);
881
882 // If all of the potentially set bits on one side are known to be set on
883 // the other side, just use the 'other' side.
884 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
885 (DemandedMask & (~RHSKnownZero)))
886 return I->getOperand(0);
887 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
888 (DemandedMask & (~LHSKnownZero)))
889 return I->getOperand(1);
890 }
891
Chris Lattner08817332009-01-31 08:24:16 +0000892 // Compute the KnownZero/KnownOne bits to simplify things downstream.
893 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
894 return 0;
895 }
896
897 // If this is the root being simplified, allow it to have multiple uses,
898 // just set the DemandedMask to all bits so that we can try to simplify the
899 // operands. This allows visitTruncInst (for example) to simplify the
900 // operand of a trunc without duplicating all the logic below.
901 if (Depth == 0 && !V->hasOneUse())
902 DemandedMask = APInt::getAllOnesValue(BitWidth);
903
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000905 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000906 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000907 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 case Instruction::And:
909 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000910 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
911 RHSKnownZero, RHSKnownOne, Depth+1) ||
912 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000914 return I;
915 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
916 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917
918 // If all of the demanded bits are known 1 on one side, return the other.
919 // These bits cannot contribute to the result of the 'and'.
920 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
921 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000922 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
924 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000925 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926
927 // If all of the demanded bits in the inputs are known zeros, return zero.
928 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersonaac28372009-07-31 20:28:14 +0000929 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930
931 // If the RHS is a constant, see if we can simplify it.
Owen Anderson24be4c12009-07-03 00:17:18 +0000932 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +0000933 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 // Output known-1 bits are only known if set in both the LHS & RHS.
936 RHSKnownOne &= LHSKnownOne;
937 // Output known-0 are known to be clear if zero in either the LHS | RHS.
938 RHSKnownZero |= LHSKnownZero;
939 break;
940 case Instruction::Or:
941 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000942 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
943 RHSKnownZero, RHSKnownOne, Depth+1) ||
944 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000946 return I;
947 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
948 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949
950 // If all of the demanded bits are known zero on one side, return the other.
951 // These bits cannot contribute to the result of the 'or'.
952 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
953 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000954 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
956 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000957 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958
959 // If all of the potentially set bits on one side are known to be set on
960 // the other side, just use the 'other' side.
961 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
962 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000963 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
965 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000966 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967
968 // If the RHS is a constant, see if we can simplify it.
Owen Anderson24be4c12009-07-03 00:17:18 +0000969 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +0000970 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971
972 // Output known-0 bits are only known if clear in both the LHS & RHS.
973 RHSKnownZero &= LHSKnownZero;
974 // Output known-1 are known to be set if set in either the LHS | RHS.
975 RHSKnownOne |= LHSKnownOne;
976 break;
977 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000978 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
979 RHSKnownZero, RHSKnownOne, Depth+1) ||
980 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000982 return I;
983 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
984 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985
986 // If all of the demanded bits are known zero on one side, return the other.
987 // These bits cannot contribute to the result of the 'xor'.
988 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000989 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000991 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992
993 // Output known-0 bits are known if clear or set in both the LHS & RHS.
994 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
995 (RHSKnownOne & LHSKnownOne);
996 // Output known-1 are known to be set if set in only one of the LHS, RHS.
997 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
998 (RHSKnownOne & LHSKnownZero);
999
1000 // If all of the demanded bits are known to be zero on one side or the
1001 // other, turn this into an *inclusive* or.
1002 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1003 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1004 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001005 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001007 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008 }
1009
1010 // If all of the demanded bits on one side are known, and all of the set
1011 // bits on that side are also known to be set on the other side, turn this
1012 // into an AND, as we know the bits will be cleared.
1013 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1014 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1015 // all known
1016 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohmancf2c9982009-08-03 22:07:33 +00001017 Constant *AndC = Constant::getIntegerValue(VTy,
1018 ~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001020 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001021 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022 }
1023 }
1024
1025 // If the RHS is a constant, see if we can simplify it.
1026 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Anderson24be4c12009-07-03 00:17:18 +00001027 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001028 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029
1030 RHSKnownZero = KnownZeroOut;
1031 RHSKnownOne = KnownOneOut;
1032 break;
1033 }
1034 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001035 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1036 RHSKnownZero, RHSKnownOne, Depth+1) ||
1037 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001039 return I;
1040 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1041 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042
1043 // If the operands are constants, see if we can simplify them.
Owen Anderson24be4c12009-07-03 00:17:18 +00001044 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1045 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001046 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047
1048 // Only known if known in both the LHS and RHS.
1049 RHSKnownOne &= LHSKnownOne;
1050 RHSKnownZero &= LHSKnownZero;
1051 break;
1052 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001053 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 DemandedMask.zext(truncBf);
1055 RHSKnownZero.zext(truncBf);
1056 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001057 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001059 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060 DemandedMask.trunc(BitWidth);
1061 RHSKnownZero.trunc(BitWidth);
1062 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001063 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 break;
1065 }
1066 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001067 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001068 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001069
1070 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1071 if (const VectorType *SrcVTy =
1072 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1073 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1074 // Don't touch a bitcast between vectors of different element counts.
1075 return false;
1076 } else
1077 // Don't touch a scalar-to-vector bitcast.
1078 return false;
1079 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1080 // Don't touch a vector-to-scalar bitcast.
1081 return false;
1082
Chris Lattner676c78e2009-01-31 08:15:18 +00001083 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001085 return I;
1086 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 break;
1088 case Instruction::ZExt: {
1089 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001090 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091
1092 DemandedMask.trunc(SrcBitWidth);
1093 RHSKnownZero.trunc(SrcBitWidth);
1094 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001095 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001097 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 DemandedMask.zext(BitWidth);
1099 RHSKnownZero.zext(BitWidth);
1100 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001101 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 // The top bits are known to be zero.
1103 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1104 break;
1105 }
1106 case Instruction::SExt: {
1107 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001108 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109
1110 APInt InputDemandedBits = DemandedMask &
1111 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1112
1113 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1114 // If any of the sign extended bits are demanded, we know that the sign
1115 // bit is demanded.
1116 if ((NewBits & DemandedMask) != 0)
1117 InputDemandedBits.set(SrcBitWidth-1);
1118
1119 InputDemandedBits.trunc(SrcBitWidth);
1120 RHSKnownZero.trunc(SrcBitWidth);
1121 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001122 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001124 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 InputDemandedBits.zext(BitWidth);
1126 RHSKnownZero.zext(BitWidth);
1127 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129
1130 // If the sign bit of the input is known set or clear, then we know the
1131 // top bits of the result.
1132
1133 // If the input sign bit is known zero, or if the NewBits are not demanded
1134 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001135 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001137 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1138 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1140 RHSKnownOne |= NewBits;
1141 }
1142 break;
1143 }
1144 case Instruction::Add: {
1145 // Figure out what the input bits are. If the top bits of the and result
1146 // are not demanded, then the add doesn't demand them from its input
1147 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001148 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149
1150 // If there is a constant on the RHS, there are a variety of xformations
1151 // we can do.
1152 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1153 // If null, this should be simplified elsewhere. Some of the xforms here
1154 // won't work if the RHS is zero.
1155 if (RHS->isZero())
1156 break;
1157
1158 // If the top bit of the output is demanded, demand everything from the
1159 // input. Otherwise, we demand all the input bits except NLZ top bits.
1160 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1161
1162 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001163 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001165 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166
1167 // If the RHS of the add has bits set that can't affect the input, reduce
1168 // the constant.
Owen Anderson24be4c12009-07-03 00:17:18 +00001169 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001170 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171
1172 // Avoid excess work.
1173 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1174 break;
1175
1176 // Turn it into OR if input bits are zero.
1177 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1178 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001179 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001181 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 }
1183
1184 // We can say something about the output known-zero and known-one bits,
1185 // depending on potential carries from the input constant and the
1186 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1187 // bits set and the RHS constant is 0x01001, then we know we have a known
1188 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1189
1190 // To compute this, we first compute the potential carry bits. These are
1191 // the bits which may be modified. I'm not aware of a better way to do
1192 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001193 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1195
1196 // Now that we know which bits have carries, compute the known-1/0 sets.
1197
1198 // Bits are known one if they are known zero in one operand and one in the
1199 // other, and there is no input carry.
1200 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1201 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1202
1203 // Bits are known zero if they are known zero in both operands and there
1204 // is no input carry.
1205 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1206 } else {
1207 // If the high-bits of this ADD are not demanded, then it does not demand
1208 // the high bits of its LHS or RHS.
1209 if (DemandedMask[BitWidth-1] == 0) {
1210 // Right fill the mask of bits for this ADD to demand the most
1211 // significant bit and all those below it.
1212 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001213 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214 LHSKnownZero, LHSKnownOne, Depth+1) ||
1215 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001216 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001217 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218 }
1219 }
1220 break;
1221 }
1222 case Instruction::Sub:
1223 // If the high-bits of this SUB are not demanded, then it does not demand
1224 // the high bits of its LHS or RHS.
1225 if (DemandedMask[BitWidth-1] == 0) {
1226 // Right fill the mask of bits for this SUB to demand the most
1227 // significant bit and all those below it.
1228 uint32_t NLZ = DemandedMask.countLeadingZeros();
1229 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001230 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1231 LHSKnownZero, LHSKnownOne, Depth+1) ||
1232 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001234 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001236 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1237 // the known zeros and ones.
1238 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 break;
1240 case Instruction::Shl:
1241 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1242 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1243 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001244 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001246 return I;
1247 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 RHSKnownZero <<= ShiftAmt;
1249 RHSKnownOne <<= ShiftAmt;
1250 // low bits known zero.
1251 if (ShiftAmt)
1252 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1253 }
1254 break;
1255 case Instruction::LShr:
1256 // For a logical shift right
1257 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1259
1260 // Unsigned shift right.
1261 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001262 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001263 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001264 return I;
1265 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1267 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1268 if (ShiftAmt) {
1269 // Compute the new bits that are at the top now.
1270 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1271 RHSKnownZero |= HighBits; // high bits known zero.
1272 }
1273 }
1274 break;
1275 case Instruction::AShr:
1276 // If this is an arithmetic shift right and only the low-bit is set, we can
1277 // always convert this into a logical shr, even if the shift amount is
1278 // variable. The low bit of the shift cannot be an input sign bit unless
1279 // the shift amount is >= the size of the datatype, which is undefined.
1280 if (DemandedMask == 1) {
1281 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001282 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001284 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 }
1286
1287 // If the sign bit is the only bit demanded by this ashr, then there is no
1288 // need to do it, the shift doesn't change the high bit.
1289 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001290 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001291
1292 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1293 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1294
1295 // Signed shift right.
1296 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1297 // If any of the "high bits" are demanded, we should set the sign bit as
1298 // demanded.
1299 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1300 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001301 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001302 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001303 return I;
1304 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 // Compute the new bits that are at the top now.
1306 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1307 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1308 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1309
1310 // Handle the sign bits.
1311 APInt SignBit(APInt::getSignBit(BitWidth));
1312 // Adjust to where it is now in the mask.
1313 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1314
1315 // If the input sign bit is known to be zero, or if none of the top bits
1316 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001317 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 (HighBits & ~DemandedMask) == HighBits) {
1319 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001320 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001322 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1324 RHSKnownOne |= HighBits;
1325 }
1326 }
1327 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001328 case Instruction::SRem:
1329 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001330 APInt RA = Rem->getValue().abs();
1331 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001332 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001333 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001334
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001335 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001336 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001337 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001338 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001339 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001340
1341 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1342 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001343
1344 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001345
Chris Lattner676c78e2009-01-31 08:15:18 +00001346 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001347 }
1348 }
1349 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001350 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001351 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1352 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001353 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1354 KnownZero2, KnownOne2, Depth+1) ||
1355 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001356 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001357 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001358
Chris Lattneree5417c2009-01-21 18:09:24 +00001359 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001360 Leaders = std::max(Leaders,
1361 KnownZero2.countLeadingOnes());
1362 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001363 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364 }
Chris Lattner989ba312008-06-18 04:33:20 +00001365 case Instruction::Call:
1366 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1367 switch (II->getIntrinsicID()) {
1368 default: break;
1369 case Intrinsic::bswap: {
1370 // If the only bits demanded come from one byte of the bswap result,
1371 // just shift the input byte into position to eliminate the bswap.
1372 unsigned NLZ = DemandedMask.countLeadingZeros();
1373 unsigned NTZ = DemandedMask.countTrailingZeros();
1374
1375 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1376 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1377 // have 14 leading zeros, round to 8.
1378 NLZ &= ~7;
1379 NTZ &= ~7;
1380 // If we need exactly one byte, we can do this transformation.
1381 if (BitWidth-NLZ-NTZ == 8) {
1382 unsigned ResultBit = NTZ;
1383 unsigned InputBit = BitWidth-NTZ-8;
1384
1385 // Replace this with either a left or right shift to get the byte into
1386 // the right place.
1387 Instruction *NewVal;
1388 if (InputBit > ResultBit)
1389 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001390 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001391 else
1392 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001393 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001394 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001395 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001396 }
1397
1398 // TODO: Could compute known zero/one bits based on the input.
1399 break;
1400 }
1401 }
1402 }
Chris Lattner4946e222008-06-18 18:11:55 +00001403 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001404 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001405 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001406
1407 // If the client is only demanding bits that we know, return the known
1408 // constant.
Dan Gohmancf2c9982009-08-03 22:07:33 +00001409 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1410 return Constant::getIntegerValue(VTy, RHSKnownOne);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 return false;
1412}
1413
1414
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001415/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001416/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417/// actually used by the caller. This method analyzes which elements of the
1418/// operand are undef and returns that information in UndefElts.
1419///
1420/// If the information about demanded elements can be used to simplify the
1421/// operation, the operation is simplified, then the resultant value is
1422/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001423Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1424 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 unsigned Depth) {
1426 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001427 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001428 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429
1430 if (isa<UndefValue>(V)) {
1431 // If the entire vector is undefined, just return this info.
1432 UndefElts = EltMask;
1433 return 0;
1434 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1435 UndefElts = EltMask;
Owen Andersonb99ecca2009-07-30 23:03:37 +00001436 return UndefValue::get(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001438
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 UndefElts = 0;
1440 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1441 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonb99ecca2009-07-30 23:03:37 +00001442 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443
1444 std::vector<Constant*> Elts;
1445 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001446 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001448 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1450 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001451 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 } else { // Otherwise, defined.
1453 Elts.push_back(CP->getOperand(i));
1454 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001455
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 // If we changed the constant, return it.
Owen Anderson2f422e02009-07-28 21:19:26 +00001457 Constant *NewCP = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 return NewCP != CP ? NewCP : 0;
1459 } else if (isa<ConstantAggregateZero>(V)) {
1460 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1461 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001462
1463 // Check if this is identity. If so, return 0 since we are not simplifying
1464 // anything.
1465 if (DemandedElts == ((1ULL << VWidth) -1))
1466 return 0;
1467
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001468 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersonaac28372009-07-31 20:28:14 +00001469 Constant *Zero = Constant::getNullValue(EltTy);
Owen Andersonb99ecca2009-07-30 23:03:37 +00001470 Constant *Undef = UndefValue::get(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001472 for (unsigned i = 0; i != VWidth; ++i) {
1473 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1474 Elts.push_back(Elt);
1475 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476 UndefElts = DemandedElts ^ EltMask;
Owen Anderson2f422e02009-07-28 21:19:26 +00001477 return ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001478 }
1479
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001480 // Limit search depth.
1481 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001482 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001483
1484 // If multiple users are using the root value, procede with
1485 // simplification conservatively assuming that all elements
1486 // are needed.
1487 if (!V->hasOneUse()) {
1488 // Quit if we find multiple users of a non-root value though.
1489 // They'll be handled when it's their turn to be visited by
1490 // the main instcombine process.
1491 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001493 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001494
1495 // Conservatively assume that all elements are needed.
1496 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001497 }
1498
1499 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001500 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501
1502 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001503 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504 Value *TmpV;
1505 switch (I->getOpcode()) {
1506 default: break;
1507
1508 case Instruction::InsertElement: {
1509 // If this is a variable index, we don't know which element it overwrites.
1510 // demand exactly the same input as we produce.
1511 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1512 if (Idx == 0) {
1513 // Note that we can't propagate undef elt info, because we don't know
1514 // which elt is getting updated.
1515 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1516 UndefElts2, Depth+1);
1517 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1518 break;
1519 }
1520
1521 // If this is inserting an element that isn't demanded, remove this
1522 // insertelement.
1523 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001524 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525 return AddSoonDeadInstToWorklist(*I, 0);
1526
1527 // Otherwise, the element inserted overwrites whatever was there, so the
1528 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001529 APInt DemandedElts2 = DemandedElts;
1530 DemandedElts2.clear(IdxNo);
1531 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 UndefElts, Depth+1);
1533 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1534
1535 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001536 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001537 break;
1538 }
1539 case Instruction::ShuffleVector: {
1540 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001541 uint64_t LHSVWidth =
1542 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001543 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001544 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001545 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001546 unsigned MaskVal = Shuffle->getMaskValue(i);
1547 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001548 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001549 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001550 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001551 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001552 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001553 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001554 }
1555 }
1556 }
1557
Nate Begemanb4d176f2009-02-11 22:36:25 +00001558 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001559 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001560 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001561 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1562
Nate Begemanb4d176f2009-02-11 22:36:25 +00001563 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001564 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1565 UndefElts3, Depth+1);
1566 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1567
1568 bool NewUndefElts = false;
1569 for (unsigned i = 0; i < VWidth; i++) {
1570 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001571 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001572 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001573 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001574 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001575 NewUndefElts = true;
1576 UndefElts.set(i);
1577 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001578 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001579 if (UndefElts3[MaskVal - LHSVWidth]) {
1580 NewUndefElts = true;
1581 UndefElts.set(i);
1582 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001583 }
1584 }
1585
1586 if (NewUndefElts) {
1587 // Add additional discovered undefs.
1588 std::vector<Constant*> Elts;
1589 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001590 if (UndefElts[i])
Owen Andersonb99ecca2009-07-30 23:03:37 +00001591 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001592 else
Owen Andersoneacb44d2009-07-24 23:12:02 +00001593 Elts.push_back(ConstantInt::get(Type::Int32Ty,
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001594 Shuffle->getMaskValue(i)));
1595 }
Owen Anderson2f422e02009-07-28 21:19:26 +00001596 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001597 MadeChange = true;
1598 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001599 break;
1600 }
1601 case Instruction::BitCast: {
1602 // Vector->vector casts only.
1603 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1604 if (!VTy) break;
1605 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001606 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 unsigned Ratio;
1608
1609 if (VWidth == InVWidth) {
1610 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1611 // elements as are demanded of us.
1612 Ratio = 1;
1613 InputDemandedElts = DemandedElts;
1614 } else if (VWidth > InVWidth) {
1615 // Untested so far.
1616 break;
1617
1618 // If there are more elements in the result than there are in the source,
1619 // then an input element is live if any of the corresponding output
1620 // elements are live.
1621 Ratio = VWidth/InVWidth;
1622 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001623 if (DemandedElts[OutIdx])
1624 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625 }
1626 } else {
1627 // Untested so far.
1628 break;
1629
1630 // If there are more elements in the source than there are in the result,
1631 // then an input element is live if the corresponding output element is
1632 // live.
1633 Ratio = InVWidth/VWidth;
1634 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001635 if (DemandedElts[InIdx/Ratio])
1636 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001637 }
1638
1639 // div/rem demand all inputs, because they don't want divide by zero.
1640 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1641 UndefElts2, Depth+1);
1642 if (TmpV) {
1643 I->setOperand(0, TmpV);
1644 MadeChange = true;
1645 }
1646
1647 UndefElts = UndefElts2;
1648 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001649 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650 // If there are more elements in the result than there are in the source,
1651 // then an output element is undef if the corresponding input element is
1652 // undef.
1653 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001654 if (UndefElts2[OutIdx/Ratio])
1655 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001656 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001657 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001658 // If there are more elements in the source than there are in the result,
1659 // then a result element is undef if all of the corresponding input
1660 // elements are undef.
1661 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1662 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001663 if (!UndefElts2[InIdx]) // Not undef?
1664 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 }
1666 break;
1667 }
1668 case Instruction::And:
1669 case Instruction::Or:
1670 case Instruction::Xor:
1671 case Instruction::Add:
1672 case Instruction::Sub:
1673 case Instruction::Mul:
1674 // div/rem demand all inputs, because they don't want divide by zero.
1675 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1676 UndefElts, Depth+1);
1677 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1678 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1679 UndefElts2, Depth+1);
1680 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1681
1682 // Output elements are undefined if both are undefined. Consider things
1683 // like undef&0. The result is known zero, not undef.
1684 UndefElts &= UndefElts2;
1685 break;
1686
1687 case Instruction::Call: {
1688 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1689 if (!II) break;
1690 switch (II->getIntrinsicID()) {
1691 default: break;
1692
1693 // Binary vector operations that work column-wise. A dest element is a
1694 // function of the corresponding input elements from the two inputs.
1695 case Intrinsic::x86_sse_sub_ss:
1696 case Intrinsic::x86_sse_mul_ss:
1697 case Intrinsic::x86_sse_min_ss:
1698 case Intrinsic::x86_sse_max_ss:
1699 case Intrinsic::x86_sse2_sub_sd:
1700 case Intrinsic::x86_sse2_mul_sd:
1701 case Intrinsic::x86_sse2_min_sd:
1702 case Intrinsic::x86_sse2_max_sd:
1703 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1704 UndefElts, Depth+1);
1705 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1706 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1707 UndefElts2, Depth+1);
1708 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1709
1710 // If only the low elt is demanded and this is a scalarizable intrinsic,
1711 // scalarize it now.
1712 if (DemandedElts == 1) {
1713 switch (II->getIntrinsicID()) {
1714 default: break;
1715 case Intrinsic::x86_sse_sub_ss:
1716 case Intrinsic::x86_sse_mul_ss:
1717 case Intrinsic::x86_sse2_sub_sd:
1718 case Intrinsic::x86_sse2_mul_sd:
1719 // TODO: Lower MIN/MAX/ABS/etc
1720 Value *LHS = II->getOperand(1);
1721 Value *RHS = II->getOperand(2);
1722 // Extract the element as scalars.
Eric Christopher1ba36872009-07-25 02:28:41 +00001723 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001724 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Eric Christopher1ba36872009-07-25 02:28:41 +00001725 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001726 ConstantInt::get(Type::Int32Ty, 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727
1728 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001729 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001730 case Intrinsic::x86_sse_sub_ss:
1731 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001732 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 II->getName()), *II);
1734 break;
1735 case Intrinsic::x86_sse_mul_ss:
1736 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001737 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738 II->getName()), *II);
1739 break;
1740 }
1741
1742 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001743 InsertElementInst::Create(
Owen Andersonb99ecca2009-07-30 23:03:37 +00001744 UndefValue::get(II->getType()), TmpV,
Owen Andersoneacb44d2009-07-24 23:12:02 +00001745 ConstantInt::get(Type::Int32Ty, 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001746 InsertNewInstBefore(New, *II);
1747 AddSoonDeadInstToWorklist(*II, 0);
1748 return New;
1749 }
1750 }
1751
1752 // Output elements are undefined if both are undefined. Consider things
1753 // like undef&0. The result is known zero, not undef.
1754 UndefElts &= UndefElts2;
1755 break;
1756 }
1757 break;
1758 }
1759 }
1760 return MadeChange ? I : 0;
1761}
1762
Dan Gohman5d56fd42008-05-19 22:14:15 +00001763
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764/// AssociativeOpt - Perform an optimization on an associative operator. This
1765/// function is designed to check a chain of associative operators for a
1766/// potential to apply a certain optimization. Since the optimization may be
1767/// applicable if the expression was reassociated, this checks the chain, then
1768/// reassociates the expression as necessary to expose the optimization
1769/// opportunity. This makes use of a special Functor, which must define
1770/// 'shouldApply' and 'apply' methods.
1771///
1772template<typename Functor>
Owen Anderson24be4c12009-07-03 00:17:18 +00001773static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson5349f052009-07-06 23:00:19 +00001774 LLVMContext *Context) {
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;
Owen Anderson5349f052009-07-06 23:00:19 +00001846 LLVMContext *Context;
1847 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1849 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001850 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00001851 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001852 }
1853};
1854
1855// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1856// iff C1&C2 == 0
1857struct AddMaskingAnd {
1858 Constant *C2;
Owen Anderson5349f052009-07-06 23:00:19 +00001859 LLVMContext *Context;
1860 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861 bool shouldApply(Value *LHS) const {
1862 ConstantInt *C1;
Owen Andersona21eb582009-07-10 17:35:01 +00001863 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Anderson02b48c32009-07-29 18:55:55 +00001864 ConstantExpr::getAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001865 }
1866 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001867 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001868 }
1869};
1870
Dan Gohman089efff2008-05-13 00:00:25 +00001871}
1872
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001873static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1874 InstCombiner *IC) {
Owen Anderson5349f052009-07-06 23:00:19 +00001875 LLVMContext *Context = IC->getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00001876
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001877 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001878 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879 }
1880
1881 // Figure out if the constant is the left or the right argument.
1882 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1883 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1884
1885 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1886 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +00001887 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1888 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001889 }
1890
1891 Value *Op0 = SO, *Op1 = ConstOperand;
1892 if (!ConstIsRHS)
1893 std::swap(Op0, Op1);
1894 Instruction *New;
1895 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001896 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001897 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001898 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1899 Op0, Op1, SO->getName()+".cmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001901 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 }
1903 return IC->InsertNewInstBefore(New, I);
1904}
1905
1906// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1907// constant as the other operand, try to fold the binary operator into the
1908// select arguments. This also works for Cast instructions, which obviously do
1909// not have a second operand.
1910static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1911 InstCombiner *IC) {
1912 // Don't modify shared select instructions
1913 if (!SI->hasOneUse()) return 0;
1914 Value *TV = SI->getOperand(1);
1915 Value *FV = SI->getOperand(2);
1916
1917 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1918 // Bool selects with constant operands can be folded to logical ops.
1919 if (SI->getType() == Type::Int1Ty) return 0;
1920
1921 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1922 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1923
Gabor Greifd6da1d02008-04-06 20:25:17 +00001924 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1925 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001926 }
1927 return 0;
1928}
1929
1930
1931/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1932/// node as operand #0, see if we can fold the instruction into the PHI (which
1933/// is only possible if all operands to the PHI are constants).
1934Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1935 PHINode *PN = cast<PHINode>(I.getOperand(0));
1936 unsigned NumPHIValues = PN->getNumIncomingValues();
1937 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1938
1939 // Check to see if all of the operands of the PHI are constants. If there is
1940 // one non-constant value, remember the BB it is. If there is more than one
1941 // or if *it* is a PHI, bail out.
1942 BasicBlock *NonConstBB = 0;
1943 for (unsigned i = 0; i != NumPHIValues; ++i)
1944 if (!isa<Constant>(PN->getIncomingValue(i))) {
1945 if (NonConstBB) return 0; // More than one non-const value.
1946 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1947 NonConstBB = PN->getIncomingBlock(i);
1948
1949 // If the incoming non-constant value is in I's block, we have an infinite
1950 // loop.
1951 if (NonConstBB == I.getParent())
1952 return 0;
1953 }
1954
1955 // If there is exactly one non-constant value, we can insert a copy of the
1956 // operation in that block. However, if this is a critical edge, we would be
1957 // inserting the computation one some other paths (e.g. inside a loop). Only
1958 // do this if the pred block is unconditionally branching into the phi block.
1959 if (NonConstBB) {
1960 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1961 if (!BI || !BI->isUnconditional()) return 0;
1962 }
1963
1964 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001965 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1967 InsertNewInstBefore(NewPN, *PN);
1968 NewPN->takeName(PN);
1969
1970 // Next, add all of the operands to the PHI.
1971 if (I.getNumOperands() == 2) {
1972 Constant *C = cast<Constant>(I.getOperand(1));
1973 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001974 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001975 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1976 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +00001977 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001978 else
Owen Anderson02b48c32009-07-29 18:55:55 +00001979 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980 } else {
1981 assert(PN->getIncomingBlock(i) == NonConstBB);
1982 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001983 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 PN->getIncomingValue(i), C, "phitmp",
1985 NonConstBB->getTerminator());
1986 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001987 InV = CmpInst::Create(*Context, CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 CI->getPredicate(),
1989 PN->getIncomingValue(i), C, "phitmp",
1990 NonConstBB->getTerminator());
1991 else
Edwin Törökbd448e32009-07-14 16:55:14 +00001992 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993
1994 AddToWorkList(cast<Instruction>(InV));
1995 }
1996 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1997 }
1998 } else {
1999 CastInst *CI = cast<CastInst>(&I);
2000 const Type *RetTy = CI->getType();
2001 for (unsigned i = 0; i != NumPHIValues; ++i) {
2002 Value *InV;
2003 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002004 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 } else {
2006 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002007 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002008 I.getType(), "phitmp",
2009 NonConstBB->getTerminator());
2010 AddToWorkList(cast<Instruction>(InV));
2011 }
2012 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2013 }
2014 }
2015 return ReplaceInstUsesWith(I, NewPN);
2016}
2017
Chris Lattner55476162008-01-29 06:52:45 +00002018
Chris Lattner3554f972008-05-20 05:46:13 +00002019/// WillNotOverflowSignedAdd - Return true if we can prove that:
2020/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2021/// This basically requires proving that the add in the original type would not
2022/// overflow to change the sign bit or have a carry out.
2023bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2024 // There are different heuristics we can use for this. Here are some simple
2025 // ones.
2026
2027 // Add has the property that adding any two 2's complement numbers can only
2028 // have one carry bit which can change a sign. As such, if LHS and RHS each
2029 // have at least two sign bits, we know that the addition of the two values will
2030 // sign extend fine.
2031 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2032 return true;
2033
2034
2035 // If one of the operands only has one non-zero bit, and if the other operand
2036 // has a known-zero bit in a more significant place than it (not including the
2037 // sign bit) the ripple may go up to and fill the zero, but won't change the
2038 // sign. For example, (X & ~4) + 1.
2039
2040 // TODO: Implement.
2041
2042 return false;
2043}
2044
Chris Lattner55476162008-01-29 06:52:45 +00002045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002046Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2047 bool Changed = SimplifyCommutative(I);
2048 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2049
2050 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2051 // X + undef -> undef
2052 if (isa<UndefValue>(RHS))
2053 return ReplaceInstUsesWith(I, RHS);
2054
2055 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002056 if (RHSC->isNullValue())
2057 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002058
2059 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2060 // X + (signbit) --> X ^ signbit
2061 const APInt& Val = CI->getValue();
2062 uint32_t BitWidth = Val.getBitWidth();
2063 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002064 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002065
2066 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2067 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002068 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002069 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002070
Eli Friedmana21526d2009-07-13 22:27:52 +00002071 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002072 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedmana21526d2009-07-13 22:27:52 +00002073 if (ZI->getSrcTy() == Type::Int1Ty)
2074 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002075 }
2076
2077 if (isa<PHINode>(LHS))
2078 if (Instruction *NV = FoldOpIntoPhi(I))
2079 return NV;
2080
2081 ConstantInt *XorRHS = 0;
2082 Value *XorLHS = 0;
2083 if (isa<ConstantInt>(RHSC) &&
Owen Andersona21eb582009-07-10 17:35:01 +00002084 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002085 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002086 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2087
2088 uint32_t Size = TySizeBits / 2;
2089 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2090 APInt CFF80Val(-C0080Val);
2091 do {
2092 if (TySizeBits > Size) {
2093 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2094 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2095 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2096 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2097 // This is a sign extend if the top bits are known zero.
2098 if (!MaskedValueIsZero(XorLHS,
2099 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2100 Size = 0; // Not a sign ext, but can't be any others either.
2101 break;
2102 }
2103 }
2104 Size >>= 1;
2105 C0080Val = APIntOps::lshr(C0080Val, Size);
2106 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2107 } while (Size >= 1);
2108
2109 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002110 // with funny bit widths then this switch statement should be removed. It
2111 // is just here to get the size of the "middle" type back up to something
2112 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002113 const Type *MiddleType = 0;
2114 switch (Size) {
2115 default: break;
2116 case 32: MiddleType = Type::Int32Ty; break;
2117 case 16: MiddleType = Type::Int16Ty; break;
2118 case 8: MiddleType = Type::Int8Ty; break;
2119 }
2120 if (MiddleType) {
2121 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2122 InsertNewInstBefore(NewTrunc, I);
2123 return new SExtInst(NewTrunc, I.getType(), I.getName());
2124 }
2125 }
2126 }
2127
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002128 if (I.getType() == Type::Int1Ty)
2129 return BinaryOperator::CreateXor(LHS, RHS);
2130
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002131 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002132 if (I.getType()->isInteger()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002133 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2134 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002135
2136 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2137 if (RHSI->getOpcode() == Instruction::Sub)
2138 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2139 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2140 }
2141 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2142 if (LHSI->getOpcode() == Instruction::Sub)
2143 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2144 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2145 }
2146 }
2147
2148 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002149 // -A + -B --> -(A + B)
Owen Anderson24be4c12009-07-03 00:17:18 +00002150 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002151 if (LHS->getType()->isIntOrIntVector()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002152 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002153 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002154 InsertNewInstBefore(NewAdd, I);
Owen Anderson15b39322009-07-13 04:09:18 +00002155 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002156 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002157 }
2158
Gabor Greifa645dd32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002160 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161
2162 // A + -B --> A - B
2163 if (!isa<Constant>(RHS))
Owen Anderson24be4c12009-07-03 00:17:18 +00002164 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166
2167
2168 ConstantInt *C2;
Owen Anderson24be4c12009-07-03 00:17:18 +00002169 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002170 if (X == RHS) // X*C + X --> X * (C+1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002171 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172
2173 // X*C1 + X*C2 --> X * (C1+C2)
2174 ConstantInt *C1;
Owen Anderson24be4c12009-07-03 00:17:18 +00002175 if (X == dyn_castFoldableMul(RHS, C1, Context))
Owen Anderson02b48c32009-07-29 18:55:55 +00002176 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 }
2178
2179 // X + X*C --> X * (C+1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002180 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2181 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002182
2183 // X + ~X --> -1 since ~X = -X-1
Owen Anderson24be4c12009-07-03 00:17:18 +00002184 if (dyn_castNotVal(LHS, Context) == RHS ||
2185 dyn_castNotVal(RHS, Context) == LHS)
Owen Andersonaac28372009-07-31 20:28:14 +00002186 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002187
2188
2189 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersona21eb582009-07-10 17:35:01 +00002190 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Anderson24be4c12009-07-03 00:17:18 +00002191 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002192 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002193
2194 // A+B --> A|B iff A and B have no bits set in common.
2195 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2196 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2197 APInt LHSKnownOne(IT->getBitWidth(), 0);
2198 APInt LHSKnownZero(IT->getBitWidth(), 0);
2199 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2200 if (LHSKnownZero != 0) {
2201 APInt RHSKnownOne(IT->getBitWidth(), 0);
2202 APInt RHSKnownZero(IT->getBitWidth(), 0);
2203 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2204
2205 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002206 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002207 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002208 }
2209 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210
Nick Lewycky83598a72008-02-03 07:42:09 +00002211 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002212 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002213 Value *W, *X, *Y, *Z;
Owen Andersona21eb582009-07-10 17:35:01 +00002214 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2215 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002216 if (W != Y) {
2217 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002218 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002219 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002220 std::swap(W, X);
2221 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002222 std::swap(Y, Z);
2223 std::swap(W, X);
2224 }
2225 }
2226
2227 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002228 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002229 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002230 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002231 }
2232 }
2233 }
2234
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2236 Value *X = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00002237 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Anderson24be4c12009-07-03 00:17:18 +00002238 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002239
2240 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002241 if (LHS->hasOneUse() &&
2242 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00002243 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244 if (Anded == CRHS) {
2245 // See if all bits from the first bit set in the Add RHS up are included
2246 // in the mask. First, get the rightmost bit.
2247 const APInt& AddRHSV = CRHS->getValue();
2248
2249 // Form a mask of all bits from the lowest bit added through the top.
2250 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2251
2252 // See if the and mask includes all of these bits.
2253 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2254
2255 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2256 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002257 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002259 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 }
2261 }
2262 }
2263
2264 // Try to fold constant add into select arguments.
2265 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2266 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2267 return R;
2268 }
2269
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002270 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002271 {
2272 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002273 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002274 if (!SI) {
2275 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002276 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002277 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002278 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002279 Value *TV = SI->getTrueValue();
2280 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002281 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002282
2283 // Can we fold the add into the argument of the select?
2284 // We check both true and false select arguments for a matching subtract.
Owen Andersona21eb582009-07-10 17:35:01 +00002285 if (match(FV, m_Zero(), *Context) &&
2286 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner641ea462008-11-16 04:46:19 +00002287 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002288 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersona21eb582009-07-10 17:35:01 +00002289 if (match(TV, m_Zero(), *Context) &&
2290 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner641ea462008-11-16 04:46:19 +00002291 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002292 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002293 }
2294 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295
Chris Lattner3554f972008-05-20 05:46:13 +00002296 // Check for (add (sext x), y), see if we can merge this into an
2297 // integer add followed by a sext.
2298 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2299 // (add (sext x), cst) --> (sext (add x, cst'))
2300 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2301 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002302 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002303 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002304 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002305 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2306 // Insert the new, smaller add.
2307 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2308 CI, "addconv");
2309 InsertNewInstBefore(NewAdd, I);
2310 return new SExtInst(NewAdd, I.getType());
2311 }
2312 }
2313
2314 // (add (sext x), (sext y)) --> (sext (add int x, y))
2315 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2316 // Only do this if x/y have the same type, if at last one of them has a
2317 // single use (so we don't increase the number of sexts), and if the
2318 // integer add will not overflow.
2319 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2320 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2321 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2322 RHSConv->getOperand(0))) {
2323 // Insert the new integer add.
2324 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2325 RHSConv->getOperand(0),
2326 "addconv");
2327 InsertNewInstBefore(NewAdd, I);
2328 return new SExtInst(NewAdd, I.getType());
2329 }
2330 }
2331 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002332
2333 return Changed ? &I : 0;
2334}
2335
2336Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2337 bool Changed = SimplifyCommutative(I);
2338 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2339
2340 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2341 // X + 0 --> X
2342 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond363a0e2009-07-27 20:59:43 +00002343 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002344 (I.getType())->getValueAPF()))
2345 return ReplaceInstUsesWith(I, LHS);
2346 }
2347
2348 if (isa<PHINode>(LHS))
2349 if (Instruction *NV = FoldOpIntoPhi(I))
2350 return NV;
2351 }
2352
2353 // -A + B --> B - A
2354 // -A + -B --> -(A + B)
Owen Anderson24be4c12009-07-03 00:17:18 +00002355 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002356 return BinaryOperator::CreateFSub(RHS, LHSV);
2357
2358 // A + -B --> A - B
2359 if (!isa<Constant>(RHS))
Owen Anderson24be4c12009-07-03 00:17:18 +00002360 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002361 return BinaryOperator::CreateFSub(LHS, V);
2362
2363 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2364 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2365 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2366 return ReplaceInstUsesWith(I, LHS);
2367
Chris Lattner3554f972008-05-20 05:46:13 +00002368 // Check for (add double (sitofp x), y), see if we can merge this into an
2369 // integer add followed by a promotion.
2370 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2371 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2372 // ... if the constant fits in the integer value. This is useful for things
2373 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2374 // requires a constant pool load, and generally allows the add to be better
2375 // instcombined.
2376 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2377 Constant *CI =
Owen Anderson02b48c32009-07-29 18:55:55 +00002378 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002379 if (LHSConv->hasOneUse() &&
Owen Anderson02b48c32009-07-29 18:55:55 +00002380 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002381 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2382 // Insert the new integer add.
2383 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2384 CI, "addconv");
2385 InsertNewInstBefore(NewAdd, I);
2386 return new SIToFPInst(NewAdd, I.getType());
2387 }
2388 }
2389
2390 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2391 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2392 // Only do this if x/y have the same type, if at last one of them has a
2393 // single use (so we don't increase the number of int->fp conversions),
2394 // and if the integer add will not overflow.
2395 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2396 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2397 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2398 RHSConv->getOperand(0))) {
2399 // Insert the new integer add.
2400 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2401 RHSConv->getOperand(0),
2402 "addconv");
2403 InsertNewInstBefore(NewAdd, I);
2404 return new SIToFPInst(NewAdd, I.getType());
2405 }
2406 }
2407 }
2408
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002409 return Changed ? &I : 0;
2410}
2411
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002412Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2414
Dan Gohman7ce405e2009-06-04 22:49:04 +00002415 if (Op0 == Op1) // sub X, X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002416 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417
2418 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Anderson24be4c12009-07-03 00:17:18 +00002419 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002420 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002421
2422 if (isa<UndefValue>(Op0))
2423 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2424 if (isa<UndefValue>(Op1))
2425 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2426
2427 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2428 // Replace (-1 - A) with (~A)...
2429 if (C->isAllOnesValue())
Owen Anderson035d41d2009-07-13 20:58:05 +00002430 return BinaryOperator::CreateNot(*Context, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002431
2432 // C - ~X == X + (1+C)
2433 Value *X = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00002434 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Anderson24be4c12009-07-03 00:17:18 +00002435 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002436
2437 // -(X >>u 31) -> (X >>s 31)
2438 // -(X >>s 31) -> (X >>u 31)
2439 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002440 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002441 if (SI->getOpcode() == Instruction::LShr) {
2442 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2443 // Check to see if we are shifting out everything but the sign bit.
2444 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2445 SI->getType()->getPrimitiveSizeInBits()-1) {
2446 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002447 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448 SI->getOperand(0), CU, SI->getName());
2449 }
2450 }
2451 }
2452 else if (SI->getOpcode() == Instruction::AShr) {
2453 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2454 // Check to see if we are shifting out everything but the sign bit.
2455 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2456 SI->getType()->getPrimitiveSizeInBits()-1) {
2457 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459 SI->getOperand(0), CU, SI->getName());
2460 }
2461 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002462 }
2463 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002464 }
2465
2466 // Try to fold constant sub into select arguments.
2467 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2468 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2469 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002470
2471 // C - zext(bool) -> bool ? C - 1 : C
2472 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2473 if (ZI->getSrcTy() == Type::Int1Ty)
2474 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002475 }
2476
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002477 if (I.getType() == Type::Int1Ty)
2478 return BinaryOperator::CreateXor(Op0, Op1);
2479
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002480 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002481 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002482 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002483 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2484 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002485 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002486 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2487 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2489 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2490 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002491 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00002492 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493 }
2494 }
2495
2496 if (Op1I->hasOneUse()) {
2497 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2498 // is not used by anyone else...
2499 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002500 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002501 // Swap the two operands of the subexpr...
2502 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2503 Op1I->setOperand(0, IIOp1);
2504 Op1I->setOperand(1, IIOp0);
2505
2506 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002507 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002508 }
2509
2510 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2511 //
2512 if (Op1I->getOpcode() == Instruction::And &&
2513 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2514 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2515
2516 Value *NewNot =
Owen Anderson035d41d2009-07-13 20:58:05 +00002517 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2518 OtherOp, "B.not"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002519 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520 }
2521
2522 // 0 - (X sdiv C) -> (X sdiv -C)
2523 if (Op1I->getOpcode() == Instruction::SDiv)
2524 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2525 if (CSI->isZero())
2526 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002527 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002528 ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529
2530 // X - X*C --> X * (1-C)
2531 ConstantInt *C2 = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +00002532 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2533 Constant *CP1 =
Owen Anderson02b48c32009-07-29 18:55:55 +00002534 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002535 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002537 }
2538 }
2539 }
2540
Dan Gohman7ce405e2009-06-04 22:49:04 +00002541 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2542 if (Op0I->getOpcode() == Instruction::Add) {
2543 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2544 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2545 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2546 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2547 } else if (Op0I->getOpcode() == Instruction::Sub) {
2548 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002549 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2550 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002551 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002552 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002553
2554 ConstantInt *C1;
Owen Anderson24be4c12009-07-03 00:17:18 +00002555 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556 if (X == Op1) // X*C - X --> X * (C-1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002557 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558
2559 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Anderson24be4c12009-07-03 00:17:18 +00002560 if (X == dyn_castFoldableMul(Op1, C2, Context))
Owen Anderson02b48c32009-07-29 18:55:55 +00002561 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 }
2563 return 0;
2564}
2565
Dan Gohman7ce405e2009-06-04 22:49:04 +00002566Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2567 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Anderson24be4c12009-07-03 00:17:18 +00002570 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002571 return BinaryOperator::CreateFAdd(Op0, V);
2572
2573 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2574 if (Op1I->getOpcode() == Instruction::FAdd) {
2575 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002576 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2577 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002578 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002579 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2580 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002581 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002582 }
2583
2584 return 0;
2585}
2586
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2588/// comparison only checks the sign bit. If it only checks the sign bit, set
2589/// TrueIfSigned if the result of the comparison is true when the input value is
2590/// signed.
2591static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2592 bool &TrueIfSigned) {
2593 switch (pred) {
2594 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2595 TrueIfSigned = true;
2596 return RHS->isZero();
2597 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2598 TrueIfSigned = true;
2599 return RHS->isAllOnesValue();
2600 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2601 TrueIfSigned = false;
2602 return RHS->isAllOnesValue();
2603 case ICmpInst::ICMP_UGT:
2604 // True if LHS u> RHS and RHS == high-bit-mask - 1
2605 TrueIfSigned = true;
2606 return RHS->getValue() ==
2607 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2608 case ICmpInst::ICMP_UGE:
2609 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2610 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002611 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002612 default:
2613 return false;
2614 }
2615}
2616
2617Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2618 bool Changed = SimplifyCommutative(I);
2619 Value *Op0 = I.getOperand(0);
2620
Eli Friedmane426ded2009-07-18 09:12:15 +00002621 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00002622 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623
2624 // Simplify mul instructions with a constant RHS...
2625 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2626 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2627
2628 // ((X << C1)*C2) == (X * (C2 << C1))
2629 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2630 if (SI->getOpcode() == Instruction::Shl)
2631 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002632 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002633 ConstantExpr::getShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002634
2635 if (CI->isZero())
2636 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2637 if (CI->equalsInt(1)) // X * 1 == X
2638 return ReplaceInstUsesWith(I, Op0);
2639 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson15b39322009-07-13 04:09:18 +00002640 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002641
2642 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2643 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002644 return BinaryOperator::CreateShl(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002645 ConstantInt::get(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002646 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002647 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002648 if (Op1->isNullValue())
2649 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002650
2651 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2652 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson15b39322009-07-13 04:09:18 +00002653 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002654
2655 // As above, vector X*splat(1.0) -> X in all defined cases.
2656 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002657 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2658 if (CI->equalsInt(1))
2659 return ReplaceInstUsesWith(I, Op0);
2660 }
2661 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002662 }
2663
2664 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2665 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002666 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002668 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669 Op1, "tmp");
2670 InsertNewInstBefore(Add, I);
Owen Anderson02b48c32009-07-29 18:55:55 +00002671 Value *C1C2 = ConstantExpr::getMul(Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002673 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674
2675 }
2676
2677 // Try to fold constant mul into select arguments.
2678 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2679 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2680 return R;
2681
2682 if (isa<PHINode>(Op0))
2683 if (Instruction *NV = FoldOpIntoPhi(I))
2684 return NV;
2685 }
2686
Owen Anderson24be4c12009-07-03 00:17:18 +00002687 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2688 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002689 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002690
Nick Lewycky1c246402008-11-21 07:33:58 +00002691 // (X / Y) * Y = X - (X % Y)
2692 // (X / Y) * -Y = (X % Y) - X
2693 {
2694 Value *Op1 = I.getOperand(1);
2695 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2696 if (!BO ||
2697 (BO->getOpcode() != Instruction::UDiv &&
2698 BO->getOpcode() != Instruction::SDiv)) {
2699 Op1 = Op0;
2700 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2701 }
Owen Anderson24be4c12009-07-03 00:17:18 +00002702 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky1c246402008-11-21 07:33:58 +00002703 if (BO && BO->hasOneUse() &&
2704 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2705 (BO->getOpcode() == Instruction::UDiv ||
2706 BO->getOpcode() == Instruction::SDiv)) {
2707 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2708
2709 Instruction *Rem;
2710 if (BO->getOpcode() == Instruction::UDiv)
2711 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2712 else
2713 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2714
2715 InsertNewInstBefore(Rem, I);
2716 Rem->takeName(BO);
2717
2718 if (Op1BO == Op1)
2719 return BinaryOperator::CreateSub(Op0BO, Rem);
2720 else
2721 return BinaryOperator::CreateSub(Rem, Op0BO);
2722 }
2723 }
2724
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002725 if (I.getType() == Type::Int1Ty)
2726 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2727
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728 // If one of the operands of the multiply is a cast from a boolean value, then
2729 // we know the bool is either zero or one, so this is a 'masking' multiply.
2730 // See if we can simplify things based on how the boolean was originally
2731 // formed.
2732 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002733 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002734 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2735 BoolCast = CI;
2736 if (!BoolCast)
2737 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2738 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2739 BoolCast = CI;
2740 if (BoolCast) {
2741 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2742 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2743 const Type *SCOpTy = SCIOp0->getType();
2744 bool TIS = false;
2745
2746 // If the icmp is true iff the sign bit of X is set, then convert this
2747 // multiply into a shift/and combination.
2748 if (isa<ConstantInt>(SCIOp1) &&
2749 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2750 TIS) {
2751 // Shift the X value right to turn it into "all signbits".
Owen Andersoneacb44d2009-07-24 23:12:02 +00002752 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 SCOpTy->getPrimitiveSizeInBits()-1);
2754 Value *V =
2755 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002756 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002757 BoolCast->getOperand(0)->getName()+
2758 ".mask"), I);
2759
2760 // If the multiply type is not the same as the source type, sign extend
2761 // or truncate to the multiply type.
2762 if (I.getType() != V->getType()) {
2763 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2764 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2765 Instruction::CastOps opcode =
2766 (SrcBits == DstBits ? Instruction::BitCast :
2767 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2768 V = InsertCastBefore(opcode, V, I.getType(), I);
2769 }
2770
2771 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002772 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 }
2774 }
2775 }
2776
2777 return Changed ? &I : 0;
2778}
2779
Dan Gohman7ce405e2009-06-04 22:49:04 +00002780Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2781 bool Changed = SimplifyCommutative(I);
2782 Value *Op0 = I.getOperand(0);
2783
2784 // Simplify mul instructions with a constant RHS...
2785 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2786 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2787 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2788 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2789 if (Op1F->isExactlyValue(1.0))
2790 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2791 } else if (isa<VectorType>(Op1->getType())) {
2792 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2793 // As above, vector X*splat(1.0) -> X in all defined cases.
2794 if (Constant *Splat = Op1V->getSplatValue()) {
2795 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2796 if (F->isExactlyValue(1.0))
2797 return ReplaceInstUsesWith(I, Op0);
2798 }
2799 }
2800 }
2801
2802 // Try to fold constant mul into select arguments.
2803 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2804 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2805 return R;
2806
2807 if (isa<PHINode>(Op0))
2808 if (Instruction *NV = FoldOpIntoPhi(I))
2809 return NV;
2810 }
2811
Owen Anderson24be4c12009-07-03 00:17:18 +00002812 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2813 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002814 return BinaryOperator::CreateFMul(Op0v, Op1v);
2815
2816 return Changed ? &I : 0;
2817}
2818
Chris Lattner76972db2008-07-14 00:15:52 +00002819/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2820/// instruction.
2821bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2822 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2823
2824 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2825 int NonNullOperand = -1;
2826 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2827 if (ST->isNullValue())
2828 NonNullOperand = 2;
2829 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2830 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2831 if (ST->isNullValue())
2832 NonNullOperand = 1;
2833
2834 if (NonNullOperand == -1)
2835 return false;
2836
2837 Value *SelectCond = SI->getOperand(0);
2838
2839 // Change the div/rem to use 'Y' instead of the select.
2840 I.setOperand(1, SI->getOperand(NonNullOperand));
2841
2842 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2843 // problem. However, the select, or the condition of the select may have
2844 // multiple uses. Based on our knowledge that the operand must be non-zero,
2845 // propagate the known value for the select into other uses of it, and
2846 // propagate a known value of the condition into its other users.
2847
2848 // If the select and condition only have a single use, don't bother with this,
2849 // early exit.
2850 if (SI->use_empty() && SelectCond->hasOneUse())
2851 return true;
2852
2853 // Scan the current block backward, looking for other uses of SI.
2854 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2855
2856 while (BBI != BBFront) {
2857 --BBI;
2858 // If we found a call to a function, we can't assume it will return, so
2859 // information from below it cannot be propagated above it.
2860 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2861 break;
2862
2863 // Replace uses of the select or its condition with the known values.
2864 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2865 I != E; ++I) {
2866 if (*I == SI) {
2867 *I = SI->getOperand(NonNullOperand);
2868 AddToWorkList(BBI);
2869 } else if (*I == SelectCond) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00002870 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2871 ConstantInt::getFalse(*Context);
Chris Lattner76972db2008-07-14 00:15:52 +00002872 AddToWorkList(BBI);
2873 }
2874 }
2875
2876 // If we past the instruction, quit looking for it.
2877 if (&*BBI == SI)
2878 SI = 0;
2879 if (&*BBI == SelectCond)
2880 SelectCond = 0;
2881
2882 // If we ran out of things to eliminate, break out of the loop.
2883 if (SelectCond == 0 && SI == 0)
2884 break;
2885
2886 }
2887 return true;
2888}
2889
2890
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891/// This function implements the transforms on div instructions that work
2892/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2893/// used by the visitors to those instructions.
2894/// @brief Transforms common to all three div instructions
2895Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2897
Chris Lattner653ef3c2008-02-19 06:12:18 +00002898 // undef / X -> 0 for integer.
2899 // undef / X -> undef for FP (the undef could be a snan).
2900 if (isa<UndefValue>(Op0)) {
2901 if (Op0->getType()->isFPOrFPVector())
2902 return ReplaceInstUsesWith(I, Op0);
Owen Andersonaac28372009-07-31 20:28:14 +00002903 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002904 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905
2906 // X / undef -> undef
2907 if (isa<UndefValue>(Op1))
2908 return ReplaceInstUsesWith(I, Op1);
2909
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 return 0;
2911}
2912
2913/// This function implements the transforms common to both integer division
2914/// instructions (udiv and sdiv). It is called by the visitors to those integer
2915/// division instructions.
2916/// @brief Common integer divide transforms
2917Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2918 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2919
Chris Lattnercefb36c2008-05-16 02:59:42 +00002920 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002921 if (Op0 == Op1) {
2922 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00002923 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002924 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson2f422e02009-07-28 21:19:26 +00002925 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002926 }
2927
Owen Andersoneacb44d2009-07-24 23:12:02 +00002928 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002929 return ReplaceInstUsesWith(I, CI);
2930 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002931
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932 if (Instruction *Common = commonDivTransforms(I))
2933 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002934
2935 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2936 // This does not apply for fdiv.
2937 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2938 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002939
2940 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2941 // div X, 1 == X
2942 if (RHS->equalsInt(1))
2943 return ReplaceInstUsesWith(I, Op0);
2944
2945 // (X / C1) / C2 -> X / (C1*C2)
2946 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2947 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2948 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002949 if (MultiplyOverflows(RHS, LHSRHS,
2950 I.getOpcode()==Instruction::SDiv, Context))
Owen Andersonaac28372009-07-31 20:28:14 +00002951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002952 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002953 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00002954 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002955 }
2956
2957 if (!RHS->isZero()) { // avoid X udiv 0
2958 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2959 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2960 return R;
2961 if (isa<PHINode>(Op0))
2962 if (Instruction *NV = FoldOpIntoPhi(I))
2963 return NV;
2964 }
2965 }
2966
2967 // 0 / X == 0, we don't need to preserve faults!
2968 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2969 if (LHS->equalsInt(0))
Owen Andersonaac28372009-07-31 20:28:14 +00002970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002972 // It can't be division by zero, hence it must be division by one.
2973 if (I.getType() == Type::Int1Ty)
2974 return ReplaceInstUsesWith(I, Op0);
2975
Nick Lewycky94418732008-11-27 20:21:08 +00002976 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2977 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2978 // div X, 1 == X
2979 if (X->isOne())
2980 return ReplaceInstUsesWith(I, Op0);
2981 }
2982
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 return 0;
2984}
2985
2986Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2987 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2988
2989 // Handle the integer div common cases
2990 if (Instruction *Common = commonIDivTransforms(I))
2991 return Common;
2992
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002993 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00002994 // X udiv C^2 -> X >> C
2995 // Check to see if this is an unsigned division with an exact power of 2,
2996 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002997 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002998 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00002999 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003000
3001 // X udiv C, where C >= signbit
3002 if (C->getValue().isNegative()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00003003 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3004 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky240182a2008-11-27 22:41:10 +00003005 I);
Owen Andersonaac28372009-07-31 20:28:14 +00003006 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneacb44d2009-07-24 23:12:02 +00003007 ConstantInt::get(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003008 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009 }
3010
3011 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3012 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3013 if (RHSI->getOpcode() == Instruction::Shl &&
3014 isa<ConstantInt>(RHSI->getOperand(0))) {
3015 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3016 if (C1.isPowerOf2()) {
3017 Value *N = RHSI->getOperand(1);
3018 const Type *NTy = N->getType();
3019 if (uint32_t C2 = C1.logBase2()) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00003020 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003021 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003023 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003024 }
3025 }
3026 }
3027
3028 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3029 // where C1&C2 are powers of two.
3030 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3031 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3032 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3033 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3034 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3035 // Compute the shift amounts
3036 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3037 // Construct the "on true" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003038 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003039 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003040 Op0, TC, SI->getName()+".t");
3041 TSI = InsertNewInstBefore(TSI, I);
3042
3043 // Construct the "on false" case of the select
Owen Andersoneacb44d2009-07-24 23:12:02 +00003044 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003045 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046 Op0, FC, SI->getName()+".f");
3047 FSI = InsertNewInstBefore(FSI, I);
3048
3049 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003050 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 }
3052 }
3053 return 0;
3054}
3055
3056Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3058
3059 // Handle the integer div common cases
3060 if (Instruction *Common = commonIDivTransforms(I))
3061 return Common;
3062
3063 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3064 // sdiv X, -1 == -X
3065 if (RHS->isAllOnesValue())
Owen Anderson15b39322009-07-13 04:09:18 +00003066 return BinaryOperator::CreateNeg(*Context, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003067 }
3068
3069 // If the sign bits of both operands are zero (i.e. we can prove they are
3070 // unsigned inputs), turn this into a udiv.
3071 if (I.getType()->isInteger()) {
3072 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003073 if (MaskedValueIsZero(Op0, Mask)) {
3074 if (MaskedValueIsZero(Op1, Mask)) {
3075 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3076 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3077 }
3078 ConstantInt *ShiftedInt;
3079 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3080 ShiftedInt->getValue().isPowerOf2()) {
3081 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3082 // Safe because the only negative value (1 << Y) can take on is
3083 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3084 // the sign bit set.
3085 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3086 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003087 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003088 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089
3090 return 0;
3091}
3092
3093Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3094 return commonDivTransforms(I);
3095}
3096
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097/// This function implements the transforms on rem instructions that work
3098/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3099/// is used by the visitors to those instructions.
3100/// @brief Transforms common to all three rem instructions
3101Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3103
Chris Lattner653ef3c2008-02-19 06:12:18 +00003104 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3105 if (I.getType()->isFPOrFPVector())
3106 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersonaac28372009-07-31 20:28:14 +00003107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003108 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109 if (isa<UndefValue>(Op1))
3110 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3111
3112 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003113 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3114 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115
3116 return 0;
3117}
3118
3119/// This function implements the transforms common to both integer remainder
3120/// instructions (urem and srem). It is called by the visitors to those integer
3121/// remainder instructions.
3122/// @brief Common integer remainder transforms
3123Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3125
3126 if (Instruction *common = commonRemTransforms(I))
3127 return common;
3128
Dale Johannesena51f7372009-01-21 00:35:19 +00003129 // 0 % X == 0 for integer, we don't need to preserve faults!
3130 if (Constant *LHS = dyn_cast<Constant>(Op0))
3131 if (LHS->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +00003132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003133
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003134 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3135 // X % 0 == undef, we don't need to preserve faults!
3136 if (RHS->equalsInt(0))
Owen Andersonb99ecca2009-07-30 23:03:37 +00003137 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138
3139 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersonaac28372009-07-31 20:28:14 +00003140 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141
3142 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3144 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3145 return R;
3146 } else if (isa<PHINode>(Op0I)) {
3147 if (Instruction *NV = FoldOpIntoPhi(I))
3148 return NV;
3149 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003150
3151 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003152 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003153 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 }
3155 }
3156
3157 return 0;
3158}
3159
3160Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3161 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3162
3163 if (Instruction *common = commonIRemTransforms(I))
3164 return common;
3165
3166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3167 // X urem C^2 -> X and C
3168 // Check to see if this is an unsigned remainder with an exact power of 2,
3169 // if so, convert to a bitwise and.
3170 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3171 if (C->getValue().isPowerOf2())
Owen Anderson24be4c12009-07-03 00:17:18 +00003172 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003173 }
3174
3175 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3176 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3177 if (RHSI->getOpcode() == Instruction::Shl &&
3178 isa<ConstantInt>(RHSI->getOperand(0))) {
3179 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersonaac28372009-07-31 20:28:14 +00003180 Constant *N1 = Constant::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003181 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003183 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 }
3185 }
3186 }
3187
3188 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189 // where C1&C2 are powers of two.
3190 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193 // STO == 0 and SFO == 0 handled above.
3194 if ((STO->getValue().isPowerOf2()) &&
3195 (SFO->getValue().isPowerOf2())) {
3196 Value *TrueAnd = InsertNewInstBefore(
Owen Anderson24be4c12009-07-03 00:17:18 +00003197 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3198 SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199 Value *FalseAnd = InsertNewInstBefore(
Owen Anderson24be4c12009-07-03 00:17:18 +00003200 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3201 SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003202 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 }
3204 }
3205 }
3206
3207 return 0;
3208}
3209
3210Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3211 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3212
Dan Gohmandb3dd962007-11-05 23:16:33 +00003213 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 if (Instruction *common = commonIRemTransforms(I))
3215 return common;
3216
Owen Anderson24be4c12009-07-03 00:17:18 +00003217 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003218 if (!isa<Constant>(RHSNeg) ||
3219 (isa<ConstantInt>(RHSNeg) &&
3220 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 // X % -Y -> X % Y
3222 AddUsesToWorkList(I);
3223 I.setOperand(1, RHSNeg);
3224 return &I;
3225 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003226
Dan Gohmandb3dd962007-11-05 23:16:33 +00003227 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003228 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003229 if (I.getType()->isInteger()) {
3230 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3231 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3232 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003233 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003234 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003235 }
3236
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003237 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003238 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3239 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003240
Nick Lewyckyfd746832008-12-20 16:48:00 +00003241 bool hasNegative = false;
3242 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3243 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3244 if (RHS->getValue().isNegative())
3245 hasNegative = true;
3246
3247 if (hasNegative) {
3248 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003249 for (unsigned i = 0; i != VWidth; ++i) {
3250 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3251 if (RHS->getValue().isNegative())
Owen Anderson02b48c32009-07-29 18:55:55 +00003252 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003253 else
3254 Elts[i] = RHS;
3255 }
3256 }
3257
Owen Anderson2f422e02009-07-28 21:19:26 +00003258 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003259 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003260 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003261 I.setOperand(1, NewRHSV);
3262 return &I;
3263 }
3264 }
3265 }
3266
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267 return 0;
3268}
3269
3270Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3271 return commonRemTransforms(I);
3272}
3273
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003274// isOneBitSet - Return true if there is exactly one bit set in the specified
3275// constant.
3276static bool isOneBitSet(const ConstantInt *CI) {
3277 return CI->getValue().isPowerOf2();
3278}
3279
3280// isHighOnes - Return true if the constant is of the form 1+0+.
3281// This is the same as lowones(~X).
3282static bool isHighOnes(const ConstantInt *CI) {
3283 return (~CI->getValue() + 1).isPowerOf2();
3284}
3285
3286/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3287/// are carefully arranged to allow folding of expressions such as:
3288///
3289/// (A < B) | (A > B) --> (A != B)
3290///
3291/// Note that this is only valid if the first and second predicates have the
3292/// same sign. Is illegal to do: (A u< B) | (A s> B)
3293///
3294/// Three bits are used to represent the condition, as follows:
3295/// 0 A > B
3296/// 1 A == B
3297/// 2 A < B
3298///
3299/// <=> Value Definition
3300/// 000 0 Always false
3301/// 001 1 A > B
3302/// 010 2 A == B
3303/// 011 3 A >= B
3304/// 100 4 A < B
3305/// 101 5 A != B
3306/// 110 6 A <= B
3307/// 111 7 Always true
3308///
3309static unsigned getICmpCode(const ICmpInst *ICI) {
3310 switch (ICI->getPredicate()) {
3311 // False -> 0
3312 case ICmpInst::ICMP_UGT: return 1; // 001
3313 case ICmpInst::ICMP_SGT: return 1; // 001
3314 case ICmpInst::ICMP_EQ: return 2; // 010
3315 case ICmpInst::ICMP_UGE: return 3; // 011
3316 case ICmpInst::ICMP_SGE: return 3; // 011
3317 case ICmpInst::ICMP_ULT: return 4; // 100
3318 case ICmpInst::ICMP_SLT: return 4; // 100
3319 case ICmpInst::ICMP_NE: return 5; // 101
3320 case ICmpInst::ICMP_ULE: return 6; // 110
3321 case ICmpInst::ICMP_SLE: return 6; // 110
3322 // True -> 7
3323 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003324 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003325 return 0;
3326 }
3327}
3328
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003329/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3330/// predicate into a three bit mask. It also returns whether it is an ordered
3331/// predicate by reference.
3332static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3333 isOrdered = false;
3334 switch (CC) {
3335 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3336 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003337 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3338 case FCmpInst::FCMP_UGT: return 1; // 001
3339 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3340 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003341 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3342 case FCmpInst::FCMP_UGE: return 3; // 011
3343 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3344 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003345 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3346 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003347 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3348 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003349 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003350 default:
3351 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003352 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003353 return 0;
3354 }
3355}
3356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357/// getICmpValue - This is the complement of getICmpCode, which turns an
3358/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003359/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003360/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003361static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003362 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003364 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson4f720fa2009-07-31 17:39:07 +00003365 case 0: return ConstantInt::getFalse(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003366 case 1:
3367 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003368 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003370 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3371 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003372 case 3:
3373 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003374 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003375 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003376 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 case 4:
3378 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003379 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003380 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003381 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3382 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003383 case 6:
3384 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003386 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003387 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003388 case 7: return ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003389 }
3390}
3391
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003392/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3393/// opcode and two operands into either a FCmp instruction. isordered is passed
3394/// in to determine which kind of predicate to use in the new fcmp instruction.
3395static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003396 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003397 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003398 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003399 case 0:
3400 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003401 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003402 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003403 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003404 case 1:
3405 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003406 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003407 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003408 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003409 case 2:
3410 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003411 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003412 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003413 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003414 case 3:
3415 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003416 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003417 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003418 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003419 case 4:
3420 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003421 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003422 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003423 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003424 case 5:
3425 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003426 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003427 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003428 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003429 case 6:
3430 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003431 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003432 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003433 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson4f720fa2009-07-31 17:39:07 +00003434 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003435 }
3436}
3437
Chris Lattner2972b822008-11-16 04:55:20 +00003438/// PredicatesFoldable - Return true if both predicates match sign or if at
3439/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003440static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3441 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003442 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3443 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444}
3445
3446namespace {
3447// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3448struct FoldICmpLogical {
3449 InstCombiner &IC;
3450 Value *LHS, *RHS;
3451 ICmpInst::Predicate pred;
3452 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3453 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3454 pred(ICI->getPredicate()) {}
3455 bool shouldApply(Value *V) const {
3456 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3457 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003458 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3459 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003460 return false;
3461 }
3462 Instruction *apply(Instruction &Log) const {
3463 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3464 if (ICI->getOperand(0) != LHS) {
3465 assert(ICI->getOperand(1) == LHS);
3466 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3467 }
3468
3469 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3470 unsigned LHSCode = getICmpCode(ICI);
3471 unsigned RHSCode = getICmpCode(RHSICI);
3472 unsigned Code;
3473 switch (Log.getOpcode()) {
3474 case Instruction::And: Code = LHSCode & RHSCode; break;
3475 case Instruction::Or: Code = LHSCode | RHSCode; break;
3476 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003477 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478 }
3479
3480 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3481 ICmpInst::isSignedPredicate(ICI->getPredicate());
3482
Owen Anderson24be4c12009-07-03 00:17:18 +00003483 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484 if (Instruction *I = dyn_cast<Instruction>(RV))
3485 return I;
3486 // Otherwise, it's a constant boolean value...
3487 return IC.ReplaceInstUsesWith(Log, RV);
3488 }
3489};
3490} // end anonymous namespace
3491
3492// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3493// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3494// guaranteed to be a binary operator.
3495Instruction *InstCombiner::OptAndOp(Instruction *Op,
3496 ConstantInt *OpRHS,
3497 ConstantInt *AndRHS,
3498 BinaryOperator &TheAnd) {
3499 Value *X = Op->getOperand(0);
3500 Constant *Together = 0;
3501 if (!Op->isShift())
Owen Anderson02b48c32009-07-29 18:55:55 +00003502 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003503
3504 switch (Op->getOpcode()) {
3505 case Instruction::Xor:
3506 if (Op->hasOneUse()) {
3507 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003508 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003509 InsertNewInstBefore(And, TheAnd);
3510 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003511 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 }
3513 break;
3514 case Instruction::Or:
3515 if (Together == AndRHS) // (X | C) & C --> C
3516 return ReplaceInstUsesWith(TheAnd, AndRHS);
3517
3518 if (Op->hasOneUse() && Together != OpRHS) {
3519 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003520 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521 InsertNewInstBefore(Or, TheAnd);
3522 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003523 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003524 }
3525 break;
3526 case Instruction::Add:
3527 if (Op->hasOneUse()) {
3528 // Adding a one to a single bit bit-field should be turned into an XOR
3529 // of the bit. First thing to check is to see if this AND is with a
3530 // single bit constant.
3531 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3532
3533 // If there is only one bit set...
3534 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3535 // Ok, at this point, we know that we are masking the result of the
3536 // ADD down to exactly one bit. If the constant we are adding has
3537 // no bits set below this bit, then we can eliminate the ADD.
3538 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3539
3540 // Check to see if any bits below the one bit set in AndRHSV are set.
3541 if ((AddRHS & (AndRHSV-1)) == 0) {
3542 // If not, the only thing that can effect the output of the AND is
3543 // the bit specified by AndRHSV. If that bit is set, the effect of
3544 // the XOR is to toggle the bit. If it is clear, then the ADD has
3545 // no effect.
3546 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3547 TheAnd.setOperand(0, X);
3548 return &TheAnd;
3549 } else {
3550 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003551 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552 InsertNewInstBefore(NewAnd, TheAnd);
3553 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003554 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555 }
3556 }
3557 }
3558 }
3559 break;
3560
3561 case Instruction::Shl: {
3562 // We know that the AND will not produce any of the bits shifted in, so if
3563 // the anded constant includes them, clear them now!
3564 //
3565 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3566 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3567 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003568 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003569
3570 if (CI->getValue() == ShlMask) {
3571 // Masking out bits that the shift already masks
3572 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3573 } else if (CI != AndRHS) { // Reducing bits set in and.
3574 TheAnd.setOperand(1, CI);
3575 return &TheAnd;
3576 }
3577 break;
3578 }
3579 case Instruction::LShr:
3580 {
3581 // We know that the AND will not produce any of the bits shifted in, so if
3582 // the anded constant includes them, clear them now! This only applies to
3583 // unsigned shifts, because a signed shr may bring in set bits!
3584 //
3585 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3586 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3587 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003588 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003589
3590 if (CI->getValue() == ShrMask) {
3591 // Masking out bits that the shift already masks.
3592 return ReplaceInstUsesWith(TheAnd, Op);
3593 } else if (CI != AndRHS) {
3594 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3595 return &TheAnd;
3596 }
3597 break;
3598 }
3599 case Instruction::AShr:
3600 // Signed shr.
3601 // See if this is shifting in some sign extension, then masking it out
3602 // with an and.
3603 if (Op->hasOneUse()) {
3604 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3605 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3606 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00003607 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003608 if (C == AndRHS) { // Masking out bits shifted in.
3609 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3610 // Make the argument unsigned.
3611 Value *ShVal = Op->getOperand(0);
3612 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003613 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003614 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003615 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003616 }
3617 }
3618 break;
3619 }
3620 return 0;
3621}
3622
3623
3624/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3625/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3626/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3627/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3628/// insert new instructions.
3629Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3630 bool isSigned, bool Inside,
3631 Instruction &IB) {
Owen Anderson02b48c32009-07-29 18:55:55 +00003632 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003633 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3634 "Lo is not <= Hi in range emission code!");
3635
3636 if (Inside) {
3637 if (Lo == Hi) // Trivially false.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003638 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003639
3640 // V >= Min && V < Hi --> V < Hi
3641 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3642 ICmpInst::Predicate pred = (isSigned ?
3643 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003644 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003645 }
3646
3647 // Emit V-Lo <u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +00003648 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003649 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003651 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003652 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003653 }
3654
3655 if (Lo == Hi) // Trivially true.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003656 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003657
3658 // V < Min || V >= Hi -> V > Hi-1
Owen Anderson24be4c12009-07-03 00:17:18 +00003659 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003660 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3661 ICmpInst::Predicate pred = (isSigned ?
3662 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003663 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003664 }
3665
3666 // Emit V-Lo >u Hi-1-Lo
3667 // Note that Hi has already had one subtracted from it, above.
Owen Anderson02b48c32009-07-29 18:55:55 +00003668 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003669 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003670 InsertNewInstBefore(Add, IB);
Owen Anderson02b48c32009-07-29 18:55:55 +00003671 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003672 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003673}
3674
3675// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3676// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3677// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3678// not, since all 1s are not contiguous.
3679static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3680 const APInt& V = Val->getValue();
3681 uint32_t BitWidth = Val->getType()->getBitWidth();
3682 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3683
3684 // look for the first zero bit after the run of ones
3685 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3686 // look for the first non-zero bit
3687 ME = V.getActiveBits();
3688 return true;
3689}
3690
3691/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3692/// where isSub determines whether the operator is a sub. If we can fold one of
3693/// the following xforms:
3694///
3695/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3696/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3697/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3698///
3699/// return (A +/- B).
3700///
3701Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3702 ConstantInt *Mask, bool isSub,
3703 Instruction &I) {
3704 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3705 if (!LHSI || LHSI->getNumOperands() != 2 ||
3706 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3707
3708 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3709
3710 switch (LHSI->getOpcode()) {
3711 default: return 0;
3712 case Instruction::And:
Owen Anderson02b48c32009-07-29 18:55:55 +00003713 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003714 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3715 if ((Mask->getValue().countLeadingZeros() +
3716 Mask->getValue().countPopulation()) ==
3717 Mask->getValue().getBitWidth())
3718 break;
3719
3720 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3721 // part, we don't need any explicit masks to take them out of A. If that
3722 // is all N is, ignore it.
3723 uint32_t MB = 0, ME = 0;
3724 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3725 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3726 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3727 if (MaskedValueIsZero(RHS, Mask))
3728 break;
3729 }
3730 }
3731 return 0;
3732 case Instruction::Or:
3733 case Instruction::Xor:
3734 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3735 if ((Mask->getValue().countLeadingZeros() +
3736 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson02b48c32009-07-29 18:55:55 +00003737 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003738 break;
3739 return 0;
3740 }
3741
3742 Instruction *New;
3743 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003744 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003745 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003746 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003747 return InsertNewInstBefore(New, I);
3748}
3749
Chris Lattner0631ea72008-11-16 05:06:21 +00003750/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3751Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3752 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003753 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003754 ConstantInt *LHSCst, *RHSCst;
3755 ICmpInst::Predicate LHSCC, RHSCC;
3756
Chris Lattnerf3803482008-11-16 05:10:52 +00003757 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003758 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3759 m_ConstantInt(LHSCst)), *Context) ||
3760 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3761 m_ConstantInt(RHSCst)), *Context))
Chris Lattner0631ea72008-11-16 05:06:21 +00003762 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003763
3764 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3765 // where C is a power of 2
3766 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3767 LHSCst->getValue().isPowerOf2()) {
3768 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3769 InsertNewInstBefore(NewOr, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003770 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003771 }
3772
3773 // From here on, we only handle:
3774 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3775 if (Val != Val2) return 0;
3776
Chris Lattner0631ea72008-11-16 05:06:21 +00003777 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3778 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3779 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3780 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3781 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3782 return 0;
3783
3784 // We can't fold (ugt x, C) & (sgt x, C2).
3785 if (!PredicatesFoldable(LHSCC, RHSCC))
3786 return 0;
3787
3788 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003789 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003790 if (ICmpInst::isSignedPredicate(LHSCC) ||
3791 (ICmpInst::isEquality(LHSCC) &&
3792 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003793 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003794 else
Chris Lattner665298f2008-11-16 05:14:43 +00003795 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3796
3797 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003798 std::swap(LHS, RHS);
3799 std::swap(LHSCst, RHSCst);
3800 std::swap(LHSCC, RHSCC);
3801 }
3802
3803 // At this point, we know we have have two icmp instructions
3804 // comparing a value against two constants and and'ing the result
3805 // together. Because of the above check, we know that we only have
3806 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3807 // (from the FoldICmpLogical check above), that the two constants
3808 // are not equal and that the larger constant is on the RHS
3809 assert(LHSCst != RHSCst && "Compares not folded above?");
3810
3811 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003812 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003813 case ICmpInst::ICMP_EQ:
3814 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003815 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003816 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3817 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3818 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003819 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003820 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3821 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3822 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3823 return ReplaceInstUsesWith(I, LHS);
3824 }
3825 case ICmpInst::ICMP_NE:
3826 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003827 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003828 case ICmpInst::ICMP_ULT:
Owen Anderson24be4c12009-07-03 00:17:18 +00003829 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003830 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003831 break; // (X != 13 & X u< 15) -> no change
3832 case ICmpInst::ICMP_SLT:
Owen Anderson24be4c12009-07-03 00:17:18 +00003833 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003834 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003835 break; // (X != 13 & X s< 15) -> no change
3836 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3837 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3838 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3839 return ReplaceInstUsesWith(I, RHS);
3840 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003841 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Anderson02b48c32009-07-29 18:55:55 +00003842 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003843 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3844 Val->getName()+".off");
3845 InsertNewInstBefore(Add, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003846 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersoneacb44d2009-07-24 23:12:02 +00003847 ConstantInt::get(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003848 }
3849 break; // (X != 13 & X != 15) -> no change
3850 }
3851 break;
3852 case ICmpInst::ICMP_ULT:
3853 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003854 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003855 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3856 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003857 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003858 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3859 break;
3860 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3861 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3862 return ReplaceInstUsesWith(I, LHS);
3863 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3864 break;
3865 }
3866 break;
3867 case ICmpInst::ICMP_SLT:
3868 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003869 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003870 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3871 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00003872 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner0631ea72008-11-16 05:06:21 +00003873 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3874 break;
3875 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3876 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3877 return ReplaceInstUsesWith(I, LHS);
3878 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3879 break;
3880 }
3881 break;
3882 case ICmpInst::ICMP_UGT:
3883 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003884 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003885 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3886 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3887 return ReplaceInstUsesWith(I, RHS);
3888 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3889 break;
3890 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003891 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003892 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003893 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003894 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Anderson24be4c12009-07-03 00:17:18 +00003895 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3896 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003897 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3898 break;
3899 }
3900 break;
3901 case ICmpInst::ICMP_SGT:
3902 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003903 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003904 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3905 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3906 return ReplaceInstUsesWith(I, RHS);
3907 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3908 break;
3909 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003910 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003911 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003912 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003913 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Anderson24be4c12009-07-03 00:17:18 +00003914 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3915 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003916 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3917 break;
3918 }
3919 break;
3920 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003921
3922 return 0;
3923}
3924
Chris Lattner93a359a2009-07-23 05:14:02 +00003925Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3926 FCmpInst *RHS) {
3927
3928 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3929 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3930 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3931 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3932 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3933 // If either of the constants are nans, then the whole thing returns
3934 // false.
3935 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00003936 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003937 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3938 LHS->getOperand(0), RHS->getOperand(0));
3939 }
Chris Lattnercf373552009-07-23 05:32:17 +00003940
3941 // Handle vector zeros. This occurs because the canonical form of
3942 // "fcmp ord x,x" is "fcmp ord x, 0".
3943 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3944 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3945 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3946 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003947 return 0;
3948 }
3949
3950 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3951 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3952 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3953
3954
3955 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3956 // Swap RHS operands to match LHS.
3957 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3958 std::swap(Op1LHS, Op1RHS);
3959 }
3960
3961 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3962 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3963 if (Op0CC == Op1CC)
3964 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3965
3966 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003967 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003968 if (Op0CC == FCmpInst::FCMP_TRUE)
3969 return ReplaceInstUsesWith(I, RHS);
3970 if (Op1CC == FCmpInst::FCMP_TRUE)
3971 return ReplaceInstUsesWith(I, LHS);
3972
3973 bool Op0Ordered;
3974 bool Op1Ordered;
3975 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3976 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3977 if (Op1Pred == 0) {
3978 std::swap(LHS, RHS);
3979 std::swap(Op0Pred, Op1Pred);
3980 std::swap(Op0Ordered, Op1Ordered);
3981 }
3982 if (Op0Pred == 0) {
3983 // uno && ueq -> uno && (uno || eq) -> ueq
3984 // ord && olt -> ord && (ord && lt) -> olt
3985 if (Op0Ordered == Op1Ordered)
3986 return ReplaceInstUsesWith(I, RHS);
3987
3988 // uno && oeq -> uno && (ord && eq) -> false
3989 // uno && ord -> false
3990 if (!Op0Ordered)
Owen Anderson4f720fa2009-07-31 17:39:07 +00003991 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner93a359a2009-07-23 05:14:02 +00003992 // ord && ueq -> ord && (uno || eq) -> oeq
3993 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3994 Op0LHS, Op0RHS, Context));
3995 }
3996 }
3997
3998 return 0;
3999}
4000
Chris Lattner0631ea72008-11-16 05:06:21 +00004001
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004002Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4003 bool Changed = SimplifyCommutative(I);
4004 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4005
4006 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00004007 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004008
4009 // and X, X = X
4010 if (Op0 == Op1)
4011 return ReplaceInstUsesWith(I, Op1);
4012
4013 // See if we can simplify any instructions used by the instruction whose sole
4014 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004015 if (SimplifyDemandedInstructionBits(I))
4016 return &I;
4017 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004018 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4019 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4020 return ReplaceInstUsesWith(I, I.getOperand(0));
4021 } else if (isa<ConstantAggregateZero>(Op1)) {
4022 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4023 }
4024 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004025
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004026 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4027 const APInt& AndRHSMask = AndRHS->getValue();
4028 APInt NotAndRHS(~AndRHSMask);
4029
4030 // Optimize a variety of ((val OP C1) & C2) combinations...
4031 if (isa<BinaryOperator>(Op0)) {
4032 Instruction *Op0I = cast<Instruction>(Op0);
4033 Value *Op0LHS = Op0I->getOperand(0);
4034 Value *Op0RHS = Op0I->getOperand(1);
4035 switch (Op0I->getOpcode()) {
4036 case Instruction::Xor:
4037 case Instruction::Or:
4038 // If the mask is only needed on one incoming arm, push it up.
4039 if (Op0I->hasOneUse()) {
4040 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4041 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004042 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004043 Op0RHS->getName()+".masked");
4044 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004045 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004046 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4047 }
4048 if (!isa<Constant>(Op0RHS) &&
4049 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4050 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004051 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004052 Op0LHS->getName()+".masked");
4053 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004054 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004055 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4056 }
4057 }
4058
4059 break;
4060 case Instruction::Add:
4061 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4062 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4063 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4064 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004065 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004066 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004067 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004068 break;
4069
4070 case Instruction::Sub:
4071 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4072 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4073 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4074 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004075 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004076
Nick Lewyckya349ba42008-07-10 05:51:40 +00004077 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4078 // has 1's for all bits that the subtraction with A might affect.
4079 if (Op0I->hasOneUse()) {
4080 uint32_t BitWidth = AndRHSMask.getBitWidth();
4081 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4082 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4083
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004084 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004085 if (!(A && A->isZero()) && // avoid infinite recursion.
4086 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson15b39322009-07-13 04:09:18 +00004087 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004088 InsertNewInstBefore(NewNeg, I);
4089 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4090 }
4091 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004092 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004093
4094 case Instruction::Shl:
4095 case Instruction::LShr:
4096 // (1 << x) & 1 --> zext(x == 0)
4097 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004098 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00004099 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00004100 Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004101 InsertNewInstBefore(NewICmp, I);
4102 return new ZExtInst(NewICmp, I.getType());
4103 }
4104 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004105 }
4106
4107 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4108 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4109 return Res;
4110 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4111 // If this is an integer truncation or change from signed-to-unsigned, and
4112 // if the source is an and/or with immediate, transform it. This
4113 // frequently occurs for bitfield accesses.
4114 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4115 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4116 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004117 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004118 if (CastOp->getOpcode() == Instruction::And) {
4119 // Change: and (cast (and X, C1) to T), C2
4120 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4121 // This will fold the two constants together, which may allow
4122 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004123 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004124 CastOp->getOperand(0), I.getType(),
4125 CastOp->getName()+".shrunk");
4126 NewCast = InsertNewInstBefore(NewCast, I);
4127 // trunc_or_bitcast(C1)&C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004128 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004129 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4130 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004131 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004132 } else if (CastOp->getOpcode() == Instruction::Or) {
4133 // Change: and (cast (or X, C1) to T), C2
4134 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004135 Constant *C3 =
Owen Anderson02b48c32009-07-29 18:55:55 +00004136 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4137 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00004138 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004139 return ReplaceInstUsesWith(I, AndRHS);
4140 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004141 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004142 }
4143 }
4144
4145 // Try to fold constant and into select arguments.
4146 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4147 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4148 return R;
4149 if (isa<PHINode>(Op0))
4150 if (Instruction *NV = FoldOpIntoPhi(I))
4151 return NV;
4152 }
4153
Owen Anderson24be4c12009-07-03 00:17:18 +00004154 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4155 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004156
4157 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersonaac28372009-07-31 20:28:14 +00004158 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004159
4160 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4161 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004162 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163 I.getName()+".demorgan");
4164 InsertNewInstBefore(Or, I);
Owen Anderson035d41d2009-07-13 20:58:05 +00004165 return BinaryOperator::CreateNot(*Context, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166 }
4167
4168 {
4169 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004170 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004171 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4172 return ReplaceInstUsesWith(I, Op1);
4173
4174 // (A|B) & ~(A&B) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004175 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004176 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004177 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004178 }
4179 }
4180
Owen Andersona21eb582009-07-10 17:35:01 +00004181 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004182 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4183 return ReplaceInstUsesWith(I, Op0);
4184
4185 // ~(A&B) & (A|B) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004186 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004187 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004188 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004189 }
4190 }
4191
4192 if (Op0->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004193 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004194 if (A == Op1) { // (A^B)&A -> A&(A^B)
4195 I.swapOperands(); // Simplify below
4196 std::swap(Op0, Op1);
4197 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4198 cast<BinaryOperator>(Op0)->swapOperands();
4199 I.swapOperands(); // Simplify below
4200 std::swap(Op0, Op1);
4201 }
4202 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004203
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004204 if (Op1->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004205 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 if (B == Op0) { // B&(A^B) -> B&(B^A)
4207 cast<BinaryOperator>(Op1)->swapOperands();
4208 std::swap(A, B);
4209 }
4210 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson035d41d2009-07-13 20:58:05 +00004211 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004212 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004213 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004214 }
4215 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004216
4217 // (A&((~A)|B)) -> A&B
Owen Andersona21eb582009-07-10 17:35:01 +00004218 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4219 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattner9db479f2008-12-01 05:16:26 +00004220 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersona21eb582009-07-10 17:35:01 +00004221 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4222 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattner9db479f2008-12-01 05:16:26 +00004223 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004224 }
4225
4226 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4227 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Anderson24be4c12009-07-03 00:17:18 +00004228 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004229 return R;
4230
Chris Lattner0631ea72008-11-16 05:06:21 +00004231 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4232 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4233 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004234 }
4235
4236 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4237 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4238 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4239 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4240 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004241 if (SrcTy == Op1C->getOperand(0)->getType() &&
4242 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004243 // Only do this if the casts both really cause code to be generated.
4244 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4245 I.getType(), TD) &&
4246 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4247 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004248 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004249 Op1C->getOperand(0),
4250 I.getName());
4251 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004252 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004253 }
4254 }
4255
4256 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4257 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4258 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4259 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4260 SI0->getOperand(1) == SI1->getOperand(1) &&
4261 (SI0->hasOneUse() || SI1->hasOneUse())) {
4262 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004263 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004264 SI1->getOperand(0),
4265 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004266 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004267 SI1->getOperand(1));
4268 }
4269 }
4270
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004271 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004272 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004273 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4274 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4275 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004276 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004277
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004278 return Changed ? &I : 0;
4279}
4280
Chris Lattner567f5112008-10-05 02:13:19 +00004281/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4282/// capable of providing pieces of a bswap. The subexpression provides pieces
4283/// of a bswap if it is proven that each of the non-zero bytes in the output of
4284/// the expression came from the corresponding "byte swapped" byte in some other
4285/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4286/// we know that the expression deposits the low byte of %X into the high byte
4287/// of the bswap result and that all other bytes are zero. This expression is
4288/// accepted, the high byte of ByteValues is set to X to indicate a correct
4289/// match.
4290///
4291/// This function returns true if the match was unsuccessful and false if so.
4292/// On entry to the function the "OverallLeftShift" is a signed integer value
4293/// indicating the number of bytes that the subexpression is later shifted. For
4294/// example, if the expression is later right shifted by 16 bits, the
4295/// OverallLeftShift value would be -2 on entry. This is used to specify which
4296/// byte of ByteValues is actually being set.
4297///
4298/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4299/// byte is masked to zero by a user. For example, in (X & 255), X will be
4300/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4301/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4302/// always in the local (OverallLeftShift) coordinate space.
4303///
4304static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4305 SmallVector<Value*, 8> &ByteValues) {
4306 if (Instruction *I = dyn_cast<Instruction>(V)) {
4307 // If this is an or instruction, it may be an inner node of the bswap.
4308 if (I->getOpcode() == Instruction::Or) {
4309 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4310 ByteValues) ||
4311 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4312 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313 }
Chris Lattner567f5112008-10-05 02:13:19 +00004314
4315 // If this is a logical shift by a constant multiple of 8, recurse with
4316 // OverallLeftShift and ByteMask adjusted.
4317 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4318 unsigned ShAmt =
4319 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4320 // Ensure the shift amount is defined and of a byte value.
4321 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4322 return true;
4323
4324 unsigned ByteShift = ShAmt >> 3;
4325 if (I->getOpcode() == Instruction::Shl) {
4326 // X << 2 -> collect(X, +2)
4327 OverallLeftShift += ByteShift;
4328 ByteMask >>= ByteShift;
4329 } else {
4330 // X >>u 2 -> collect(X, -2)
4331 OverallLeftShift -= ByteShift;
4332 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004333 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004334 }
4335
4336 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4337 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4338
4339 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4340 ByteValues);
4341 }
4342
4343 // If this is a logical 'and' with a mask that clears bytes, clear the
4344 // corresponding bytes in ByteMask.
4345 if (I->getOpcode() == Instruction::And &&
4346 isa<ConstantInt>(I->getOperand(1))) {
4347 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4348 unsigned NumBytes = ByteValues.size();
4349 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4350 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4351
4352 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4353 // If this byte is masked out by a later operation, we don't care what
4354 // the and mask is.
4355 if ((ByteMask & (1 << i)) == 0)
4356 continue;
4357
4358 // If the AndMask is all zeros for this byte, clear the bit.
4359 APInt MaskB = AndMask & Byte;
4360 if (MaskB == 0) {
4361 ByteMask &= ~(1U << i);
4362 continue;
4363 }
4364
4365 // If the AndMask is not all ones for this byte, it's not a bytezap.
4366 if (MaskB != Byte)
4367 return true;
4368
4369 // Otherwise, this byte is kept.
4370 }
4371
4372 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4373 ByteValues);
4374 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004375 }
4376
Chris Lattner567f5112008-10-05 02:13:19 +00004377 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4378 // the input value to the bswap. Some observations: 1) if more than one byte
4379 // is demanded from this input, then it could not be successfully assembled
4380 // into a byteswap. At least one of the two bytes would not be aligned with
4381 // their ultimate destination.
4382 if (!isPowerOf2_32(ByteMask)) return true;
4383 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384
Chris Lattner567f5112008-10-05 02:13:19 +00004385 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4386 // is demanded, it needs to go into byte 0 of the result. This means that the
4387 // byte needs to be shifted until it lands in the right byte bucket. The
4388 // shift amount depends on the position: if the byte is coming from the high
4389 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4390 // low part, it must be shifted left.
4391 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4392 if (InputByteNo < ByteValues.size()/2) {
4393 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4394 return true;
4395 } else {
4396 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4397 return true;
4398 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004399
4400 // If the destination byte value is already defined, the values are or'd
4401 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004402 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004403 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004404 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004405 return false;
4406}
4407
4408/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4409/// If so, insert the new bswap intrinsic and return it.
4410Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4411 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004412 if (!ITy || ITy->getBitWidth() % 16 ||
4413 // ByteMask only allows up to 32-byte values.
4414 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004415 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4416
4417 /// ByteValues - For each byte of the result, we keep track of which value
4418 /// defines each byte.
4419 SmallVector<Value*, 8> ByteValues;
4420 ByteValues.resize(ITy->getBitWidth()/8);
4421
4422 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004423 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4424 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004425 return 0;
4426
4427 // Check to see if all of the bytes come from the same value.
4428 Value *V = ByteValues[0];
4429 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4430
4431 // Check to make sure that all of the bytes come from the same value.
4432 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4433 if (ByteValues[i] != V)
4434 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004435 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004437 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004438 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004439}
4440
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004441/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4442/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4443/// we can simplify this expression to "cond ? C : D or B".
4444static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004445 Value *C, Value *D,
4446 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004447 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004448 Value *Cond = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004449 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004450 return 0;
4451
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004452 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersona21eb582009-07-10 17:35:01 +00004453 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004454 return SelectInst::Create(Cond, C, B);
Owen Andersona21eb582009-07-10 17:35:01 +00004455 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004456 return SelectInst::Create(Cond, C, B);
4457 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersona21eb582009-07-10 17:35:01 +00004458 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004459 return SelectInst::Create(Cond, C, D);
Owen Andersona21eb582009-07-10 17:35:01 +00004460 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004461 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004462 return 0;
4463}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004464
Chris Lattner0c678e52008-11-16 05:20:07 +00004465/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4466Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4467 ICmpInst *LHS, ICmpInst *RHS) {
4468 Value *Val, *Val2;
4469 ConstantInt *LHSCst, *RHSCst;
4470 ICmpInst::Predicate LHSCC, RHSCC;
4471
4472 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004473 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4474 m_ConstantInt(LHSCst)), *Context) ||
4475 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4476 m_ConstantInt(RHSCst)), *Context))
Chris Lattner0c678e52008-11-16 05:20:07 +00004477 return 0;
4478
4479 // From here on, we only handle:
4480 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4481 if (Val != Val2) return 0;
4482
4483 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4484 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4485 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4486 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4487 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4488 return 0;
4489
4490 // We can't fold (ugt x, C) | (sgt x, C2).
4491 if (!PredicatesFoldable(LHSCC, RHSCC))
4492 return 0;
4493
4494 // Ensure that the larger constant is on the RHS.
4495 bool ShouldSwap;
4496 if (ICmpInst::isSignedPredicate(LHSCC) ||
4497 (ICmpInst::isEquality(LHSCC) &&
4498 ICmpInst::isSignedPredicate(RHSCC)))
4499 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4500 else
4501 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4502
4503 if (ShouldSwap) {
4504 std::swap(LHS, RHS);
4505 std::swap(LHSCst, RHSCst);
4506 std::swap(LHSCC, RHSCC);
4507 }
4508
4509 // At this point, we know we have have two icmp instructions
4510 // comparing a value against two constants and or'ing the result
4511 // together. Because of the above check, we know that we only have
4512 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4513 // FoldICmpLogical check above), that the two constants are not
4514 // equal.
4515 assert(LHSCst != RHSCst && "Compares not folded above?");
4516
4517 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004518 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004519 case ICmpInst::ICMP_EQ:
4520 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004521 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004522 case ICmpInst::ICMP_EQ:
Owen Anderson24be4c12009-07-03 00:17:18 +00004523 if (LHSCst == SubOne(RHSCst, Context)) {
4524 // (X == 13 | X == 14) -> X-13 <u 2
Owen Anderson02b48c32009-07-29 18:55:55 +00004525 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004526 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4527 Val->getName()+".off");
4528 InsertNewInstBefore(Add, I);
Owen Anderson02b48c32009-07-29 18:55:55 +00004529 AddCST = ConstantExpr::getSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson6601fcd2009-07-09 23:48:35 +00004530 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004531 }
4532 break; // (X == 13 | X == 15) -> no change
4533 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4534 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4535 break;
4536 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4537 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4538 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4539 return ReplaceInstUsesWith(I, RHS);
4540 }
4541 break;
4542 case ICmpInst::ICMP_NE:
4543 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004544 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004545 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4546 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4547 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4548 return ReplaceInstUsesWith(I, LHS);
4549 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4550 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4551 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004552 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004553 }
4554 break;
4555 case ICmpInst::ICMP_ULT:
4556 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004557 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004558 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4559 break;
4560 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4561 // If RHSCst is [us]MAXINT, it is always false. Not handling
4562 // this can cause overflow.
4563 if (RHSCst->isMaxValue(false))
4564 return ReplaceInstUsesWith(I, LHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00004565 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4566 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004567 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4568 break;
4569 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4570 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4571 return ReplaceInstUsesWith(I, RHS);
4572 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4573 break;
4574 }
4575 break;
4576 case ICmpInst::ICMP_SLT:
4577 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004578 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004579 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4580 break;
4581 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4582 // If RHSCst is [us]MAXINT, it is always false. Not handling
4583 // this can cause overflow.
4584 if (RHSCst->isMaxValue(true))
4585 return ReplaceInstUsesWith(I, LHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00004586 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4587 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004588 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4589 break;
4590 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4591 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4592 return ReplaceInstUsesWith(I, RHS);
4593 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4594 break;
4595 }
4596 break;
4597 case ICmpInst::ICMP_UGT:
4598 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004599 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004600 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4601 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4602 return ReplaceInstUsesWith(I, LHS);
4603 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4604 break;
4605 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4606 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004607 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004608 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4609 break;
4610 }
4611 break;
4612 case ICmpInst::ICMP_SGT:
4613 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004614 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004615 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4616 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4617 return ReplaceInstUsesWith(I, LHS);
4618 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4619 break;
4620 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4621 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00004622 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner0c678e52008-11-16 05:20:07 +00004623 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4624 break;
4625 }
4626 break;
4627 }
4628 return 0;
4629}
4630
Chris Lattner57e66fa2009-07-23 05:46:22 +00004631Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4632 FCmpInst *RHS) {
4633 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4634 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4635 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4636 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4637 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4638 // If either of the constants are nans, then the whole thing returns
4639 // true.
4640 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson4f720fa2009-07-31 17:39:07 +00004641 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004642
4643 // Otherwise, no need to compare the two constants, compare the
4644 // rest.
4645 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4646 LHS->getOperand(0), RHS->getOperand(0));
4647 }
4648
4649 // Handle vector zeros. This occurs because the canonical form of
4650 // "fcmp uno x,x" is "fcmp uno x, 0".
4651 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4652 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4653 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4654 LHS->getOperand(0), RHS->getOperand(0));
4655
4656 return 0;
4657 }
4658
4659 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4660 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4661 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4662
4663 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4664 // Swap RHS operands to match LHS.
4665 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4666 std::swap(Op1LHS, Op1RHS);
4667 }
4668 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4669 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4670 if (Op0CC == Op1CC)
4671 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4672 Op0LHS, Op0RHS);
4673 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00004674 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner57e66fa2009-07-23 05:46:22 +00004675 if (Op0CC == FCmpInst::FCMP_FALSE)
4676 return ReplaceInstUsesWith(I, RHS);
4677 if (Op1CC == FCmpInst::FCMP_FALSE)
4678 return ReplaceInstUsesWith(I, LHS);
4679 bool Op0Ordered;
4680 bool Op1Ordered;
4681 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4682 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4683 if (Op0Ordered == Op1Ordered) {
4684 // If both are ordered or unordered, return a new fcmp with
4685 // or'ed predicates.
4686 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4687 Op0LHS, Op0RHS, Context);
4688 if (Instruction *I = dyn_cast<Instruction>(RV))
4689 return I;
4690 // Otherwise, it's a constant boolean value...
4691 return ReplaceInstUsesWith(I, RV);
4692 }
4693 }
4694 return 0;
4695}
4696
Bill Wendlingdae376a2008-12-01 08:23:25 +00004697/// FoldOrWithConstants - This helper function folds:
4698///
Bill Wendling236a1192008-12-02 05:09:00 +00004699/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004700///
4701/// into:
4702///
Bill Wendling236a1192008-12-02 05:09:00 +00004703/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004704///
Bill Wendling236a1192008-12-02 05:09:00 +00004705/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004706Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004707 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004708 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4709 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004710
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004711 Value *V1 = 0;
4712 ConstantInt *CI2 = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004713 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004714
Bill Wendling86ee3162008-12-02 06:18:11 +00004715 APInt Xor = CI1->getValue() ^ CI2->getValue();
4716 if (!Xor.isAllOnesValue()) return 0;
4717
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004718 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004719 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004720 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4721 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004722 }
4723
4724 return 0;
4725}
4726
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004727Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4728 bool Changed = SimplifyCommutative(I);
4729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4730
4731 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersonaac28372009-07-31 20:28:14 +00004732 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004733
4734 // or X, X = X
4735 if (Op0 == Op1)
4736 return ReplaceInstUsesWith(I, Op0);
4737
4738 // See if we can simplify any instructions used by the instruction whose sole
4739 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004740 if (SimplifyDemandedInstructionBits(I))
4741 return &I;
4742 if (isa<VectorType>(I.getType())) {
4743 if (isa<ConstantAggregateZero>(Op1)) {
4744 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4745 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4746 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4747 return ReplaceInstUsesWith(I, I.getOperand(1));
4748 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004749 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004750
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751 // or X, -1 == -1
4752 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4753 ConstantInt *C1 = 0; Value *X = 0;
4754 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersona21eb582009-07-10 17:35:01 +00004755 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4756 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004757 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004758 InsertNewInstBefore(Or, I);
4759 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004760 return BinaryOperator::CreateAnd(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004761 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004762 }
4763
4764 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersona21eb582009-07-10 17:35:01 +00004765 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4766 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004767 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004768 InsertNewInstBefore(Or, I);
4769 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004770 return BinaryOperator::CreateXor(Or,
Owen Andersoneacb44d2009-07-24 23:12:02 +00004771 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772 }
4773
4774 // Try to fold constant and into select arguments.
4775 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4776 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4777 return R;
4778 if (isa<PHINode>(Op0))
4779 if (Instruction *NV = FoldOpIntoPhi(I))
4780 return NV;
4781 }
4782
4783 Value *A = 0, *B = 0;
4784 ConstantInt *C1 = 0, *C2 = 0;
4785
Owen Andersona21eb582009-07-10 17:35:01 +00004786 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004787 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4788 return ReplaceInstUsesWith(I, Op1);
Owen Andersona21eb582009-07-10 17:35:01 +00004789 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004790 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4791 return ReplaceInstUsesWith(I, Op0);
4792
4793 // (A | B) | C and A | (B | C) -> bswap if possible.
4794 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersona21eb582009-07-10 17:35:01 +00004795 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4796 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4797 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4798 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004799 if (Instruction *BSwap = MatchBSwap(I))
4800 return BSwap;
4801 }
4802
4803 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004804 if (Op0->hasOneUse() &&
4805 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004806 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004807 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004808 InsertNewInstBefore(NOr, I);
4809 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004810 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004811 }
4812
4813 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004814 if (Op1->hasOneUse() &&
4815 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004816 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004817 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004818 InsertNewInstBefore(NOr, I);
4819 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004820 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004821 }
4822
4823 // (A & C)|(B & D)
4824 Value *C = 0, *D = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004825 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4826 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004827 Value *V1 = 0, *V2 = 0, *V3 = 0;
4828 C1 = dyn_cast<ConstantInt>(C);
4829 C2 = dyn_cast<ConstantInt>(D);
4830 if (C1 && C2) { // (A & C1)|(B & C2)
4831 // If we have: ((V + N) & C1) | (V & C2)
4832 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4833 // replace with V+N.
4834 if (C1->getValue() == ~C2->getValue()) {
4835 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersona21eb582009-07-10 17:35:01 +00004836 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004837 // Add commutes, try both ways.
4838 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4839 return ReplaceInstUsesWith(I, A);
4840 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4841 return ReplaceInstUsesWith(I, A);
4842 }
4843 // Or commutes, try both ways.
4844 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersona21eb582009-07-10 17:35:01 +00004845 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004846 // Add commutes, try both ways.
4847 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4848 return ReplaceInstUsesWith(I, B);
4849 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4850 return ReplaceInstUsesWith(I, B);
4851 }
4852 }
4853 V1 = 0; V2 = 0; V3 = 0;
4854 }
4855
4856 // Check to see if we have any common things being and'ed. If so, find the
4857 // terms for V1 & (V2|V3).
4858 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4859 if (A == B) // (A & C)|(A & D) == A & (C|D)
4860 V1 = A, V2 = C, V3 = D;
4861 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4862 V1 = A, V2 = B, V3 = C;
4863 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4864 V1 = C, V2 = A, V3 = D;
4865 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4866 V1 = C, V2 = A, V3 = B;
4867
4868 if (V1) {
4869 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004870 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4871 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004872 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004873 }
Dan Gohman279952c2008-10-28 22:38:57 +00004874
Dan Gohman35b76162008-10-30 20:40:10 +00004875 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004876 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004877 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004878 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004879 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004880 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004881 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004882 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004883 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004884
Bill Wendling22ca8352008-11-30 13:52:49 +00004885 // ((A&~B)|(~A&B)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004886 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4887 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004888 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004889 // ((~B&A)|(~A&B)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004890 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4891 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004892 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004893 // ((A&~B)|(B&~A)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004894 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4895 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004896 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004897 // ((~B&A)|(B&~A)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004898 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4899 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004900 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004901 }
4902
4903 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4904 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4905 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4906 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4907 SI0->getOperand(1) == SI1->getOperand(1) &&
4908 (SI0->hasOneUse() || SI1->hasOneUse())) {
4909 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004910 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004911 SI1->getOperand(0),
4912 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004913 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004914 SI1->getOperand(1));
4915 }
4916 }
4917
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004918 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersona21eb582009-07-10 17:35:01 +00004919 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4920 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling9912f712008-12-01 08:32:40 +00004921 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004922 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004923 }
4924 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersona21eb582009-07-10 17:35:01 +00004925 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4926 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling9912f712008-12-01 08:32:40 +00004927 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004928 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004929 }
4930
Owen Andersona21eb582009-07-10 17:35:01 +00004931 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004932 if (A == Op1) // ~A | A == -1
Owen Andersonaac28372009-07-31 20:28:14 +00004933 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004934 } else {
4935 A = 0;
4936 }
4937 // Note, A is still live here!
Owen Andersona21eb582009-07-10 17:35:01 +00004938 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004939 if (Op0 == B)
Owen Andersonaac28372009-07-31 20:28:14 +00004940 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004941
4942 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4943 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004944 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004945 I.getName()+".demorgan"), I);
Owen Anderson035d41d2009-07-13 20:58:05 +00004946 return BinaryOperator::CreateNot(*Context, And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004947 }
4948 }
4949
4950 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4951 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004952 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004953 return R;
4954
Chris Lattner0c678e52008-11-16 05:20:07 +00004955 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4956 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4957 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004958 }
4959
4960 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004961 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004962 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4963 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004964 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4965 !isa<ICmpInst>(Op1C->getOperand(0))) {
4966 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004967 if (SrcTy == Op1C->getOperand(0)->getType() &&
4968 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004969 // Only do this if the casts both really cause code to be
4970 // generated.
4971 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4972 I.getType(), TD) &&
4973 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4974 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004975 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004976 Op1C->getOperand(0),
4977 I.getName());
4978 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004979 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004980 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004981 }
4982 }
Chris Lattner91882432007-10-24 05:38:08 +00004983 }
4984
4985
4986 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4987 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner57e66fa2009-07-23 05:46:22 +00004988 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4989 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4990 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004991 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004992
4993 return Changed ? &I : 0;
4994}
4995
Dan Gohman089efff2008-05-13 00:00:25 +00004996namespace {
4997
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004998// XorSelf - Implements: X ^ X --> 0
4999struct XorSelf {
5000 Value *RHS;
5001 XorSelf(Value *rhs) : RHS(rhs) {}
5002 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5003 Instruction *apply(BinaryOperator &Xor) const {
5004 return &Xor;
5005 }
5006};
5007
Dan Gohman089efff2008-05-13 00:00:25 +00005008}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005009
5010Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5011 bool Changed = SimplifyCommutative(I);
5012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5013
Evan Chenge5cd8032008-03-25 20:07:13 +00005014 if (isa<UndefValue>(Op1)) {
5015 if (isa<UndefValue>(Op0))
5016 // Handle undef ^ undef -> 0 special case. This is a common
5017 // idiom (misuse).
Owen Andersonaac28372009-07-31 20:28:14 +00005018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005019 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005020 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005021
5022 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Anderson24be4c12009-07-03 00:17:18 +00005023 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005024 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersonaac28372009-07-31 20:28:14 +00005025 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005026 }
5027
5028 // See if we can simplify any instructions used by the instruction whose sole
5029 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005030 if (SimplifyDemandedInstructionBits(I))
5031 return &I;
5032 if (isa<VectorType>(I.getType()))
5033 if (isa<ConstantAggregateZero>(Op1))
5034 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035
5036 // Is this a ~ operation?
Owen Anderson24be4c12009-07-03 00:17:18 +00005037 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005038 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5039 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5040 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5041 if (Op0I->getOpcode() == Instruction::And ||
5042 Op0I->getOpcode() == Instruction::Or) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005043 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5044 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005045 Instruction *NotY =
Owen Anderson035d41d2009-07-13 20:58:05 +00005046 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005047 Op0I->getOperand(1)->getName()+".not");
5048 InsertNewInstBefore(NotY, I);
5049 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005050 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005051 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005052 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005053 }
5054 }
5055 }
5056 }
5057
5058
5059 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00005060 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005061 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005062 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005063 return new ICmpInst(*Context, ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005064 ICI->getOperand(0), ICI->getOperand(1));
5065
Nick Lewycky1405e922007-08-06 20:04:16 +00005066 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005067 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005068 FCI->getOperand(0), FCI->getOperand(1));
5069 }
5070
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005071 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5072 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5073 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5074 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5075 Instruction::CastOps Opcode = Op0C->getOpcode();
5076 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005077 if (RHS == ConstantExpr::getCast(Opcode,
Owen Anderson4f720fa2009-07-31 17:39:07 +00005078 ConstantInt::getTrue(*Context),
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005079 Op0C->getDestTy())) {
5080 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson6601fcd2009-07-09 23:48:35 +00005081 *Context,
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005082 CI->getOpcode(), CI->getInversePredicate(),
5083 CI->getOperand(0), CI->getOperand(1)), I);
5084 NewCI->takeName(CI);
5085 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5086 }
5087 }
5088 }
5089 }
5090 }
5091
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005092 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5093 // ~(c-X) == X-c-1 == X+(-c-1)
5094 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5095 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005096 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5097 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005098 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005099 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005100 }
5101
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005102 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005103 if (Op0I->getOpcode() == Instruction::Add) {
5104 // ~(X-c) --> (-c-1)-X
5105 if (RHS->isAllOnesValue()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005106 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005107 return BinaryOperator::CreateSub(
Owen Anderson02b48c32009-07-29 18:55:55 +00005108 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005109 ConstantInt::get(I.getType(), 1)),
Owen Anderson24be4c12009-07-03 00:17:18 +00005110 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005111 } else if (RHS->getValue().isSignBit()) {
5112 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005113 Constant *C = ConstantInt::get(*Context,
5114 RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005115 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005116
5117 }
5118 } else if (Op0I->getOpcode() == Instruction::Or) {
5119 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5120 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005121 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005122 // Anything in both C1 and C2 is known to be zero, remove it from
5123 // NewRHS.
Owen Anderson02b48c32009-07-29 18:55:55 +00005124 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5125 NewRHS = ConstantExpr::getAnd(NewRHS,
5126 ConstantExpr::getNot(CommonBits));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005127 AddToWorkList(Op0I);
5128 I.setOperand(0, Op0I->getOperand(0));
5129 I.setOperand(1, NewRHS);
5130 return &I;
5131 }
5132 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005133 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005134 }
5135
5136 // Try to fold constant and into select arguments.
5137 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5138 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5139 return R;
5140 if (isa<PHINode>(Op0))
5141 if (Instruction *NV = FoldOpIntoPhi(I))
5142 return NV;
5143 }
5144
Owen Anderson24be4c12009-07-03 00:17:18 +00005145 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005146 if (X == Op1)
Owen Andersonaac28372009-07-31 20:28:14 +00005147 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005148
Owen Anderson24be4c12009-07-03 00:17:18 +00005149 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005150 if (X == Op0)
Owen Andersonaac28372009-07-31 20:28:14 +00005151 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005152
5153
5154 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5155 if (Op1I) {
5156 Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00005157 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005158 if (A == Op0) { // B^(B|A) == (A|B)^B
5159 Op1I->swapOperands();
5160 I.swapOperands();
5161 std::swap(Op0, Op1);
5162 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5163 I.swapOperands(); // Simplified below.
5164 std::swap(Op0, Op1);
5165 }
Owen Andersona21eb582009-07-10 17:35:01 +00005166 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005167 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersona21eb582009-07-10 17:35:01 +00005168 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005169 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersona21eb582009-07-10 17:35:01 +00005170 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5171 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005172 if (A == Op0) { // A^(A&B) -> A^(B&A)
5173 Op1I->swapOperands();
5174 std::swap(A, B);
5175 }
5176 if (B == Op0) { // A^(B&A) -> (B&A)^A
5177 I.swapOperands(); // Simplified below.
5178 std::swap(Op0, Op1);
5179 }
5180 }
5181 }
5182
5183 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5184 if (Op0I) {
5185 Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00005186 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5187 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005188 if (A == Op1) // (B|A)^B == (A|B)^B
5189 std::swap(A, B);
5190 if (B == Op1) { // (A|B)^B == A & ~B
5191 Instruction *NotB =
Owen Anderson035d41d2009-07-13 20:58:05 +00005192 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5193 Op1, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005194 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005195 }
Owen Andersona21eb582009-07-10 17:35:01 +00005196 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005197 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersona21eb582009-07-10 17:35:01 +00005198 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005199 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersona21eb582009-07-10 17:35:01 +00005200 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5201 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005202 if (A == Op1) // (A&B)^A -> (B&A)^A
5203 std::swap(A, B);
5204 if (B == Op1 && // (B&A)^A == ~B & A
5205 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5206 Instruction *N =
Owen Anderson035d41d2009-07-13 20:58:05 +00005207 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005208 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209 }
5210 }
5211 }
5212
5213 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5214 if (Op0I && Op1I && Op0I->isShift() &&
5215 Op0I->getOpcode() == Op1I->getOpcode() &&
5216 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5217 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5218 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005219 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005220 Op1I->getOperand(0),
5221 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005222 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005223 Op1I->getOperand(1));
5224 }
5225
5226 if (Op0I && Op1I) {
5227 Value *A, *B, *C, *D;
5228 // (A & B)^(A | B) -> A ^ B
Owen Andersona21eb582009-07-10 17:35:01 +00005229 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5230 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005231 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005232 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005233 }
5234 // (A | B)^(A & B) -> A ^ B
Owen Andersona21eb582009-07-10 17:35:01 +00005235 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5236 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005237 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005238 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005239 }
5240
5241 // (A & B)^(C & D)
5242 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005243 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5244 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005245 // (X & Y)^(X & Y) -> (Y^Z) & X
5246 Value *X = 0, *Y = 0, *Z = 0;
5247 if (A == C)
5248 X = A, Y = B, Z = D;
5249 else if (A == D)
5250 X = A, Y = B, Z = C;
5251 else if (B == C)
5252 X = B, Y = A, Z = D;
5253 else if (B == D)
5254 X = B, Y = A, Z = C;
5255
5256 if (X) {
5257 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005258 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5259 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005260 }
5261 }
5262 }
5263
5264 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5265 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Anderson24be4c12009-07-03 00:17:18 +00005266 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005267 return R;
5268
5269 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005270 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005271 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5272 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5273 const Type *SrcTy = Op0C->getOperand(0)->getType();
5274 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5275 // Only do this if the casts both really cause code to be generated.
5276 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5277 I.getType(), TD) &&
5278 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5279 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005280 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005281 Op1C->getOperand(0),
5282 I.getName());
5283 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005284 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005285 }
5286 }
Chris Lattner91882432007-10-24 05:38:08 +00005287 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005288
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005289 return Changed ? &I : 0;
5290}
5291
Owen Anderson24be4c12009-07-03 00:17:18 +00005292static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005293 LLVMContext *Context) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005294 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005295}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005296
Dan Gohman8fd520a2009-06-15 22:12:54 +00005297static bool HasAddOverflow(ConstantInt *Result,
5298 ConstantInt *In1, ConstantInt *In2,
5299 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005300 if (IsSigned)
5301 if (In2->getValue().isNegative())
5302 return Result->getValue().sgt(In1->getValue());
5303 else
5304 return Result->getValue().slt(In1->getValue());
5305 else
5306 return Result->getValue().ult(In1->getValue());
5307}
5308
Dan Gohman8fd520a2009-06-15 22:12:54 +00005309/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005310/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005311static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005312 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005313 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005314 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005315
Dan Gohman8fd520a2009-06-15 22:12:54 +00005316 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5317 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005318 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005319 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5320 ExtractElement(In1, Idx, Context),
5321 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005322 IsSigned))
5323 return true;
5324 }
5325 return false;
5326 }
5327
5328 return HasAddOverflow(cast<ConstantInt>(Result),
5329 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5330 IsSigned);
5331}
5332
5333static bool HasSubOverflow(ConstantInt *Result,
5334 ConstantInt *In1, ConstantInt *In2,
5335 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005336 if (IsSigned)
5337 if (In2->getValue().isNegative())
5338 return Result->getValue().slt(In1->getValue());
5339 else
5340 return Result->getValue().sgt(In1->getValue());
5341 else
5342 return Result->getValue().ugt(In1->getValue());
5343}
5344
Dan Gohman8fd520a2009-06-15 22:12:54 +00005345/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5346/// overflowed for this type.
5347static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005348 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005349 bool IsSigned = false) {
Owen Anderson02b48c32009-07-29 18:55:55 +00005350 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005351
5352 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5353 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005354 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
Owen Anderson24be4c12009-07-03 00:17:18 +00005355 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5356 ExtractElement(In1, Idx, Context),
5357 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005358 IsSigned))
5359 return true;
5360 }
5361 return false;
5362 }
5363
5364 return HasSubOverflow(cast<ConstantInt>(Result),
5365 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5366 IsSigned);
5367}
5368
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005369/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5370/// code necessary to compute the offset from the base pointer (without adding
5371/// in the base pointer). Return the result as a signed integer of intptr size.
5372static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005373 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005374 gep_type_iterator GTI = gep_type_begin(GEP);
5375 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson5349f052009-07-06 23:00:19 +00005376 LLVMContext *Context = IC.getContext();
Owen Andersonaac28372009-07-31 20:28:14 +00005377 Value *Result = Constant::getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005378
5379 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005380 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005381 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5382
Gabor Greif17396002008-06-12 21:37:33 +00005383 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5384 ++i, ++GTI) {
5385 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005386 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005387 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5388 if (OpC->isZero()) continue;
5389
5390 // Handle a struct index, which adds its field offset to the pointer.
5391 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5392 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5393
5394 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005395 Result =
Owen Andersoneacb44d2009-07-24 23:12:02 +00005396 ConstantInt::get(*Context,
5397 RC->getValue() + APInt(IntPtrWidth, Size));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005398 else
5399 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005400 BinaryOperator::CreateAdd(Result,
Owen Andersoneacb44d2009-07-24 23:12:02 +00005401 ConstantInt::get(IntPtrTy, Size),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005402 GEP->getName()+".offs"), I);
5403 continue;
5404 }
5405
Owen Andersoneacb44d2009-07-24 23:12:02 +00005406 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Anderson24be4c12009-07-03 00:17:18 +00005407 Constant *OC =
Owen Anderson02b48c32009-07-29 18:55:55 +00005408 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5409 Scale = ConstantExpr::getMul(OC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005410 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00005411 Result = ConstantExpr::getAdd(RC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005412 else {
5413 // Emit an add instruction.
5414 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005415 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005416 GEP->getName()+".offs"), I);
5417 }
5418 continue;
5419 }
5420 // Convert to correct type.
5421 if (Op->getType() != IntPtrTy) {
5422 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson02b48c32009-07-29 18:55:55 +00005423 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005424 else
Chris Lattner2941a652009-04-07 05:03:34 +00005425 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5426 true,
5427 Op->getName()+".c"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005428 }
5429 if (Size != 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00005430 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson02b48c32009-07-29 18:55:55 +00005432 Op = ConstantExpr::getMul(OpC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005433 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005434 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005435 GEP->getName()+".idx"), I);
5436 }
5437
5438 // Emit an add instruction.
5439 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00005440 Result = ConstantExpr::getAdd(cast<Constant>(Op),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005441 cast<Constant>(Result));
5442 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005443 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005444 GEP->getName()+".offs"), I);
5445 }
5446 return Result;
5447}
5448
Chris Lattnereba75862008-04-22 02:53:33 +00005449
Dan Gohmanff9b4732009-07-17 22:16:21 +00005450/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5451/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5452/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5453/// be complex, and scales are involved. The above expression would also be
5454/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5455/// This later form is less amenable to optimization though, and we are allowed
5456/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005457///
5458/// If we can't emit an optimized form for this expression, this returns null.
5459///
5460static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5461 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005462 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005463 gep_type_iterator GTI = gep_type_begin(GEP);
5464
5465 // Check to see if this gep only has a single variable index. If so, and if
5466 // any constant indices are a multiple of its scale, then we can compute this
5467 // in terms of the scale of the variable index. For example, if the GEP
5468 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5469 // because the expression will cross zero at the same point.
5470 unsigned i, e = GEP->getNumOperands();
5471 int64_t Offset = 0;
5472 for (i = 1; i != e; ++i, ++GTI) {
5473 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5474 // Compute the aggregate offset of constant indices.
5475 if (CI->isZero()) continue;
5476
5477 // Handle a struct index, which adds its field offset to the pointer.
5478 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5479 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5480 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005481 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005482 Offset += Size*CI->getSExtValue();
5483 }
5484 } else {
5485 // Found our variable index.
5486 break;
5487 }
5488 }
5489
5490 // If there are no variable indices, we must have a constant offset, just
5491 // evaluate it the general way.
5492 if (i == e) return 0;
5493
5494 Value *VariableIdx = GEP->getOperand(i);
5495 // Determine the scale factor of the variable element. For example, this is
5496 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005497 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005498
5499 // Verify that there are no other variable indices. If so, emit the hard way.
5500 for (++i, ++GTI; i != e; ++i, ++GTI) {
5501 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5502 if (!CI) return 0;
5503
5504 // Compute the aggregate offset of constant indices.
5505 if (CI->isZero()) continue;
5506
5507 // Handle a struct index, which adds its field offset to the pointer.
5508 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5509 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5510 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005511 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005512 Offset += Size*CI->getSExtValue();
5513 }
5514 }
5515
5516 // Okay, we know we have a single variable index, which must be a
5517 // pointer/array/vector index. If there is no offset, life is simple, return
5518 // the index.
5519 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5520 if (Offset == 0) {
5521 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5522 // we don't need to bother extending: the extension won't affect where the
5523 // computation crosses zero.
5524 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5525 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005526 VariableIdx->getName(), &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005527 return VariableIdx;
5528 }
5529
5530 // Otherwise, there is an index. The computation we will do will be modulo
5531 // the pointer size, so get it.
5532 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5533
5534 Offset &= PtrSizeMask;
5535 VariableScale &= PtrSizeMask;
5536
5537 // To do this transformation, any constant index must be a multiple of the
5538 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5539 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5540 // multiple of the variable scale.
5541 int64_t NewOffs = Offset / (int64_t)VariableScale;
5542 if (Offset != NewOffs*(int64_t)VariableScale)
5543 return 0;
5544
5545 // Okay, we can do this evaluation. Start by converting the index to intptr.
5546 const Type *IntPtrTy = TD.getIntPtrType();
5547 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005548 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005549 true /*SExt*/,
Daniel Dunbar5d3ea962009-07-26 09:48:23 +00005550 VariableIdx->getName(), &I);
Owen Andersoneacb44d2009-07-24 23:12:02 +00005551 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005552 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005553}
5554
5555
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005556/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5557/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohman17f46f72009-07-28 01:40:03 +00005558Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005559 ICmpInst::Predicate Cond,
5560 Instruction &I) {
Chris Lattnereba75862008-04-22 02:53:33 +00005561 // Look through bitcasts.
5562 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5563 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005564
5565 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohman17f46f72009-07-28 01:40:03 +00005566 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005567 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005568 // This transformation (ignoring the base and scales) is valid because we
Dan Gohman17f46f72009-07-28 01:40:03 +00005569 // know pointers can't overflow since the gep is inbounds. See if we can
5570 // output an optimized form.
Chris Lattnereba75862008-04-22 02:53:33 +00005571 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5572
5573 // If not, synthesize the offset the hard way.
5574 if (Offset == 0)
5575 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005576 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersonaac28372009-07-31 20:28:14 +00005577 Constant::getNullValue(Offset->getType()));
Dan Gohman17f46f72009-07-28 01:40:03 +00005578 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005579 // If the base pointers are different, but the indices are the same, just
5580 // compare the base pointer.
5581 if (PtrBase != GEPRHS->getOperand(0)) {
5582 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5583 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5584 GEPRHS->getOperand(0)->getType();
5585 if (IndicesTheSame)
5586 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5587 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5588 IndicesTheSame = false;
5589 break;
5590 }
5591
5592 // If all indices are the same, just compare the base pointers.
5593 if (IndicesTheSame)
Owen Anderson6601fcd2009-07-09 23:48:35 +00005594 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005595 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5596
5597 // Otherwise, the base pointers are different and the indices are
5598 // different, bail out.
5599 return 0;
5600 }
5601
5602 // If one of the GEPs has all zero indices, recurse.
5603 bool AllZeros = true;
5604 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5605 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5606 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5607 AllZeros = false;
5608 break;
5609 }
5610 if (AllZeros)
5611 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5612 ICmpInst::getSwappedPredicate(Cond), I);
5613
5614 // If the other GEP has all zero indices, recurse.
5615 AllZeros = true;
5616 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5617 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5618 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5619 AllZeros = false;
5620 break;
5621 }
5622 if (AllZeros)
5623 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5624
5625 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5626 // If the GEPs only differ by one index, compare it.
5627 unsigned NumDifferences = 0; // Keep track of # differences.
5628 unsigned DiffOperand = 0; // The operand that differs.
5629 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5630 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5631 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5632 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5633 // Irreconcilable differences.
5634 NumDifferences = 2;
5635 break;
5636 } else {
5637 if (NumDifferences++) break;
5638 DiffOperand = i;
5639 }
5640 }
5641
5642 if (NumDifferences == 0) // SAME GEP?
5643 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersoneacb44d2009-07-24 23:12:02 +00005644 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005645 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005646
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005647 else if (NumDifferences == 1) {
5648 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5649 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5650 // Make sure we do a signed comparison here.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005651 return new ICmpInst(*Context,
5652 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005653 }
5654 }
5655
5656 // Only lower this if the icmp is the only user of the GEP or if we expect
5657 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005658 if (TD &&
5659 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005660 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5661 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5662 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5663 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005664 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005665 }
5666 }
5667 return 0;
5668}
5669
Chris Lattnere6b62d92008-05-19 20:18:56 +00005670/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5671///
5672Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5673 Instruction *LHSI,
5674 Constant *RHSC) {
5675 if (!isa<ConstantFP>(RHSC)) return 0;
5676 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5677
5678 // Get the width of the mantissa. We don't want to hack on conversions that
5679 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005680 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005681 if (MantissaWidth == -1) return 0; // Unknown.
5682
5683 // Check to see that the input is converted from an integer type that is small
5684 // enough that preserves all bits. TODO: check here for "known" sign bits.
5685 // 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 +00005686 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005687
5688 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005689 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5690 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005691 ++InputSize;
5692
5693 // If the conversion would lose info, don't hack on this.
5694 if ((int)InputSize > MantissaWidth)
5695 return 0;
5696
5697 // Otherwise, we can potentially simplify the comparison. We know that it
5698 // will always come through as an integer value and we know the constant is
5699 // not a NAN (it would have been previously simplified).
5700 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5701
5702 ICmpInst::Predicate Pred;
5703 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005704 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005705 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005706 case FCmpInst::FCMP_OEQ:
5707 Pred = ICmpInst::ICMP_EQ;
5708 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005709 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005710 case FCmpInst::FCMP_OGT:
5711 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5712 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005713 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005714 case FCmpInst::FCMP_OGE:
5715 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5716 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005717 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005718 case FCmpInst::FCMP_OLT:
5719 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5720 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005721 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005722 case FCmpInst::FCMP_OLE:
5723 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5724 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005725 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005726 case FCmpInst::FCMP_ONE:
5727 Pred = ICmpInst::ICMP_NE;
5728 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005729 case FCmpInst::FCMP_ORD:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005730 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005731 case FCmpInst::FCMP_UNO:
Owen Anderson4f720fa2009-07-31 17:39:07 +00005732 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005733 }
5734
5735 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5736
5737 // Now we know that the APFloat is a normal number, zero or inf.
5738
Chris Lattnerf13ff492008-05-20 03:50:52 +00005739 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005740 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005741 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005742
Bill Wendling20636df2008-11-09 04:26:50 +00005743 if (!LHSUnsigned) {
5744 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5745 // and large values.
5746 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5747 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5748 APFloat::rmNearestTiesToEven);
5749 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5750 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5751 Pred == ICmpInst::ICMP_SLE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005752 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5753 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005754 }
5755 } else {
5756 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5757 // +INF and large values.
5758 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5759 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5760 APFloat::rmNearestTiesToEven);
5761 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5762 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5763 Pred == ICmpInst::ICMP_ULE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005764 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5765 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005766 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005767 }
5768
Bill Wendling20636df2008-11-09 04:26:50 +00005769 if (!LHSUnsigned) {
5770 // See if the RHS value is < SignedMin.
5771 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5772 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5773 APFloat::rmNearestTiesToEven);
5774 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5775 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5776 Pred == ICmpInst::ICMP_SGE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005777 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5778 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendling20636df2008-11-09 04:26:50 +00005779 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005780 }
5781
Bill Wendling20636df2008-11-09 04:26:50 +00005782 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5783 // [0, UMAX], but it may still be fractional. See if it is fractional by
5784 // casting the FP value to the integer value and back, checking for equality.
5785 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005786 Constant *RHSInt = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005787 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5788 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005789 if (!RHS.isZero()) {
5790 bool Equal = LHSUnsigned
Owen Anderson02b48c32009-07-29 18:55:55 +00005791 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5792 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005793 if (!Equal) {
5794 // If we had a comparison against a fractional value, we have to adjust
5795 // the compare predicate and sometimes the value. RHSC is rounded towards
5796 // zero at this point.
5797 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005798 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005799 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson4f720fa2009-07-31 17:39:07 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005801 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson4f720fa2009-07-31 17:39:07 +00005802 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005803 case ICmpInst::ICMP_ULE:
5804 // (float)int <= 4.4 --> int <= 4
5805 // (float)int <= -4.4 --> false
5806 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005807 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005808 break;
5809 case ICmpInst::ICMP_SLE:
5810 // (float)int <= 4.4 --> int <= 4
5811 // (float)int <= -4.4 --> int < -4
5812 if (RHS.isNegative())
5813 Pred = ICmpInst::ICMP_SLT;
5814 break;
5815 case ICmpInst::ICMP_ULT:
5816 // (float)int < -4.4 --> false
5817 // (float)int < 4.4 --> int <= 4
5818 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005819 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005820 Pred = ICmpInst::ICMP_ULE;
5821 break;
5822 case ICmpInst::ICMP_SLT:
5823 // (float)int < -4.4 --> int < -4
5824 // (float)int < 4.4 --> int <= 4
5825 if (!RHS.isNegative())
5826 Pred = ICmpInst::ICMP_SLE;
5827 break;
5828 case ICmpInst::ICMP_UGT:
5829 // (float)int > 4.4 --> int > 4
5830 // (float)int > -4.4 --> true
5831 if (RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005832 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005833 break;
5834 case ICmpInst::ICMP_SGT:
5835 // (float)int > 4.4 --> int > 4
5836 // (float)int > -4.4 --> int >= -4
5837 if (RHS.isNegative())
5838 Pred = ICmpInst::ICMP_SGE;
5839 break;
5840 case ICmpInst::ICMP_UGE:
5841 // (float)int >= -4.4 --> true
5842 // (float)int >= 4.4 --> int > 4
5843 if (!RHS.isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00005844 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng14118132009-05-22 23:10:53 +00005845 Pred = ICmpInst::ICMP_UGT;
5846 break;
5847 case ICmpInst::ICMP_SGE:
5848 // (float)int >= -4.4 --> int >= -4
5849 // (float)int >= 4.4 --> int > 4
5850 if (!RHS.isNegative())
5851 Pred = ICmpInst::ICMP_SGT;
5852 break;
5853 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005854 }
5855 }
5856
5857 // Lower this FP comparison into an appropriate integer version of the
5858 // comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005859 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005860}
5861
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005862Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5863 bool Changed = SimplifyCompare(I);
5864 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5865
5866 // Fold trivial predicates.
5867 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005868 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005869 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005871
5872 // Simplify 'fcmp pred X, X'
5873 if (Op0 == Op1) {
5874 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005875 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005876 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5877 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5878 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson4f720fa2009-07-31 17:39:07 +00005879 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005880 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5881 case FCmpInst::FCMP_OLT: // True if ordered and less than
5882 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson4f720fa2009-07-31 17:39:07 +00005883 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005884
5885 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5886 case FCmpInst::FCMP_ULT: // True if unordered or less than
5887 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5888 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5889 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5890 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersonaac28372009-07-31 20:28:14 +00005891 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005892 return &I;
5893
5894 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5895 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5896 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5897 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5898 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5899 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersonaac28372009-07-31 20:28:14 +00005900 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005901 return &I;
5902 }
5903 }
5904
5905 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersonb99ecca2009-07-30 23:03:37 +00005906 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005907
5908 // Handle fcmp with constant RHS
5909 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005910 // If the constant is a nan, see if we can fold the comparison based on it.
5911 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5912 if (CFP->getValueAPF().isNaN()) {
5913 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson4f720fa2009-07-31 17:39:07 +00005914 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005915 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5916 "Comparison must be either ordered or unordered!");
5917 // True if unordered.
Owen Anderson4f720fa2009-07-31 17:39:07 +00005918 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005919 }
5920 }
5921
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005922 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5923 switch (LHSI->getOpcode()) {
5924 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005925 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5926 // block. If in the same block, we're encouraging jump threading. If
5927 // not, we are just pessimizing the code by making an i1 phi.
5928 if (LHSI->getParent() == I.getParent())
5929 if (Instruction *NV = FoldOpIntoPhi(I))
5930 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005931 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005932 case Instruction::SIToFP:
5933 case Instruction::UIToFP:
5934 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5935 return NV;
5936 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005937 case Instruction::Select:
5938 // If either operand of the select is a constant, we can fold the
5939 // comparison into the select arms, which will cause one to be
5940 // constant folded and the select turned into a bitwise or.
5941 Value *Op1 = 0, *Op2 = 0;
5942 if (LHSI->hasOneUse()) {
5943 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5944 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005945 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005946 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005947 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005948 LHSI->getOperand(2), RHSC,
5949 I.getName()), I);
5950 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5951 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00005952 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005953 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005954 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005955 LHSI->getOperand(1), RHSC,
5956 I.getName()), I);
5957 }
5958 }
5959
5960 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005961 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005962 break;
5963 }
5964 }
5965
5966 return Changed ? &I : 0;
5967}
5968
5969Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5970 bool Changed = SimplifyCompare(I);
5971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5972 const Type *Ty = Op0->getType();
5973
5974 // icmp X, X
5975 if (Op0 == Op1)
Owen Andersoneacb44d2009-07-24 23:12:02 +00005976 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005977 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005978
5979 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersonb99ecca2009-07-30 23:03:37 +00005980 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005981
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005982 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5983 // addresses never equal each other! We already know that Op0 != Op1.
5984 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5985 isa<ConstantPointerNull>(Op0)) &&
5986 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5987 isa<ConstantPointerNull>(Op1)))
Owen Andersoneacb44d2009-07-24 23:12:02 +00005988 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005989 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005990
5991 // icmp's with boolean values can always be turned into bitwise operations
5992 if (Ty == Type::Int1Ty) {
5993 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005994 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005995 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005996 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005997 InsertNewInstBefore(Xor, I);
Owen Anderson035d41d2009-07-13 20:58:05 +00005998 return BinaryOperator::CreateNot(*Context, Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005999 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006000 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006001 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006002
6003 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006004 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006005 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006006 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson035d41d2009-07-13 20:58:05 +00006007 Instruction *Not = BinaryOperator::CreateNot(*Context,
6008 Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006009 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006010 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006012 case ICmpInst::ICMP_SGT:
6013 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006014 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006015 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson035d41d2009-07-13 20:58:05 +00006016 Instruction *Not = BinaryOperator::CreateNot(*Context,
6017 Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006018 InsertNewInstBefore(Not, I);
6019 return BinaryOperator::CreateAnd(Not, Op0);
6020 }
6021 case ICmpInst::ICMP_UGE:
6022 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6023 // FALL THROUGH
6024 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson035d41d2009-07-13 20:58:05 +00006025 Instruction *Not = BinaryOperator::CreateNot(*Context,
6026 Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006027 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006028 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006029 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SGE:
6031 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson035d41d2009-07-13 20:58:05 +00006034 Instruction *Not = BinaryOperator::CreateNot(*Context,
6035 Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006036 InsertNewInstBefore(Not, I);
6037 return BinaryOperator::CreateOr(Not, Op0);
6038 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006039 }
6040 }
6041
Dan Gohman7934d592009-04-25 17:12:48 +00006042 unsigned BitWidth = 0;
6043 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006044 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6045 else if (Ty->isIntOrIntVector())
6046 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006047
6048 bool isSignBit = false;
6049
Dan Gohman58c09632008-09-16 18:46:06 +00006050 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006051 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006052 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006053
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006054 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6055 if (I.isEquality() && CI->isNullValue() &&
Owen Andersona21eb582009-07-10 17:35:01 +00006056 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006057 // (icmp cond A B) if cond is equality
Owen Anderson6601fcd2009-07-09 23:48:35 +00006058 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006059 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006060
Dan Gohman58c09632008-09-16 18:46:06 +00006061 // If we have an icmp le or icmp ge instruction, turn it into the
6062 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6063 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006064 switch (I.getPredicate()) {
6065 default: break;
6066 case ICmpInst::ICMP_ULE:
6067 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006068 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006069 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6070 AddOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006071 case ICmpInst::ICMP_SLE:
6072 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006073 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006074 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6075 AddOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006076 case ICmpInst::ICMP_UGE:
6077 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006078 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006079 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6080 SubOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006081 case ICmpInst::ICMP_SGE:
6082 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson4f720fa2009-07-31 17:39:07 +00006083 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006084 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6085 SubOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006086 }
6087
Chris Lattnera1308652008-07-11 05:40:05 +00006088 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006089 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006090 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006091 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6092 }
6093
6094 // See if we can fold the comparison based on range information we can get
6095 // by checking whether bits are known to be zero or one in the input.
6096 if (BitWidth != 0) {
6097 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6098 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6099
6100 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006101 isSignBit ? APInt::getSignBit(BitWidth)
6102 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006103 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006104 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006105 if (SimplifyDemandedBits(I.getOperandUse(1),
6106 APInt::getAllOnesValue(BitWidth),
6107 Op1KnownZero, Op1KnownOne, 0))
6108 return &I;
6109
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006110 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006111 // in. Compute the Min, Max and RHS values based on the known bits. For the
6112 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006113 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6114 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6115 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6116 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6117 Op0Min, Op0Max);
6118 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6119 Op1Min, Op1Max);
6120 } else {
6121 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6122 Op0Min, Op0Max);
6123 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6124 Op1Min, Op1Max);
6125 }
6126
Chris Lattnera1308652008-07-11 05:40:05 +00006127 // If Min and Max are known to be the same, then SimplifyDemandedBits
6128 // figured out that the LHS is a constant. Just constant fold this now so
6129 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006130 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006131 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006132 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006133 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006134 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006135 ConstantInt::get(*Context, Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006136
Chris Lattnera1308652008-07-11 05:40:05 +00006137 // Based on the range information we know about the LHS, see if we can
6138 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006139 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006140 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006141 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006142 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006143 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006144 break;
6145 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006146 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson4f720fa2009-07-31 17:39:07 +00006147 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006148 break;
6149 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006150 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006151 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006152 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006153 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006154 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006155 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006156 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6157 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006158 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6159 SubOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006160
6161 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6162 if (CI->isMinValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006163 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006164 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006165 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006166 break;
6167 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006168 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006169 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006170 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006171 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006172
6173 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006174 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006175 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6176 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006177 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6178 AddOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006179
6180 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6181 if (CI->isMaxValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006182 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersonaac28372009-07-31 20:28:14 +00006183 Constant::getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006184 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006185 break;
6186 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006187 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006188 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006189 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006190 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006191 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006192 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006193 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6194 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006195 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6196 SubOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006197 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006198 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006199 case ICmpInst::ICMP_SGT:
6200 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006201 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006202 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006203 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006204
6205 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006206 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006207 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6208 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006209 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6210 AddOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006211 }
6212 break;
6213 case ICmpInst::ICMP_SGE:
6214 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6215 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006216 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006217 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006218 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006219 break;
6220 case ICmpInst::ICMP_SLE:
6221 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6222 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006223 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006224 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006225 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006226 break;
6227 case ICmpInst::ICMP_UGE:
6228 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6229 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006230 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006231 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006232 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006233 break;
6234 case ICmpInst::ICMP_ULE:
6235 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6236 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006237 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006238 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006239 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006240 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006241 }
Dan Gohman7934d592009-04-25 17:12:48 +00006242
6243 // Turn a signed comparison into an unsigned one if both operands
6244 // are known to have the same sign.
6245 if (I.isSignedPredicate() &&
6246 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6247 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006248 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006249 }
6250
6251 // Test if the ICmpInst instruction is used exclusively by a select as
6252 // part of a minimum or maximum operation. If so, refrain from doing
6253 // any other folding. This helps out other analyses which understand
6254 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6255 // and CodeGen. And in this case, at least one of the comparison
6256 // operands has at least one user besides the compare (the select),
6257 // which would often largely negate the benefit of folding anyway.
6258 if (I.hasOneUse())
6259 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6260 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6261 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6262 return 0;
6263
6264 // See if we are doing a comparison between a constant and an instruction that
6265 // can be folded into the comparison.
6266 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006267 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6268 // instruction, see if that instruction also has constants so that the
6269 // instruction can be folded into the icmp
6270 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6271 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6272 return Res;
6273 }
6274
6275 // Handle icmp with constant (but not simple integer constant) RHS
6276 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6277 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6278 switch (LHSI->getOpcode()) {
6279 case Instruction::GetElementPtr:
6280 if (RHSC->isNullValue()) {
6281 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6282 bool isAllZeros = true;
6283 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6284 if (!isa<Constant>(LHSI->getOperand(i)) ||
6285 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6286 isAllZeros = false;
6287 break;
6288 }
6289 if (isAllZeros)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006290 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersonaac28372009-07-31 20:28:14 +00006291 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006292 }
6293 break;
6294
6295 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006296 // Only fold icmp into the PHI if the phi and fcmp are in the same
6297 // block. If in the same block, we're encouraging jump threading. If
6298 // not, we are just pessimizing the code by making an i1 phi.
6299 if (LHSI->getParent() == I.getParent())
6300 if (Instruction *NV = FoldOpIntoPhi(I))
6301 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006302 break;
6303 case Instruction::Select: {
6304 // If either operand of the select is a constant, we can fold the
6305 // comparison into the select arms, which will cause one to be
6306 // constant folded and the select turned into a bitwise or.
6307 Value *Op1 = 0, *Op2 = 0;
6308 if (LHSI->hasOneUse()) {
6309 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6310 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006311 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006312 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006313 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006314 LHSI->getOperand(2), RHSC,
6315 I.getName()), I);
6316 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6317 // Fold the known value into the constant operand.
Owen Anderson02b48c32009-07-29 18:55:55 +00006318 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006319 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006320 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006321 LHSI->getOperand(1), RHSC,
6322 I.getName()), I);
6323 }
6324 }
6325
6326 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006327 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006328 break;
6329 }
6330 case Instruction::Malloc:
6331 // If we have (malloc != null), and if the malloc has a single use, we
6332 // can assume it is successful and remove the malloc.
6333 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6334 AddToWorkList(LHSI);
Owen Andersoneacb44d2009-07-24 23:12:02 +00006335 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006336 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006337 }
6338 break;
6339 }
6340 }
6341
6342 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohman17f46f72009-07-28 01:40:03 +00006343 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006344 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6345 return NI;
Dan Gohman17f46f72009-07-28 01:40:03 +00006346 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006347 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6348 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6349 return NI;
6350
6351 // Test to see if the operands of the icmp are casted versions of other
6352 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6353 // now.
6354 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6355 if (isa<PointerType>(Op0->getType()) &&
6356 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6357 // We keep moving the cast from the left operand over to the right
6358 // operand, where it can often be eliminated completely.
6359 Op0 = CI->getOperand(0);
6360
6361 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6362 // so eliminate it as well.
6363 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6364 Op1 = CI2->getOperand(0);
6365
6366 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006367 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006368 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson02b48c32009-07-29 18:55:55 +00006369 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006370 } else {
6371 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006372 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006373 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006374 }
Owen Anderson6601fcd2009-07-09 23:48:35 +00006375 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006376 }
6377 }
6378
6379 if (isa<CastInst>(Op0)) {
6380 // Handle the special case of: icmp (cast bool to X), <cst>
6381 // This comes up when you have code like
6382 // int X = A < B;
6383 // if (X) ...
6384 // For generality, we handle any zero-extension of any operand comparison
6385 // with a constant or another cast from the same type.
6386 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6387 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6388 return R;
6389 }
6390
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006391 // See if it's the same type of instruction on the left and right.
6392 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6393 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006394 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006395 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006396 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006397 default: break;
6398 case Instruction::Add:
6399 case Instruction::Sub:
6400 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006401 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson6601fcd2009-07-09 23:48:35 +00006402 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006403 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006404 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6405 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6406 if (CI->getValue().isSignBit()) {
6407 ICmpInst::Predicate Pred = I.isSignedPredicate()
6408 ? I.getUnsignedPredicate()
6409 : I.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006410 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006411 Op1I->getOperand(0));
6412 }
6413
6414 if (CI->getValue().isMaxSignedValue()) {
6415 ICmpInst::Predicate Pred = I.isSignedPredicate()
6416 ? I.getUnsignedPredicate()
6417 : I.getSignedPredicate();
6418 Pred = I.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006419 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006420 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006421 }
6422 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006423 break;
6424 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006425 if (!I.isEquality())
6426 break;
6427
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006428 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6429 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6430 // Mask = -1 >> count-trailing-zeros(Cst).
6431 if (!CI->isZero() && !CI->isOne()) {
6432 const APInt &AP = CI->getValue();
Owen Andersoneacb44d2009-07-24 23:12:02 +00006433 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006434 APInt::getLowBitsSet(AP.getBitWidth(),
6435 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006436 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006437 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6438 Mask);
6439 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6440 Mask);
6441 InsertNewInstBefore(And1, I);
6442 InsertNewInstBefore(And2, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006443 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006444 }
6445 }
6446 break;
6447 }
6448 }
6449 }
6450 }
6451
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006452 // ~x < ~y --> y < x
6453 { Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00006454 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6455 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006456 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006457 }
6458
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006459 if (I.isEquality()) {
6460 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006461
6462 // -x == -y --> x == y
Owen Andersona21eb582009-07-10 17:35:01 +00006463 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6464 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006465 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006466
Owen Andersona21eb582009-07-10 17:35:01 +00006467 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006468 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6469 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006470 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006471 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006472 }
6473
Owen Andersona21eb582009-07-10 17:35:01 +00006474 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006475 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006476 ConstantInt *C1, *C2;
Owen Andersona21eb582009-07-10 17:35:01 +00006477 if (match(B, m_ConstantInt(C1), *Context) &&
6478 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006479 Constant *NC =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006480 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner3b874082008-11-16 05:38:51 +00006481 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson6601fcd2009-07-09 23:48:35 +00006482 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattner3b874082008-11-16 05:38:51 +00006483 InsertNewInstBefore(Xor, I));
6484 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006485
6486 // A^B == A^D -> B == D
Owen Anderson6601fcd2009-07-09 23:48:35 +00006487 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6488 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6489 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6490 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006491 }
6492 }
6493
Owen Andersona21eb582009-07-10 17:35:01 +00006494 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006495 (A == Op0 || B == Op0)) {
6496 // A == (A^B) -> B == 0
6497 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006498 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersonaac28372009-07-31 20:28:14 +00006499 Constant::getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006500 }
Chris Lattner3b874082008-11-16 05:38:51 +00006501
6502 // (A-B) == A -> B == 0
Owen Andersona21eb582009-07-10 17:35:01 +00006503 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006504 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006505 Constant::getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006506
6507 // A == (A-B) -> B == 0
Owen Andersona21eb582009-07-10 17:35:01 +00006508 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006509 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersonaac28372009-07-31 20:28:14 +00006510 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006511
6512 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6513 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00006514 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6515 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006516 Value *X = 0, *Y = 0, *Z = 0;
6517
6518 if (A == C) {
6519 X = B; Y = D; Z = A;
6520 } else if (A == D) {
6521 X = B; Y = C; Z = A;
6522 } else if (B == C) {
6523 X = A; Y = D; Z = B;
6524 } else if (B == D) {
6525 X = A; Y = C; Z = B;
6526 }
6527
6528 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006529 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6530 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006531 I.setOperand(0, Op1);
Owen Andersonaac28372009-07-31 20:28:14 +00006532 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006533 return &I;
6534 }
6535 }
6536 }
6537 return Changed ? &I : 0;
6538}
6539
6540
6541/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6542/// and CmpRHS are both known to be integer constants.
6543Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6544 ConstantInt *DivRHS) {
6545 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6546 const APInt &CmpRHSV = CmpRHS->getValue();
6547
6548 // FIXME: If the operand types don't match the type of the divide
6549 // then don't attempt this transform. The code below doesn't have the
6550 // logic to deal with a signed divide and an unsigned compare (and
6551 // vice versa). This is because (x /s C1) <s C2 produces different
6552 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6553 // (x /u C1) <u C2. Simply casting the operands and result won't
6554 // work. :( The if statement below tests that condition and bails
6555 // if it finds it.
6556 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6557 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6558 return 0;
6559 if (DivRHS->isZero())
6560 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006561 if (DivIsSigned && DivRHS->isAllOnesValue())
6562 return 0; // The overflow computation also screws up here
6563 if (DivRHS->isOne())
6564 return 0; // Not worth bothering, and eliminates some funny cases
6565 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006566
6567 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6568 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6569 // C2 (CI). By solving for X we can turn this into a range check
6570 // instead of computing a divide.
Owen Anderson02b48c32009-07-29 18:55:55 +00006571 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006572
6573 // Determine if the product overflows by seeing if the product is
6574 // not equal to the divide. Make sure we do the same kind of divide
6575 // as in the LHS instruction that we're folding.
Owen Anderson02b48c32009-07-29 18:55:55 +00006576 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6577 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006578
6579 // Get the ICmp opcode
6580 ICmpInst::Predicate Pred = ICI.getPredicate();
6581
6582 // Figure out the interval that is being checked. For example, a comparison
6583 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6584 // Compute this interval based on the constants involved and the signedness of
6585 // the compare/divide. This computes a half-open interval, keeping track of
6586 // whether either value in the interval overflows. After analysis each
6587 // overflow variable is set to 0 if it's corresponding bound variable is valid
6588 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6589 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006590 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006591
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006592 if (!DivIsSigned) { // udiv
6593 // e.g. X/5 op 3 --> [15, 20)
6594 LoBound = Prod;
6595 HiOverflow = LoOverflow = ProdOV;
6596 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006597 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006598 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006599 if (CmpRHSV == 0) { // (X / pos) op 0
6600 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Anderson02b48c32009-07-29 18:55:55 +00006601 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS,
Owen Anderson24be4c12009-07-03 00:17:18 +00006602 Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006603 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006604 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006605 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6606 HiOverflow = LoOverflow = ProdOV;
6607 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006608 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006609 } else { // (X / pos) op neg
6610 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Anderson24be4c12009-07-03 00:17:18 +00006611 HiBound = AddOne(Prod, Context);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006612 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6613 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006614 ConstantInt* DivNeg =
Owen Anderson02b48c32009-07-29 18:55:55 +00006615 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Anderson24be4c12009-07-03 00:17:18 +00006616 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006617 true) ? -1 : 0;
6618 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006619 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006620 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006621 if (CmpRHSV == 0) { // (X / neg) op 0
6622 // e.g. X/-5 op 0 --> [-4, 5)
Owen Anderson24be4c12009-07-03 00:17:18 +00006623 LoBound = AddOne(DivRHS, Context);
Owen Anderson02b48c32009-07-29 18:55:55 +00006624 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006625 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6626 HiOverflow = 1; // [INTMIN+1, overflow)
6627 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6628 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006629 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006630 // e.g. X/-5 op 3 --> [-19, -14)
Owen Anderson24be4c12009-07-03 00:17:18 +00006631 HiBound = AddOne(Prod, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006632 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6633 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006634 LoOverflow = AddWithOverflow(LoBound, HiBound,
6635 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006636 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006637 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6638 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006639 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006640 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006641 }
6642
6643 // Dividing by a negative swaps the condition. LT <-> GT
6644 Pred = ICmpInst::getSwappedPredicate(Pred);
6645 }
6646
6647 Value *X = DivI->getOperand(0);
6648 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006649 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006650 case ICmpInst::ICMP_EQ:
6651 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006652 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006653 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006654 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006655 ICmpInst::ICMP_UGE, X, LoBound);
6656 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006657 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006658 ICmpInst::ICMP_ULT, X, HiBound);
6659 else
6660 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6661 case ICmpInst::ICMP_NE:
6662 if (LoOverflow && HiOverflow)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006663 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006664 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006665 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006666 ICmpInst::ICMP_ULT, X, LoBound);
6667 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006668 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006669 ICmpInst::ICMP_UGE, X, HiBound);
6670 else
6671 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6672 case ICmpInst::ICMP_ULT:
6673 case ICmpInst::ICMP_SLT:
6674 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006675 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006676 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006677 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Owen Anderson6601fcd2009-07-09 23:48:35 +00006678 return new ICmpInst(*Context, Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006679 case ICmpInst::ICMP_UGT:
6680 case ICmpInst::ICMP_SGT:
6681 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006682 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson4f720fa2009-07-31 17:39:07 +00006684 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006685 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006686 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006687 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006688 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006689 }
6690}
6691
6692
6693/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6694///
6695Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6696 Instruction *LHSI,
6697 ConstantInt *RHS) {
6698 const APInt &RHSV = RHS->getValue();
6699
6700 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006701 case Instruction::Trunc:
6702 if (ICI.isEquality() && LHSI->hasOneUse()) {
6703 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6704 // of the high bits truncated out of x are known.
6705 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6706 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6707 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6708 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6709 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6710
6711 // If all the high bits are known, we can do this xform.
6712 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6713 // Pull in the high bits from known-ones set.
6714 APInt NewRHS(RHS->getValue());
6715 NewRHS.zext(SrcBits);
6716 NewRHS |= KnownOne;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006717 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006718 ConstantInt::get(*Context, NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006719 }
6720 }
6721 break;
6722
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006723 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6724 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6725 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6726 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006727 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6728 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006729 Value *CompareVal = LHSI->getOperand(0);
6730
6731 // If the sign bit of the XorCST is not set, there is no change to
6732 // the operation, just stop using the Xor.
6733 if (!XorCST->getValue().isNegative()) {
6734 ICI.setOperand(0, CompareVal);
6735 AddToWorkList(LHSI);
6736 return &ICI;
6737 }
6738
6739 // Was the old condition true if the operand is positive?
6740 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6741
6742 // If so, the new one isn't.
6743 isTrueIfPositive ^= true;
6744
6745 if (isTrueIfPositive)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006746 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006747 SubOne(RHS, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006748 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006749 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006750 AddOne(RHS, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006751 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006752
6753 if (LHSI->hasOneUse()) {
6754 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6755 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6756 const APInt &SignBit = XorCST->getValue();
6757 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6758 ? ICI.getUnsignedPredicate()
6759 : ICI.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006760 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006761 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006762 }
6763
6764 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006765 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006766 const APInt &NotSignBit = XorCST->getValue();
6767 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6768 ? ICI.getUnsignedPredicate()
6769 : ICI.getSignedPredicate();
6770 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006771 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006772 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006773 }
6774 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006775 }
6776 break;
6777 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6778 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6779 LHSI->getOperand(0)->hasOneUse()) {
6780 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6781
6782 // If the LHS is an AND of a truncating cast, we can widen the
6783 // and/compare to be the input width without changing the value
6784 // produced, eliminating a cast.
6785 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6786 // We can do this transformation if either the AND constant does not
6787 // have its sign bit set or if it is an equality comparison.
6788 // Extending a relational comparison when we're checking the sign
6789 // bit would not work.
6790 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006791 (ICI.isEquality() ||
6792 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006793 uint32_t BitWidth =
6794 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6795 APInt NewCST = AndCST->getValue();
6796 NewCST.zext(BitWidth);
6797 APInt NewCI = RHSV;
6798 NewCI.zext(BitWidth);
6799 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006800 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00006801 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006802 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006803 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006804 ConstantInt::get(*Context, NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006805 }
6806 }
6807
6808 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6809 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6810 // happens a LOT in code produced by the C front-end, for bitfield
6811 // access.
6812 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6813 if (Shift && !Shift->isShift())
6814 Shift = 0;
6815
6816 ConstantInt *ShAmt;
6817 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6818 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6819 const Type *AndTy = AndCST->getType(); // Type of the and.
6820
6821 // We can fold this as long as we can't shift unknown bits
6822 // into the mask. This can only happen with signed shift
6823 // rights, as they sign-extend.
6824 if (ShAmt) {
6825 bool CanFold = Shift->isLogicalShift();
6826 if (!CanFold) {
6827 // To test for the bad case of the signed shr, see if any
6828 // of the bits shifted in could be tested after the mask.
6829 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6830 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6831
6832 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6833 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6834 AndCST->getValue()) == 0)
6835 CanFold = true;
6836 }
6837
6838 if (CanFold) {
6839 Constant *NewCst;
6840 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006841 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006842 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006843 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006844
6845 // Check to see if we are shifting out any of the bits being
6846 // compared.
Owen Anderson02b48c32009-07-29 18:55:55 +00006847 if (ConstantExpr::get(Shift->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006848 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006849 // If we shifted bits out, the fold is not going to work out.
6850 // As a special case, check to see if this means that the
6851 // result is always true or false now.
6852 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006853 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006854 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00006855 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006856 } else {
6857 ICI.setOperand(1, NewCst);
6858 Constant *NewAndCST;
6859 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson02b48c32009-07-29 18:55:55 +00006860 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006861 else
Owen Anderson02b48c32009-07-29 18:55:55 +00006862 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006863 LHSI->setOperand(1, NewAndCST);
6864 LHSI->setOperand(0, Shift->getOperand(0));
6865 AddToWorkList(Shift); // Shift is dead.
6866 AddUsesToWorkList(ICI);
6867 return &ICI;
6868 }
6869 }
6870 }
6871
6872 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6873 // preferable because it allows the C<<Y expression to be hoisted out
6874 // of a loop if Y is invariant and X is not.
6875 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006876 ICI.isEquality() && !Shift->isArithmeticShift() &&
6877 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006878 // Compute C << Y.
6879 Value *NS;
6880 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006881 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006882 Shift->getOperand(1), "tmp");
6883 } else {
6884 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006885 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006886 Shift->getOperand(1), "tmp");
6887 }
6888 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6889
6890 // Compute X & (C << Y).
6891 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006892 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006893 InsertNewInstBefore(NewAnd, ICI);
6894
6895 ICI.setOperand(0, NewAnd);
6896 return &ICI;
6897 }
6898 }
6899 break;
6900
6901 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6902 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6903 if (!ShAmt) break;
6904
6905 uint32_t TypeBits = RHSV.getBitWidth();
6906
6907 // Check that the shift amount is in range. If not, don't perform
6908 // undefined shifts. When the shift is visited it will be
6909 // simplified.
6910 if (ShAmt->uge(TypeBits))
6911 break;
6912
6913 if (ICI.isEquality()) {
6914 // If we are comparing against bits always shifted out, the
6915 // comparison cannot succeed.
6916 Constant *Comp =
Owen Anderson02b48c32009-07-29 18:55:55 +00006917 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Anderson24be4c12009-07-03 00:17:18 +00006918 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006919 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6920 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneacb44d2009-07-24 23:12:02 +00006921 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006922 return ReplaceInstUsesWith(ICI, Cst);
6923 }
6924
6925 if (LHSI->hasOneUse()) {
6926 // Otherwise strength reduce the shift into an and.
6927 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6928 Constant *Mask =
Owen Andersoneacb44d2009-07-24 23:12:02 +00006929 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Anderson24be4c12009-07-03 00:17:18 +00006930 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006931
6932 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006933 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006934 Mask, LHSI->getName()+".mask");
6935 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006936 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersoneacb44d2009-07-24 23:12:02 +00006937 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006938 }
6939 }
6940
6941 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6942 bool TrueIfSigned = false;
6943 if (LHSI->hasOneUse() &&
6944 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6945 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneacb44d2009-07-24 23:12:02 +00006946 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006947 (TypeBits-ShAmt->getZExtValue()-1));
6948 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006949 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006950 Mask, LHSI->getName()+".mask");
6951 Value *And = InsertNewInstBefore(AndI, ICI);
6952
Owen Anderson6601fcd2009-07-09 23:48:35 +00006953 return new ICmpInst(*Context,
6954 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersonaac28372009-07-31 20:28:14 +00006955 And, Constant::getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006956 }
6957 break;
6958 }
6959
6960 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6961 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006962 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006963 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006964 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006965
Chris Lattner5ee84f82008-03-21 05:19:58 +00006966 // Check that the shift amount is in range. If not, don't perform
6967 // undefined shifts. When the shift is visited it will be
6968 // simplified.
6969 uint32_t TypeBits = RHSV.getBitWidth();
6970 if (ShAmt->uge(TypeBits))
6971 break;
6972
6973 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006974
Chris Lattner5ee84f82008-03-21 05:19:58 +00006975 // If we are comparing against bits always shifted out, the
6976 // comparison cannot succeed.
6977 APInt Comp = RHSV << ShAmtVal;
6978 if (LHSI->getOpcode() == Instruction::LShr)
6979 Comp = Comp.lshr(ShAmtVal);
6980 else
6981 Comp = Comp.ashr(ShAmtVal);
6982
6983 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6984 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersoneacb44d2009-07-24 23:12:02 +00006985 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006986 return ReplaceInstUsesWith(ICI, Cst);
6987 }
6988
6989 // Otherwise, check to see if the bits shifted out are known to be zero.
6990 // If so, we can compare against the unshifted value:
6991 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006992 if (LHSI->hasOneUse() &&
6993 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006994 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00006995 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00006996 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006997 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006998
Evan Chengfb9292a2008-04-23 00:38:06 +00006999 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007000 // Otherwise strength reduce the shift into an and.
7001 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007002 Constant *Mask = ConstantInt::get(*Context, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007003
Chris Lattner5ee84f82008-03-21 05:19:58 +00007004 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00007005 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007006 Mask, LHSI->getName()+".mask");
7007 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007008 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Anderson02b48c32009-07-29 18:55:55 +00007009 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007010 }
7011 break;
7012 }
7013
7014 case Instruction::SDiv:
7015 case Instruction::UDiv:
7016 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7017 // Fold this div into the comparison, producing a range check.
7018 // Determine, based on the divide type, what the range is being
7019 // checked. If there is an overflow on the low or high side, remember
7020 // it, otherwise compute the range [low, hi) bounding the new value.
7021 // See: InsertRangeTest above for the kinds of replacements possible.
7022 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7023 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7024 DivRHS))
7025 return R;
7026 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007027
7028 case Instruction::Add:
7029 // Fold: icmp pred (add, X, C1), C2
7030
7031 if (!ICI.isEquality()) {
7032 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7033 if (!LHSC) break;
7034 const APInt &LHSV = LHSC->getValue();
7035
7036 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7037 .subtract(LHSV);
7038
7039 if (ICI.isSignedPredicate()) {
7040 if (CR.getLower().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007041 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007042 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007043 } else if (CR.getUpper().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007044 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007045 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007046 }
7047 } else {
7048 if (CR.getLower().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007049 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007050 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007051 } else if (CR.getUpper().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007052 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneacb44d2009-07-24 23:12:02 +00007053 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007054 }
7055 }
7056 }
7057 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007058 }
7059
7060 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7061 if (ICI.isEquality()) {
7062 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7063
7064 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7065 // the second operand is a constant, simplify a bit.
7066 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7067 switch (BO->getOpcode()) {
7068 case Instruction::SRem:
7069 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7070 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7071 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7072 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7073 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00007074 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007075 BO->getName());
7076 InsertNewInstBefore(NewRem, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007077 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersonaac28372009-07-31 20:28:14 +00007078 Constant::getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007079 }
7080 }
7081 break;
7082 case Instruction::Add:
7083 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7084 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7085 if (BO->hasOneUse())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007086 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007087 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007088 } else if (RHSV == 0) {
7089 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7090 // efficiently invertible, or if the add has just this one use.
7091 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7092
Owen Anderson24be4c12009-07-03 00:17:18 +00007093 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007094 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Anderson24be4c12009-07-03 00:17:18 +00007095 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007096 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007097 else if (BO->hasOneUse()) {
Owen Anderson15b39322009-07-13 04:09:18 +00007098 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007099 InsertNewInstBefore(Neg, ICI);
7100 Neg->takeName(BO);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007101 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007102 }
7103 }
7104 break;
7105 case Instruction::Xor:
7106 // For the xor case, we can xor two constants together, eliminating
7107 // the explicit xor.
7108 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007109 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007110 ConstantExpr::getXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007111
7112 // FALLTHROUGH
7113 case Instruction::Sub:
7114 // Replace (([sub|xor] A, B) != 0) with (A != B)
7115 if (RHSV == 0)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007116 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007117 BO->getOperand(1));
7118 break;
7119
7120 case Instruction::Or:
7121 // If bits are being or'd in that are not present in the constant we
7122 // are comparing against, then the comparison could never succeed!
7123 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007124 Constant *NotCI = ConstantExpr::getNot(RHS);
7125 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00007126 return ReplaceInstUsesWith(ICI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007127 ConstantInt::get(Type::Int1Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007128 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007129 }
7130 break;
7131
7132 case Instruction::And:
7133 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7134 // If bits are being compared against that are and'd out, then the
7135 // comparison can never succeed!
7136 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007137 return ReplaceInstUsesWith(ICI,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007138 ConstantInt::get(Type::Int1Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00007139 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007140
7141 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7142 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007143 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144 ICmpInst::ICMP_NE, LHSI,
Owen Andersonaac28372009-07-31 20:28:14 +00007145 Constant::getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007146
7147 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007148 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149 Value *X = BO->getOperand(0);
Owen Andersonaac28372009-07-31 20:28:14 +00007150 Constant *Zero = Constant::getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007151 ICmpInst::Predicate pred = isICMP_NE ?
7152 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007153 return new ICmpInst(*Context, pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007154 }
7155
7156 // ((X & ~7) == 0) --> X < 8
7157 if (RHSV == 0 && isHighOnes(BOC)) {
7158 Value *X = BO->getOperand(0);
Owen Anderson02b48c32009-07-29 18:55:55 +00007159 Constant *NegX = ConstantExpr::getNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007160 ICmpInst::Predicate pred = isICMP_NE ?
7161 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007162 return new ICmpInst(*Context, pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007163 }
7164 }
7165 default: break;
7166 }
7167 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7168 // Handle icmp {eq|ne} <intrinsic>, intcst.
7169 if (II->getIntrinsicID() == Intrinsic::bswap) {
7170 AddToWorkList(II);
7171 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007172 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007173 return &ICI;
7174 }
7175 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007176 }
7177 return 0;
7178}
7179
7180/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7181/// We only handle extending casts so far.
7182///
7183Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7184 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7185 Value *LHSCIOp = LHSCI->getOperand(0);
7186 const Type *SrcTy = LHSCIOp->getType();
7187 const Type *DestTy = LHSCI->getType();
7188 Value *RHSCIOp;
7189
7190 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7191 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007192 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7193 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007194 cast<IntegerType>(DestTy)->getBitWidth()) {
7195 Value *RHSOp = 0;
7196 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007197 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007198 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7199 RHSOp = RHSC->getOperand(0);
7200 // If the pointer types don't match, insert a bitcast.
7201 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007202 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007203 }
7204
7205 if (RHSOp)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007206 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007207 }
7208
7209 // The code below only handles extension cast instructions, so far.
7210 // Enforce this.
7211 if (LHSCI->getOpcode() != Instruction::ZExt &&
7212 LHSCI->getOpcode() != Instruction::SExt)
7213 return 0;
7214
7215 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7216 bool isSignedCmp = ICI.isSignedPredicate();
7217
7218 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7219 // Not an extension from the same type?
7220 RHSCIOp = CI->getOperand(0);
7221 if (RHSCIOp->getType() != LHSCIOp->getType())
7222 return 0;
7223
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007224 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007225 // and the other is a zext), then we can't handle this.
7226 if (CI->getOpcode() != LHSCI->getOpcode())
7227 return 0;
7228
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007229 // Deal with equality cases early.
7230 if (ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007231 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007232
7233 // A signed comparison of sign extended values simplifies into a
7234 // signed comparison.
7235 if (isSignedCmp && isSignedExt)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007236 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007237
7238 // The other three cases all fold into an unsigned comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00007239 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007240 }
7241
7242 // If we aren't dealing with a constant on the RHS, exit early
7243 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7244 if (!CI)
7245 return 0;
7246
7247 // Compute the constant that would happen if we truncated to SrcTy then
7248 // reextended to DestTy.
Owen Anderson02b48c32009-07-29 18:55:55 +00007249 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7250 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Anderson24be4c12009-07-03 00:17:18 +00007251 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007252
7253 // If the re-extended constant didn't change...
7254 if (Res2 == CI) {
7255 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7256 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007257 // %A = sext i16 %X to i32
7258 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007259 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007260 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007261 // because %A may have negative value.
7262 //
Chris Lattner3d816532008-07-11 04:09:09 +00007263 // However, we allow this when the compare is EQ/NE, because they are
7264 // signless.
7265 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007266 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007267 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007268 }
7269
7270 // The re-extended constant changed so the constant cannot be represented
7271 // in the shorter type. Consequently, we cannot emit a simple comparison.
7272
7273 // First, handle some easy cases. We know the result cannot be equal at this
7274 // point so handle the ICI.isEquality() cases
7275 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007276 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007277 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson4f720fa2009-07-31 17:39:07 +00007278 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007279
7280 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7281 // should have been folded away previously and not enter in here.
7282 Value *Result;
7283 if (isSignedCmp) {
7284 // We're performing a signed comparison.
7285 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson4f720fa2009-07-31 17:39:07 +00007286 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007287 else
Owen Anderson4f720fa2009-07-31 17:39:07 +00007288 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007289 } else {
7290 // We're performing an unsigned comparison.
7291 if (isSignedExt) {
7292 // We're performing an unsigned comp with a sign extended value.
7293 // This is true if the input is >= 0. [aka >s -1]
Owen Andersonaac28372009-07-31 20:28:14 +00007294 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007295 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7296 LHSCIOp, NegOne, ICI.getName()), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007297 } else {
7298 // Unsigned extend & unsigned compare -> always true.
Owen Anderson4f720fa2009-07-31 17:39:07 +00007299 Result = ConstantInt::getTrue(*Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007300 }
7301 }
7302
7303 // Finally, return the value computed.
7304 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007305 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007306 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007307
7308 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7309 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7310 "ICmp should be folded!");
7311 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson02b48c32009-07-29 18:55:55 +00007312 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Owen Anderson035d41d2009-07-13 20:58:05 +00007313 return BinaryOperator::CreateNot(*Context, Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007314}
7315
7316Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7317 return commonShiftTransforms(I);
7318}
7319
7320Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7321 return commonShiftTransforms(I);
7322}
7323
7324Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007325 if (Instruction *R = commonShiftTransforms(I))
7326 return R;
7327
7328 Value *Op0 = I.getOperand(0);
7329
7330 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7331 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7332 if (CSI->isAllOnesValue())
7333 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007334
Dan Gohman2526aea2009-06-16 19:55:29 +00007335 // See if we can turn a signed shr into an unsigned shr.
7336 if (MaskedValueIsZero(Op0,
7337 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7338 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7339
7340 // Arithmetic shifting an all-sign-bit value is a no-op.
7341 unsigned NumSignBits = ComputeNumSignBits(Op0);
7342 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7343 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007344
Chris Lattnere3c504f2007-12-06 01:59:46 +00007345 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007346}
7347
7348Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7349 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7351
7352 // shl X, 0 == X and shr X, 0 == X
7353 // shl 0, X == 0 and shr 0, X == 0
Owen Andersonaac28372009-07-31 20:28:14 +00007354 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7355 Op0 == Constant::getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007356 return ReplaceInstUsesWith(I, Op0);
7357
7358 if (isa<UndefValue>(Op0)) {
7359 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7360 return ReplaceInstUsesWith(I, Op0);
7361 else // undef << X -> 0, undef >>u X -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007362 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007363 }
7364 if (isa<UndefValue>(Op1)) {
7365 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7366 return ReplaceInstUsesWith(I, Op0);
7367 else // X << undef, X >>u undef -> 0
Owen Andersonaac28372009-07-31 20:28:14 +00007368 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007369 }
7370
Dan Gohman2bc21562009-05-21 02:28:33 +00007371 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007372 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007373 return &I;
7374
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007375 // Try to fold constant and into select arguments.
7376 if (isa<Constant>(Op0))
7377 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7378 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7379 return R;
7380
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007381 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7382 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7383 return Res;
7384 return 0;
7385}
7386
7387Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7388 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007389 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390
7391 // See if we can simplify any instructions used by the instruction whose sole
7392 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007393 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007394
Dan Gohman9e1657f2009-06-14 23:30:43 +00007395 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7396 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007397 //
7398 if (Op1->uge(TypeBits)) {
7399 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007400 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007401 else {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007402 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007403 return &I;
7404 }
7405 }
7406
7407 // ((X*C1) << C2) == (X * (C1 << C2))
7408 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7409 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7410 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007411 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson02b48c32009-07-29 18:55:55 +00007412 ConstantExpr::getShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007413
7414 // Try to fold constant and into select arguments.
7415 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7416 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7417 return R;
7418 if (isa<PHINode>(Op0))
7419 if (Instruction *NV = FoldOpIntoPhi(I))
7420 return NV;
7421
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007422 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7423 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7424 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7425 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7426 // place. Don't try to do this transformation in this case. Also, we
7427 // require that the input operand is a shift-by-constant so that we have
7428 // confidence that the shifts will get folded together. We could do this
7429 // xform in more cases, but it is unlikely to be profitable.
7430 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7431 isa<ConstantInt>(TrOp->getOperand(1))) {
7432 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson02b48c32009-07-29 18:55:55 +00007433 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007434 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007435 I.getName());
7436 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7437
7438 // For logical shifts, the truncation has the effect of making the high
7439 // part of the register be zeros. Emulate this by inserting an AND to
7440 // clear the top bits as needed. This 'and' will usually be zapped by
7441 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007442 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7443 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007444 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7445
7446 // The mask we constructed says what the trunc would do if occurring
7447 // between the shifts. We want to know the effect *after* the second
7448 // shift. We know that it is a logical shift by a constant, so adjust the
7449 // mask as appropriate.
7450 if (I.getOpcode() == Instruction::Shl)
7451 MaskV <<= Op1->getZExtValue();
7452 else {
7453 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7454 MaskV = MaskV.lshr(Op1->getZExtValue());
7455 }
7456
Owen Anderson24be4c12009-07-03 00:17:18 +00007457 Instruction *And =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007458 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
Owen Anderson24be4c12009-07-03 00:17:18 +00007459 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007460 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7461
7462 // Return the value truncated to the interesting size.
7463 return new TruncInst(And, I.getType());
7464 }
7465 }
7466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007467 if (Op0->hasOneUse()) {
7468 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7469 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7470 Value *V1, *V2;
7471 ConstantInt *CC;
7472 switch (Op0BO->getOpcode()) {
7473 default: break;
7474 case Instruction::Add:
7475 case Instruction::And:
7476 case Instruction::Or:
7477 case Instruction::Xor: {
7478 // These operators commute.
7479 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7480 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007481 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7482 m_Specific(Op1)), *Context)){
Gabor Greifa645dd32008-05-16 19:29:10 +00007483 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007484 Op0BO->getOperand(0), Op1,
7485 Op0BO->getName());
7486 InsertNewInstBefore(YS, I); // (Y << C)
7487 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007488 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007489 Op0BO->getOperand(1)->getName());
7490 InsertNewInstBefore(X, I); // (X + (Y << C))
7491 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007492 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007493 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7494 }
7495
7496 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7497 Value *Op0BOOp1 = Op0BO->getOperand(1);
7498 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7499 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007500 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersona21eb582009-07-10 17:35:01 +00007501 m_ConstantInt(CC)), *Context) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007502 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007503 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007504 Op0BO->getOperand(0), Op1,
7505 Op0BO->getName());
7506 InsertNewInstBefore(YS, I); // (Y << C)
7507 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007508 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007509 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007510 V1->getName()+".mask");
7511 InsertNewInstBefore(XM, I); // X & (CC << C)
7512
Gabor Greifa645dd32008-05-16 19:29:10 +00007513 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007514 }
7515 }
7516
7517 // FALL THROUGH.
7518 case Instruction::Sub: {
7519 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7520 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007521 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7522 m_Specific(Op1)), *Context)){
Gabor Greifa645dd32008-05-16 19:29:10 +00007523 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007524 Op0BO->getOperand(1), Op1,
7525 Op0BO->getName());
7526 InsertNewInstBefore(YS, I); // (Y << C)
7527 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007528 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007529 Op0BO->getOperand(0)->getName());
7530 InsertNewInstBefore(X, I); // (X + (Y << C))
7531 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneacb44d2009-07-24 23:12:02 +00007532 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007533 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7534 }
7535
7536 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7537 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7538 match(Op0BO->getOperand(0),
7539 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersona21eb582009-07-10 17:35:01 +00007540 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007541 cast<BinaryOperator>(Op0BO->getOperand(0))
7542 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007543 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007544 Op0BO->getOperand(1), Op1,
7545 Op0BO->getName());
7546 InsertNewInstBefore(YS, I); // (Y << C)
7547 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007548 BinaryOperator::CreateAnd(V1,
Owen Anderson02b48c32009-07-29 18:55:55 +00007549 ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007550 V1->getName()+".mask");
7551 InsertNewInstBefore(XM, I); // X & (CC << C)
7552
Gabor Greifa645dd32008-05-16 19:29:10 +00007553 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007554 }
7555
7556 break;
7557 }
7558 }
7559
7560
7561 // If the operand is an bitwise operator with a constant RHS, and the
7562 // shift is the only use, we can pull it out of the shift.
7563 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7564 bool isValid = true; // Valid only for And, Or, Xor
7565 bool highBitSet = false; // Transform if high bit of constant set?
7566
7567 switch (Op0BO->getOpcode()) {
7568 default: isValid = false; break; // Do not perform transform!
7569 case Instruction::Add:
7570 isValid = isLeftShift;
7571 break;
7572 case Instruction::Or:
7573 case Instruction::Xor:
7574 highBitSet = false;
7575 break;
7576 case Instruction::And:
7577 highBitSet = true;
7578 break;
7579 }
7580
7581 // If this is a signed shift right, and the high bit is modified
7582 // by the logical operation, do not perform the transformation.
7583 // The highBitSet boolean indicates the value of the high bit of
7584 // the constant which would cause it to be modified for this
7585 // operation.
7586 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007587 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007588 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007589
7590 if (isValid) {
Owen Anderson02b48c32009-07-29 18:55:55 +00007591 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007592
7593 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007594 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007595 InsertNewInstBefore(NewShift, I);
7596 NewShift->takeName(Op0BO);
7597
Gabor Greifa645dd32008-05-16 19:29:10 +00007598 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007599 NewRHS);
7600 }
7601 }
7602 }
7603 }
7604
7605 // Find out if this is a shift of a shift by a constant.
7606 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7607 if (ShiftOp && !ShiftOp->isShift())
7608 ShiftOp = 0;
7609
7610 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7611 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7612 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7613 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7614 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7615 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7616 Value *X = ShiftOp->getOperand(0);
7617
7618 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007619
7620 const IntegerType *Ty = cast<IntegerType>(I.getType());
7621
7622 // Check for (X << c1) << c2 and (X >> c1) >> c2
7623 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007624 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7625 // saturates.
7626 if (AmtSum >= TypeBits) {
7627 if (I.getOpcode() != Instruction::AShr)
Owen Andersonaac28372009-07-31 20:28:14 +00007628 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007629 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7630 }
7631
Gabor Greifa645dd32008-05-16 19:29:10 +00007632 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007633 ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007634 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7635 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007636 if (AmtSum >= TypeBits)
Owen Andersonaac28372009-07-31 20:28:14 +00007637 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007638
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007639 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneacb44d2009-07-24 23:12:02 +00007640 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007641 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7642 I.getOpcode() == Instruction::LShr) {
7643 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007644 if (AmtSum >= TypeBits)
7645 AmtSum = TypeBits-1;
7646
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007647 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007648 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007649 InsertNewInstBefore(Shift, I);
7650
7651 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007652 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007653 }
7654
7655 // Okay, if we get here, one shift must be left, and the other shift must be
7656 // right. See if the amounts are equal.
7657 if (ShiftAmt1 == ShiftAmt2) {
7658 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7659 if (I.getOpcode() == Instruction::Shl) {
7660 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007661 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007662 }
7663 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7664 if (I.getOpcode() == Instruction::LShr) {
7665 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007666 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007667 }
7668 // We can simplify ((X << C) >>s C) into a trunc + sext.
7669 // NOTE: we could do this for any C, but that would make 'unusual' integer
7670 // types. For now, just stick to ones well-supported by the code
7671 // generators.
7672 const Type *SExtType = 0;
7673 switch (Ty->getBitWidth() - ShiftAmt1) {
7674 case 1 :
7675 case 8 :
7676 case 16 :
7677 case 32 :
7678 case 64 :
7679 case 128:
Owen Anderson6b6e2d92009-07-29 22:17:13 +00007680 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007681 break;
7682 default: break;
7683 }
7684 if (SExtType) {
7685 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7686 InsertNewInstBefore(NewTrunc, I);
7687 return new SExtInst(NewTrunc, Ty);
7688 }
7689 // Otherwise, we can't handle it yet.
7690 } else if (ShiftAmt1 < ShiftAmt2) {
7691 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7692
7693 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7694 if (I.getOpcode() == Instruction::Shl) {
7695 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7696 ShiftOp->getOpcode() == Instruction::AShr);
7697 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007698 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007699 InsertNewInstBefore(Shift, I);
7700
7701 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007702 return BinaryOperator::CreateAnd(Shift,
7703 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007704 }
7705
7706 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7707 if (I.getOpcode() == Instruction::LShr) {
7708 assert(ShiftOp->getOpcode() == Instruction::Shl);
7709 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007710 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007711 InsertNewInstBefore(Shift, I);
7712
7713 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007714 return BinaryOperator::CreateAnd(Shift,
7715 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 }
7717
7718 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7719 } else {
7720 assert(ShiftAmt2 < ShiftAmt1);
7721 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7722
7723 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7724 if (I.getOpcode() == Instruction::Shl) {
7725 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7726 ShiftOp->getOpcode() == Instruction::AShr);
7727 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007728 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneacb44d2009-07-24 23:12:02 +00007729 ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007730 InsertNewInstBefore(Shift, I);
7731
7732 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007733 return BinaryOperator::CreateAnd(Shift,
7734 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007735 }
7736
7737 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7738 if (I.getOpcode() == Instruction::LShr) {
7739 assert(ShiftOp->getOpcode() == Instruction::Shl);
7740 Instruction *Shift =
Owen Andersoneacb44d2009-07-24 23:12:02 +00007741 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007742 InsertNewInstBefore(Shift, I);
7743
7744 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneacb44d2009-07-24 23:12:02 +00007745 return BinaryOperator::CreateAnd(Shift,
7746 ConstantInt::get(*Context, Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007747 }
7748
7749 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7750 }
7751 }
7752 return 0;
7753}
7754
7755
7756/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7757/// expression. If so, decompose it, returning some value X, such that Val is
7758/// X*Scale+Offset.
7759///
7760static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007761 int &Offset, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007762 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7763 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7764 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007765 Scale = 0;
Owen Andersoneacb44d2009-07-24 23:12:02 +00007766 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007767 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7768 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7769 if (I->getOpcode() == Instruction::Shl) {
7770 // This is a value scaled by '1 << the shift amt'.
7771 Scale = 1U << RHS->getZExtValue();
7772 Offset = 0;
7773 return I->getOperand(0);
7774 } else if (I->getOpcode() == Instruction::Mul) {
7775 // This value is scaled by 'RHS'.
7776 Scale = RHS->getZExtValue();
7777 Offset = 0;
7778 return I->getOperand(0);
7779 } else if (I->getOpcode() == Instruction::Add) {
7780 // We have X+C. Check to see if we really have (X*C2)+C1,
7781 // where C1 is divisible by C2.
7782 unsigned SubScale;
7783 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007784 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7785 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007786 Offset += RHS->getZExtValue();
7787 Scale = SubScale;
7788 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007789 }
7790 }
7791 }
7792
7793 // Otherwise, we can't look past this.
7794 Scale = 1;
7795 Offset = 0;
7796 return Val;
7797}
7798
7799
7800/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7801/// try to eliminate the cast by moving the type information into the alloc.
7802Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7803 AllocationInst &AI) {
7804 const PointerType *PTy = cast<PointerType>(CI.getType());
7805
7806 // Remove any uses of AI that are dead.
7807 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7808
7809 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7810 Instruction *User = cast<Instruction>(*UI++);
7811 if (isInstructionTriviallyDead(User)) {
7812 while (UI != E && *UI == User)
7813 ++UI; // If this instruction uses AI more than once, don't break UI.
7814
7815 ++NumDeadInst;
7816 DOUT << "IC: DCE: " << *User;
7817 EraseInstFromFunction(*User);
7818 }
7819 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007820
7821 // This requires TargetData to get the alloca alignment and size information.
7822 if (!TD) return 0;
7823
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007824 // Get the type really allocated and the type casted to.
7825 const Type *AllocElTy = AI.getAllocatedType();
7826 const Type *CastElTy = PTy->getElementType();
7827 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7828
7829 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7830 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7831 if (CastElTyAlign < AllocElTyAlign) return 0;
7832
7833 // If the allocation has multiple uses, only promote it if we are strictly
7834 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007835 // same, we open the door to infinite loops of various kinds. (A reference
7836 // from a dbg.declare doesn't count as a use for this purpose.)
7837 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7838 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007839
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007840 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7841 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007842 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7843
7844 // See if we can satisfy the modulus by pulling a scale out of the array
7845 // size argument.
7846 unsigned ArraySizeScale;
7847 int ArrayOffset;
7848 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007849 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7850 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007851
7852 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7853 // do the xform.
7854 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7855 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7856
7857 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7858 Value *Amt = 0;
7859 if (Scale == 1) {
7860 Amt = NumElements;
7861 } else {
7862 // If the allocation size is constant, form a constant mul expression
Owen Andersoneacb44d2009-07-24 23:12:02 +00007863 Amt = ConstantInt::get(Type::Int32Ty, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007864 if (isa<ConstantInt>(NumElements))
Owen Anderson02b48c32009-07-29 18:55:55 +00007865 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman8fd520a2009-06-15 22:12:54 +00007866 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007867 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007868 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007869 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007870 Amt = InsertNewInstBefore(Tmp, AI);
7871 }
7872 }
7873
7874 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00007875 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007876 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007877 Amt = InsertNewInstBefore(Tmp, AI);
7878 }
7879
7880 AllocationInst *New;
7881 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +00007882 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007883 else
Owen Anderson140166d2009-07-15 23:53:25 +00007884 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007885 InsertNewInstBefore(New, AI);
7886 New->takeName(&AI);
7887
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007888 // If the allocation has one real use plus a dbg.declare, just remove the
7889 // declare.
7890 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7891 EraseInstFromFunction(*DI);
7892 }
7893 // If the allocation has multiple real uses, insert a cast and change all
7894 // things that used it to use the new cast. This will also hack on CI, but it
7895 // will die soon.
7896 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007897 AddUsesToWorkList(AI);
7898 // New is the allocation instruction, pointer typed. AI is the original
7899 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7900 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7901 InsertNewInstBefore(NewCast, AI);
7902 AI.replaceAllUsesWith(NewCast);
7903 }
7904 return ReplaceInstUsesWith(CI, New);
7905}
7906
7907/// CanEvaluateInDifferentType - Return true if we can take the specified value
7908/// and return it as type Ty without inserting any new casts and without
7909/// changing the computed value. This is used by code that tries to decide
7910/// whether promoting or shrinking integer operations to wider or smaller types
7911/// will allow us to eliminate a truncate or extend.
7912///
7913/// This is a truncation operation if Ty is smaller than V->getType(), or an
7914/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007915///
7916/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7917/// should return true if trunc(V) can be computed by computing V in the smaller
7918/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7919/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7920/// efficiently truncated.
7921///
7922/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7923/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7924/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007925bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007926 unsigned CastOpc,
7927 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007929 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007930 return true;
7931
7932 Instruction *I = dyn_cast<Instruction>(V);
7933 if (!I) return false;
7934
Dan Gohman8fd520a2009-06-15 22:12:54 +00007935 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007936
Chris Lattneref70bb82007-08-02 06:11:14 +00007937 // If this is an extension or truncate, we can often eliminate it.
7938 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7939 // If this is a cast from the destination type, we can trivially eliminate
7940 // it, and this will remove a cast overall.
7941 if (I->getOperand(0)->getType() == Ty) {
7942 // If the first operand is itself a cast, and is eliminable, do not count
7943 // this as an eliminable cast. We would prefer to eliminate those two
7944 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007945 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007946 ++NumCastsRemoved;
7947 return true;
7948 }
7949 }
7950
7951 // We can't extend or shrink something that has multiple uses: doing so would
7952 // require duplicating the instruction in general, which isn't profitable.
7953 if (!I->hasOneUse()) return false;
7954
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007955 unsigned Opc = I->getOpcode();
7956 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007957 case Instruction::Add:
7958 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007959 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007960 case Instruction::And:
7961 case Instruction::Or:
7962 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007963 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007964 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007965 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007966 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007967 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007968
Eli Friedman08c45bc2009-07-13 22:46:01 +00007969 case Instruction::UDiv:
7970 case Instruction::URem: {
7971 // UDiv and URem can be truncated if all the truncated bits are zero.
7972 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7973 uint32_t BitWidth = Ty->getScalarSizeInBits();
7974 if (BitWidth < OrigBitWidth) {
7975 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7976 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7977 MaskedValueIsZero(I->getOperand(1), Mask)) {
7978 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7979 NumCastsRemoved) &&
7980 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7981 NumCastsRemoved);
7982 }
7983 }
7984 break;
7985 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007986 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007987 // If we are truncating the result of this SHL, and if it's a shift of a
7988 // constant amount, we can always perform a SHL in a smaller type.
7989 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007990 uint32_t BitWidth = Ty->getScalarSizeInBits();
7991 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007993 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007994 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007995 }
7996 break;
7997 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007998 // If this is a truncate of a logical shr, we can truncate it to a smaller
7999 // lshr iff we know that the bits we would otherwise be shifting in are
8000 // already zeros.
8001 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008002 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8003 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008004 if (BitWidth < OrigBitWidth &&
8005 MaskedValueIsZero(I->getOperand(0),
8006 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8007 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008008 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008009 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008010 }
8011 }
8012 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008013 case Instruction::ZExt:
8014 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008015 case Instruction::Trunc:
8016 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008017 // can safely replace it. Note that replacing it does not reduce the number
8018 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008019 if (Opc == CastOpc)
8020 return true;
8021
8022 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008023 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008024 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008025 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008026 case Instruction::Select: {
8027 SelectInst *SI = cast<SelectInst>(I);
8028 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008029 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008030 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008031 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008032 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008033 case Instruction::PHI: {
8034 // We can change a phi if we can change all operands.
8035 PHINode *PN = cast<PHINode>(I);
8036 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8037 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008038 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008039 return false;
8040 return true;
8041 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008042 default:
8043 // TODO: Can handle more cases here.
8044 break;
8045 }
8046
8047 return false;
8048}
8049
8050/// EvaluateInDifferentType - Given an expression that
8051/// CanEvaluateInDifferentType returns true for, actually insert the code to
8052/// evaluate the expression.
8053Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8054 bool isSigned) {
8055 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +00008056 return ConstantExpr::getIntegerCast(C, Ty,
Owen Anderson24be4c12009-07-03 00:17:18 +00008057 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008058
8059 // Otherwise, it must be an instruction.
8060 Instruction *I = cast<Instruction>(V);
8061 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008062 unsigned Opc = I->getOpcode();
8063 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008064 case Instruction::Add:
8065 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008066 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008067 case Instruction::And:
8068 case Instruction::Or:
8069 case Instruction::Xor:
8070 case Instruction::AShr:
8071 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008072 case Instruction::Shl:
8073 case Instruction::UDiv:
8074 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008075 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8076 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008077 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008078 break;
8079 }
8080 case Instruction::Trunc:
8081 case Instruction::ZExt:
8082 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008083 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008084 // just return the source. There's no need to insert it because it is not
8085 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008086 if (I->getOperand(0)->getType() == Ty)
8087 return I->getOperand(0);
8088
Chris Lattner4200c2062008-06-18 04:00:49 +00008089 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008090 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008091 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008092 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008093 case Instruction::Select: {
8094 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8095 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8096 Res = SelectInst::Create(I->getOperand(0), True, False);
8097 break;
8098 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008099 case Instruction::PHI: {
8100 PHINode *OPN = cast<PHINode>(I);
8101 PHINode *NPN = PHINode::Create(Ty);
8102 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8103 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8104 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8105 }
8106 Res = NPN;
8107 break;
8108 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008109 default:
8110 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008111 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008112 break;
8113 }
8114
Chris Lattner4200c2062008-06-18 04:00:49 +00008115 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008116 return InsertNewInstBefore(Res, *I);
8117}
8118
8119/// @brief Implement the transforms common to all CastInst visitors.
8120Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8121 Value *Src = CI.getOperand(0);
8122
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008123 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8124 // eliminate it now.
8125 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8126 if (Instruction::CastOps opc =
8127 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8128 // The first cast (CSrc) is eliminable so we need to fix up or replace
8129 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008130 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008131 }
8132 }
8133
8134 // If we are casting a select then fold the cast into the select
8135 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8136 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8137 return NV;
8138
8139 // If we are casting a PHI then fold the cast into the PHI
8140 if (isa<PHINode>(Src))
8141 if (Instruction *NV = FoldOpIntoPhi(CI))
8142 return NV;
8143
8144 return 0;
8145}
8146
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008147/// FindElementAtOffset - Given a type and a constant offset, determine whether
8148/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008149/// the specified offset. If so, fill them into NewIndices and return the
8150/// resultant element type, otherwise return null.
8151static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8152 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008153 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008154 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008155 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008156 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008157
8158 // Start with the index over the outer type. Note that the type size
8159 // might be zero (even if the offset isn't zero) if the indexed type
8160 // is something like [0 x {int, int}]
8161 const Type *IntPtrTy = TD->getIntPtrType();
8162 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008163 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008164 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008165 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008166
Chris Lattnerce48c462009-01-11 20:15:20 +00008167 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008168 if (Offset < 0) {
8169 --FirstIdx;
8170 Offset += TySize;
8171 assert(Offset >= 0);
8172 }
8173 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8174 }
8175
Owen Andersoneacb44d2009-07-24 23:12:02 +00008176 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008177
8178 // Index into the types. If we fail, set OrigBase to null.
8179 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008180 // Indexing into tail padding between struct/array elements.
8181 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008182 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008183
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008184 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8185 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008186 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8187 "Offset must stay within the indexed type");
8188
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008189 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008190 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008191
8192 Offset -= SL->getElementOffset(Elt);
8193 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008194 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008195 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008196 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +00008197 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008198 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008199 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008200 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008201 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008202 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008203 }
8204 }
8205
Chris Lattner54dddc72009-01-24 01:00:13 +00008206 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008207}
8208
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008209/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8210Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8211 Value *Src = CI.getOperand(0);
8212
8213 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8214 // If casting the result of a getelementptr instruction with no offset, turn
8215 // this into a cast of the original pointer!
8216 if (GEP->hasAllZeroIndices()) {
8217 // Changing the cast operand is usually not a good idea but it is safe
8218 // here because the pointer operand is being replaced with another
8219 // pointer operand so the opcode doesn't need to change.
8220 AddToWorkList(GEP);
8221 CI.setOperand(0, GEP->getOperand(0));
8222 return &CI;
8223 }
8224
8225 // If the GEP has a single use, and the base pointer is a bitcast, and the
8226 // GEP computes a constant offset, see if we can convert these three
8227 // instructions into fewer. This typically happens with unions and other
8228 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008229 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008230 if (GEP->hasAllConstantIndices()) {
8231 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008232 ConstantInt *OffsetV =
8233 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008234 int64_t Offset = OffsetV->getSExtValue();
8235
8236 // Get the base pointer input of the bitcast, and the type it points to.
8237 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8238 const Type *GEPIdxTy =
8239 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008240 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008241 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008242 // If we were able to index down into an element, create the GEP
8243 // and bitcast the result. This eliminates one bitcast, potentially
8244 // two.
8245 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8246 NewIndices.begin(),
8247 NewIndices.end(), "");
8248 InsertNewInstBefore(NGEP, CI);
8249 NGEP->takeName(GEP);
Dan Gohman17f46f72009-07-28 01:40:03 +00008250 if (cast<GEPOperator>(GEP)->isInBounds())
8251 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008252
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008253 if (isa<BitCastInst>(CI))
8254 return new BitCastInst(NGEP, CI.getType());
8255 assert(isa<PtrToIntInst>(CI));
8256 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008257 }
8258 }
8259 }
8260 }
8261
8262 return commonCastTransforms(CI);
8263}
8264
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008265/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8266/// type like i42. We don't want to introduce operations on random non-legal
8267/// integer types where they don't already exist in the code. In the future,
8268/// we should consider making this based off target-data, so that 32-bit targets
8269/// won't get i64 operations etc.
8270static bool isSafeIntegerType(const Type *Ty) {
8271 switch (Ty->getPrimitiveSizeInBits()) {
8272 case 8:
8273 case 16:
8274 case 32:
8275 case 64:
8276 return true;
8277 default:
8278 return false;
8279 }
8280}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008281
Eli Friedman827e37a2009-07-13 20:58:59 +00008282/// commonIntCastTransforms - This function implements the common transforms
8283/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008284Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8285 if (Instruction *Result = commonCastTransforms(CI))
8286 return Result;
8287
8288 Value *Src = CI.getOperand(0);
8289 const Type *SrcTy = Src->getType();
8290 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008291 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8292 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008293
8294 // See if we can simplify any instructions used by the LHS whose sole
8295 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008296 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008297 return &CI;
8298
8299 // If the source isn't an instruction or has more than one use then we
8300 // can't do anything more.
8301 Instruction *SrcI = dyn_cast<Instruction>(Src);
8302 if (!SrcI || !Src->hasOneUse())
8303 return 0;
8304
8305 // Attempt to propagate the cast into the instruction for int->int casts.
8306 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008307 // Only do this if the dest type is a simple type, don't convert the
8308 // expression tree to something weird like i93 unless the source is also
8309 // strange.
8310 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008311 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8312 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008313 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008314 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008315 // eliminates the cast, so it is always a win. If this is a zero-extension,
8316 // we need to do an AND to maintain the clear top-part of the computation,
8317 // so we require that the input have eliminated at least one cast. If this
8318 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008319 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008320 bool DoXForm = false;
8321 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008322 switch (CI.getOpcode()) {
8323 default:
8324 // All the others use floating point so we shouldn't actually
8325 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008326 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008327 case Instruction::Trunc:
8328 DoXForm = true;
8329 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008330 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008331 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008332 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008333 // If it's unnecessary to issue an AND to clear the high bits, it's
8334 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008335 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008336 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8337 if (MaskedValueIsZero(TryRes, Mask))
8338 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008339
8340 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008341 if (TryI->use_empty())
8342 EraseInstFromFunction(*TryI);
8343 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008344 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008345 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008346 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008347 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008348 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008349 // If we do not have to emit the truncate + sext pair, then it's always
8350 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008351 //
8352 // It's not safe to eliminate the trunc + sext pair if one of the
8353 // eliminated cast is a truncate. e.g.
8354 // t2 = trunc i32 t1 to i16
8355 // t3 = sext i16 t2 to i32
8356 // !=
8357 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008358 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008359 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8360 if (NumSignBits > (DestBitSize - SrcBitSize))
8361 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008362
8363 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008364 if (TryI->use_empty())
8365 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008366 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008367 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008368 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008369 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008370
8371 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008372 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8373 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008374 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8375 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008376 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008377 // Just replace this cast with the result.
8378 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008379
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008380 assert(Res->getType() == DestTy);
8381 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008382 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008383 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008384 // Just replace this cast with the result.
8385 return ReplaceInstUsesWith(CI, Res);
8386 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008387 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008388
8389 // If the high bits are already zero, just replace this cast with the
8390 // result.
8391 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8392 if (MaskedValueIsZero(Res, Mask))
8393 return ReplaceInstUsesWith(CI, Res);
8394
8395 // We need to emit an AND to clear the high bits.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008396 Constant *C = ConstantInt::get(*Context,
8397 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008398 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008399 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008400 case Instruction::SExt: {
8401 // If the high bits are already filled with sign bit, just replace this
8402 // cast with the result.
8403 unsigned NumSignBits = ComputeNumSignBits(Res);
8404 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008405 return ReplaceInstUsesWith(CI, Res);
8406
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008407 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008408 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008409 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8410 CI), DestTy);
8411 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008412 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 }
8414 }
8415
8416 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8417 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8418
8419 switch (SrcI->getOpcode()) {
8420 case Instruction::Add:
8421 case Instruction::Mul:
8422 case Instruction::And:
8423 case Instruction::Or:
8424 case Instruction::Xor:
8425 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008426 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8427 // Don't insert two casts unless at least one can be eliminated.
8428 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008429 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008430 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8431 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008432 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8434 }
8435 }
8436
8437 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8438 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8439 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson4f720fa2009-07-31 17:39:07 +00008440 Op1 == ConstantInt::getTrue(*Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008441 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008442 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008443 return BinaryOperator::CreateXor(New,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008444 ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008445 }
8446 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008447
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008448 case Instruction::Shl: {
8449 // Canonicalize trunc inside shl, if we can.
8450 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8451 if (CI && DestBitSize < SrcBitSize &&
8452 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8453 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8454 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008455 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008456 }
8457 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008458 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008459 }
8460 return 0;
8461}
8462
8463Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8464 if (Instruction *Result = commonIntCastTransforms(CI))
8465 return Result;
8466
8467 Value *Src = CI.getOperand(0);
8468 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008469 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8470 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008471
8472 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008473 if (DestBitWidth == 1) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008474 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner32177f82009-03-24 18:15:30 +00008475 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersonaac28372009-07-31 20:28:14 +00008476 Value *Zero = Constant::getNullValue(Src->getType());
Owen Anderson6601fcd2009-07-09 23:48:35 +00008477 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008478 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008479
Chris Lattner32177f82009-03-24 18:15:30 +00008480 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8481 ConstantInt *ShAmtV = 0;
8482 Value *ShiftOp = 0;
8483 if (Src->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00008484 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner32177f82009-03-24 18:15:30 +00008485 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8486
8487 // Get a mask for the bits shifting in.
8488 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8489 if (MaskedValueIsZero(ShiftOp, Mask)) {
8490 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersonaac28372009-07-31 20:28:14 +00008491 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008492
8493 // Okay, we can shrink this. Truncate the input, then return a new
8494 // shift.
8495 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Anderson02b48c32009-07-29 18:55:55 +00008496 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008497 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008498 }
8499 }
8500
8501 return 0;
8502}
8503
Evan Chenge3779cf2008-03-24 00:21:34 +00008504/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8505/// in order to eliminate the icmp.
8506Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8507 bool DoXform) {
8508 // If we are just checking for a icmp eq of a single bit and zext'ing it
8509 // to an integer, then shift the bit to the appropriate place and then
8510 // cast to integer to avoid the comparison.
8511 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8512 const APInt &Op1CV = Op1C->getValue();
8513
8514 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8515 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8516 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8517 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8518 if (!DoXform) return ICI;
8519
8520 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00008521 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008522 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008523 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008524 In->getName()+".lobit"),
8525 CI);
8526 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008527 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008528 false/*ZExt*/, "tmp", &CI);
8529
8530 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00008531 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008532 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008533 In->getName()+".not"),
8534 CI);
8535 }
8536
8537 return ReplaceInstUsesWith(CI, In);
8538 }
8539
8540
8541
8542 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8543 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8544 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8545 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8546 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8547 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8548 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8549 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8550 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8551 // This only works for EQ and NE
8552 ICI->isEquality()) {
8553 // If Op1C some other power of two, convert:
8554 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8555 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8556 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8557 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8558
8559 APInt KnownZeroMask(~KnownZero);
8560 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8561 if (!DoXform) return ICI;
8562
8563 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8564 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8565 // (X&4) == 2 --> false
8566 // (X&4) != 2 --> true
Owen Andersoneacb44d2009-07-24 23:12:02 +00008567 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
Owen Anderson02b48c32009-07-29 18:55:55 +00008568 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008569 return ReplaceInstUsesWith(CI, Res);
8570 }
8571
8572 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8573 Value *In = ICI->getOperand(0);
8574 if (ShiftAmt) {
8575 // Perform a logical shr by shiftamt.
8576 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008577 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008578 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chenge3779cf2008-03-24 00:21:34 +00008579 In->getName()+".lobit"), CI);
8580 }
8581
8582 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneacb44d2009-07-24 23:12:02 +00008583 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008584 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008585 InsertNewInstBefore(cast<Instruction>(In), CI);
8586 }
8587
8588 if (CI.getType() == In->getType())
8589 return ReplaceInstUsesWith(CI, In);
8590 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008591 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008592 }
8593 }
8594 }
8595
8596 return 0;
8597}
8598
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008599Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8600 // If one of the common conversion will work ..
8601 if (Instruction *Result = commonIntCastTransforms(CI))
8602 return Result;
8603
8604 Value *Src = CI.getOperand(0);
8605
Chris Lattner215d56e2009-02-17 20:47:23 +00008606 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8607 // types and if the sizes are just right we can convert this into a logical
8608 // 'and' which will be much cheaper than the pair of casts.
8609 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8610 // Get the sizes of the types involved. We know that the intermediate type
8611 // will be smaller than A or C, but don't know the relation between A and C.
8612 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008613 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8614 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8615 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008616 // If we're actually extending zero bits, then if
8617 // SrcSize < DstSize: zext(a & mask)
8618 // SrcSize == DstSize: a & mask
8619 // SrcSize > DstSize: trunc(a) & mask
8620 if (SrcSize < DstSize) {
8621 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008622 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008623 Instruction *And =
8624 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8625 InsertNewInstBefore(And, CI);
8626 return new ZExtInst(And, CI.getType());
8627 } else if (SrcSize == DstSize) {
8628 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneacb44d2009-07-24 23:12:02 +00008629 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008630 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008631 } else if (SrcSize > DstSize) {
8632 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8633 InsertNewInstBefore(Trunc, CI);
8634 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008635 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneacb44d2009-07-24 23:12:02 +00008636 ConstantInt::get(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008637 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008638 }
8639 }
8640
Evan Chenge3779cf2008-03-24 00:21:34 +00008641 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8642 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008643
Evan Chenge3779cf2008-03-24 00:21:34 +00008644 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8645 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8646 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8647 // of the (zext icmp) will be transformed.
8648 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8649 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8650 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8651 (transformZExtICmp(LHS, CI, false) ||
8652 transformZExtICmp(RHS, CI, false))) {
8653 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8654 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008655 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008656 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008657 }
8658
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008659 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008660 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8661 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8662 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8663 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008664 if (TI0->getType() == CI.getType())
8665 return
8666 BinaryOperator::CreateAnd(TI0,
Owen Anderson02b48c32009-07-29 18:55:55 +00008667 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008668 }
8669
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008670 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8671 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8672 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8673 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8674 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8675 And->getOperand(1) == C)
8676 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8677 Value *TI0 = TI->getOperand(0);
8678 if (TI0->getType() == CI.getType()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00008679 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008680 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8681 InsertNewInstBefore(NewAnd, *And);
8682 return BinaryOperator::CreateXor(NewAnd, ZC);
8683 }
8684 }
8685
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008686 return 0;
8687}
8688
8689Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8690 if (Instruction *I = commonIntCastTransforms(CI))
8691 return I;
8692
8693 Value *Src = CI.getOperand(0);
8694
Dan Gohman35b76162008-10-30 20:40:10 +00008695 // Canonicalize sign-extend from i1 to a select.
8696 if (Src->getType() == Type::Int1Ty)
8697 return SelectInst::Create(Src,
Owen Andersonaac28372009-07-31 20:28:14 +00008698 Constant::getAllOnesValue(CI.getType()),
8699 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008700
8701 // See if the value being truncated is already sign extended. If so, just
8702 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008703 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008704 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008705 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8706 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8707 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008708 unsigned NumSignBits = ComputeNumSignBits(Op);
8709
8710 if (OpBits == DestBits) {
8711 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8712 // bits, it is already ready.
8713 if (NumSignBits > DestBits-MidBits)
8714 return ReplaceInstUsesWith(CI, Op);
8715 } else if (OpBits < DestBits) {
8716 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8717 // bits, just sext from i32.
8718 if (NumSignBits > OpBits-MidBits)
8719 return new SExtInst(Op, CI.getType(), "tmp");
8720 } else {
8721 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8722 // bits, just truncate to i32.
8723 if (NumSignBits > OpBits-MidBits)
8724 return new TruncInst(Op, CI.getType(), "tmp");
8725 }
8726 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008727
8728 // If the input is a shl/ashr pair of a same constant, then this is a sign
8729 // extension from a smaller value. If we could trust arbitrary bitwidth
8730 // integers, we could turn this into a truncate to the smaller bit and then
8731 // use a sext for the whole extension. Since we don't, look deeper and check
8732 // for a truncate. If the source and dest are the same type, eliminate the
8733 // trunc and extend and just do shifts. For example, turn:
8734 // %a = trunc i32 %i to i8
8735 // %b = shl i8 %a, 6
8736 // %c = ashr i8 %b, 6
8737 // %d = sext i8 %c to i32
8738 // into:
8739 // %a = shl i32 %i, 30
8740 // %d = ashr i32 %a, 30
8741 Value *A = 0;
8742 ConstantInt *BA = 0, *CA = 0;
8743 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersona21eb582009-07-10 17:35:01 +00008744 m_ConstantInt(CA)), *Context) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008745 BA == CA && isa<TruncInst>(A)) {
8746 Value *I = cast<TruncInst>(A)->getOperand(0);
8747 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008748 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8749 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008750 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneacb44d2009-07-24 23:12:02 +00008751 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner8a2d0592008-08-06 07:35:52 +00008752 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8753 CI.getName()), CI);
8754 return BinaryOperator::CreateAShr(I, ShAmtV);
8755 }
8756 }
8757
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008758 return 0;
8759}
8760
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008761/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8762/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008763static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008764 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008765 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008766 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008767 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8768 if (!losesInfo)
Owen Andersond363a0e2009-07-27 20:59:43 +00008769 return ConstantFP::get(*Context, F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008770 return 0;
8771}
8772
8773/// LookThroughFPExtensions - If this is an fp extension instruction, look
8774/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008775static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008776 if (Instruction *I = dyn_cast<Instruction>(V))
8777 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008778 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008779
8780 // If this value is a constant, return the constant in the smallest FP type
8781 // that can accurately represent it. This allows us to turn
8782 // (float)((double)X+2.0) into x+2.0f.
8783 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8784 if (CFP->getType() == Type::PPC_FP128Ty)
8785 return V; // No constant folding of this.
8786 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008787 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008788 return V;
8789 if (CFP->getType() == Type::DoubleTy)
8790 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008791 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008792 return V;
8793 // Don't try to shrink to various long double types.
8794 }
8795
8796 return V;
8797}
8798
8799Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8800 if (Instruction *I = commonCastTransforms(CI))
8801 return I;
8802
Dan Gohman7ce405e2009-06-04 22:49:04 +00008803 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008804 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008805 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008806 // many builtins (sqrt, etc).
8807 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8808 if (OpI && OpI->hasOneUse()) {
8809 switch (OpI->getOpcode()) {
8810 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008811 case Instruction::FAdd:
8812 case Instruction::FSub:
8813 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008814 case Instruction::FDiv:
8815 case Instruction::FRem:
8816 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008817 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8818 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008819 if (LHSTrunc->getType() != SrcTy &&
8820 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008821 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008822 // If the source types were both smaller than the destination type of
8823 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008824 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8825 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008826 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8827 CI.getType(), CI);
8828 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8829 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008830 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008831 }
8832 }
8833 break;
8834 }
8835 }
8836 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008837}
8838
8839Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8840 return commonCastTransforms(CI);
8841}
8842
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008843Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008844 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8845 if (OpI == 0)
8846 return commonCastTransforms(FI);
8847
8848 // fptoui(uitofp(X)) --> X
8849 // fptoui(sitofp(X)) --> X
8850 // This is safe if the intermediate type has enough bits in its mantissa to
8851 // accurately represent all values of X. For example, do not do this with
8852 // i64->float->i64. This is also safe for sitofp case, because any negative
8853 // 'X' value would cause an undefined result for the fptoui.
8854 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8855 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008856 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008857 OpI->getType()->getFPMantissaWidth())
8858 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008859
8860 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008861}
8862
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008863Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008864 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8865 if (OpI == 0)
8866 return commonCastTransforms(FI);
8867
8868 // fptosi(sitofp(X)) --> X
8869 // fptosi(uitofp(X)) --> X
8870 // This is safe if the intermediate type has enough bits in its mantissa to
8871 // accurately represent all values of X. For example, do not do this with
8872 // i64->float->i64. This is also safe for sitofp case, because any negative
8873 // 'X' value would cause an undefined result for the fptoui.
8874 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8875 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008876 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008877 OpI->getType()->getFPMantissaWidth())
8878 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008879
8880 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008881}
8882
8883Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8884 return commonCastTransforms(CI);
8885}
8886
8887Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8888 return commonCastTransforms(CI);
8889}
8890
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008891Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8892 // If the destination integer type is smaller than the intptr_t type for
8893 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8894 // trunc to be exposed to other transforms. Don't do this for extending
8895 // ptrtoint's, because we don't know if the target sign or zero extends its
8896 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008897 if (TD &&
8898 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008899 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8900 TD->getIntPtrType(),
8901 "tmp"), CI);
8902 return new TruncInst(P, CI.getType());
8903 }
8904
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008905 return commonPointerCastTransforms(CI);
8906}
8907
Chris Lattner7c1626482008-01-08 07:23:51 +00008908Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008909 // If the source integer type is larger than the intptr_t type for
8910 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8911 // allows the trunc to be exposed to other transforms. Don't do this for
8912 // extending inttoptr's, because we don't know if the target sign or zero
8913 // extends to pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008914 if (TD &&
8915 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008916 TD->getPointerSizeInBits()) {
8917 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8918 TD->getIntPtrType(),
8919 "tmp"), CI);
8920 return new IntToPtrInst(P, CI.getType());
8921 }
8922
Chris Lattner7c1626482008-01-08 07:23:51 +00008923 if (Instruction *I = commonCastTransforms(CI))
8924 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008925
Chris Lattner7c1626482008-01-08 07:23:51 +00008926 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008927}
8928
8929Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8930 // If the operands are integer typed then apply the integer transforms,
8931 // otherwise just apply the common ones.
8932 Value *Src = CI.getOperand(0);
8933 const Type *SrcTy = Src->getType();
8934 const Type *DestTy = CI.getType();
8935
Eli Friedman5013d3f2009-07-13 20:53:00 +00008936 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008937 if (Instruction *I = commonPointerCastTransforms(CI))
8938 return I;
8939 } else {
8940 if (Instruction *Result = commonCastTransforms(CI))
8941 return Result;
8942 }
8943
8944
8945 // Get rid of casts from one type to the same type. These are useless and can
8946 // be replaced by the operand.
8947 if (DestTy == Src->getType())
8948 return ReplaceInstUsesWith(CI, Src);
8949
8950 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8951 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8952 const Type *DstElTy = DstPTy->getElementType();
8953 const Type *SrcElTy = SrcPTy->getElementType();
8954
Nate Begemandf5b3612008-03-31 00:22:16 +00008955 // If the address spaces don't match, don't eliminate the bitcast, which is
8956 // required for changing types.
8957 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8958 return 0;
8959
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008960 // If we are casting a malloc or alloca to a pointer to a type of the same
8961 // size, rewrite the allocation instruction to allocate the "right" type.
8962 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8963 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8964 return V;
8965
8966 // If the source and destination are pointers, and this cast is equivalent
8967 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8968 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersonaac28372009-07-31 20:28:14 +00008969 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008970 unsigned NumZeros = 0;
8971 while (SrcElTy != DstElTy &&
8972 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8973 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8974 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8975 ++NumZeros;
8976 }
8977
8978 // If we found a path from the src to dest, create the getelementptr now.
8979 if (SrcElTy == DstElTy) {
8980 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohman17f46f72009-07-28 01:40:03 +00008981 Instruction *GEP = GetElementPtrInst::Create(Src,
8982 Idxs.begin(), Idxs.end(), "",
8983 ((Instruction*) NULL));
8984 cast<GEPOperator>(GEP)->setIsInBounds(true);
8985 return GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008986 }
8987 }
8988
Eli Friedman1d31dee2009-07-18 23:06:53 +00008989 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8990 if (DestVTy->getNumElements() == 1) {
8991 if (!isa<VectorType>(SrcTy)) {
8992 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8993 DestVTy->getElementType(), CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00008994 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Andersonaac28372009-07-31 20:28:14 +00008995 Constant::getNullValue(Type::Int32Ty));
Eli Friedman1d31dee2009-07-18 23:06:53 +00008996 }
8997 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8998 }
8999 }
9000
9001 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9002 if (SrcVTy->getNumElements() == 1) {
9003 if (!isa<VectorType>(DestTy)) {
9004 Instruction *Elem =
Owen Andersonaac28372009-07-31 20:28:14 +00009005 ExtractElementInst::Create(Src, Constant::getNullValue(Type::Int32Ty));
Eli Friedman1d31dee2009-07-18 23:06:53 +00009006 InsertNewInstBefore(Elem, CI);
9007 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9008 }
9009 }
9010 }
9011
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009012 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9013 if (SVI->hasOneUse()) {
9014 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9015 // a bitconvert to a vector with the same # elts.
9016 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009017 cast<VectorType>(DestTy)->getNumElements() ==
9018 SVI->getType()->getNumElements() &&
9019 SVI->getType()->getNumElements() ==
9020 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009021 CastInst *Tmp;
9022 // If either of the operands is a cast from CI.getType(), then
9023 // evaluating the shuffle in the casted destination's type will allow
9024 // us to eliminate at least one cast.
9025 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9026 Tmp->getOperand(0)->getType() == DestTy) ||
9027 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9028 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00009029 Value *LHS = InsertCastBefore(Instruction::BitCast,
9030 SVI->getOperand(0), DestTy, CI);
9031 Value *RHS = InsertCastBefore(Instruction::BitCast,
9032 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009033 // Return a new shuffle vector. Use the same element ID's, as we
9034 // know the vector types match #elts.
9035 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9036 }
9037 }
9038 }
9039 }
9040 return 0;
9041}
9042
9043/// GetSelectFoldableOperands - We want to turn code that looks like this:
9044/// %C = or %A, %B
9045/// %D = select %cond, %C, %A
9046/// into:
9047/// %C = select %cond, %B, 0
9048/// %D = or %A, %C
9049///
9050/// Assuming that the specified instruction is an operand to the select, return
9051/// a bitmask indicating which operands of this instruction are foldable if they
9052/// equal the other incoming value of the select.
9053///
9054static unsigned GetSelectFoldableOperands(Instruction *I) {
9055 switch (I->getOpcode()) {
9056 case Instruction::Add:
9057 case Instruction::Mul:
9058 case Instruction::And:
9059 case Instruction::Or:
9060 case Instruction::Xor:
9061 return 3; // Can fold through either operand.
9062 case Instruction::Sub: // Can only fold on the amount subtracted.
9063 case Instruction::Shl: // Can only fold on the shift amount.
9064 case Instruction::LShr:
9065 case Instruction::AShr:
9066 return 1;
9067 default:
9068 return 0; // Cannot fold
9069 }
9070}
9071
9072/// GetSelectFoldableConstant - For the same transformation as the previous
9073/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009074static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009075 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009076 switch (I->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00009077 default: llvm_unreachable("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009078 case Instruction::Add:
9079 case Instruction::Sub:
9080 case Instruction::Or:
9081 case Instruction::Xor:
9082 case Instruction::Shl:
9083 case Instruction::LShr:
9084 case Instruction::AShr:
Owen Andersonaac28372009-07-31 20:28:14 +00009085 return Constant::getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009086 case Instruction::And:
Owen Andersonaac28372009-07-31 20:28:14 +00009087 return Constant::getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009088 case Instruction::Mul:
Owen Andersoneacb44d2009-07-24 23:12:02 +00009089 return ConstantInt::get(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009090 }
9091}
9092
9093/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9094/// have the same opcode and only one use each. Try to simplify this.
9095Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9096 Instruction *FI) {
9097 if (TI->getNumOperands() == 1) {
9098 // If this is a non-volatile load or a cast from the same type,
9099 // merge.
9100 if (TI->isCast()) {
9101 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9102 return 0;
9103 } else {
9104 return 0; // unknown unary op.
9105 }
9106
9107 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009108 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christopher3e7381f2009-07-25 02:45:27 +00009109 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009110 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009111 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009112 TI->getType());
9113 }
9114
9115 // Only handle binary operators here.
9116 if (!isa<BinaryOperator>(TI))
9117 return 0;
9118
9119 // Figure out if the operations have any operands in common.
9120 Value *MatchOp, *OtherOpT, *OtherOpF;
9121 bool MatchIsOpZero;
9122 if (TI->getOperand(0) == FI->getOperand(0)) {
9123 MatchOp = TI->getOperand(0);
9124 OtherOpT = TI->getOperand(1);
9125 OtherOpF = FI->getOperand(1);
9126 MatchIsOpZero = true;
9127 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9128 MatchOp = TI->getOperand(1);
9129 OtherOpT = TI->getOperand(0);
9130 OtherOpF = FI->getOperand(0);
9131 MatchIsOpZero = false;
9132 } else if (!TI->isCommutative()) {
9133 return 0;
9134 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9135 MatchOp = TI->getOperand(0);
9136 OtherOpT = TI->getOperand(1);
9137 OtherOpF = FI->getOperand(0);
9138 MatchIsOpZero = true;
9139 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9140 MatchOp = TI->getOperand(1);
9141 OtherOpT = TI->getOperand(0);
9142 OtherOpF = FI->getOperand(1);
9143 MatchIsOpZero = true;
9144 } else {
9145 return 0;
9146 }
9147
9148 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009149 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9150 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009151 InsertNewInstBefore(NewSI, SI);
9152
9153 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9154 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009155 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009156 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009157 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009158 }
Edwin Törökbd448e32009-07-14 16:55:14 +00009159 llvm_unreachable("Shouldn't get here");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009160 return 0;
9161}
9162
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009163static bool isSelect01(Constant *C1, Constant *C2) {
9164 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9165 if (!C1I)
9166 return false;
9167 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9168 if (!C2I)
9169 return false;
9170 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9171}
9172
9173/// FoldSelectIntoOp - Try fold the select into one of the operands to
9174/// facilitate further optimization.
9175Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9176 Value *FalseVal) {
9177 // See the comment above GetSelectFoldableOperands for a description of the
9178 // transformation we are doing here.
9179 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9180 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9181 !isa<Constant>(FalseVal)) {
9182 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9183 unsigned OpToFold = 0;
9184 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9185 OpToFold = 1;
9186 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9187 OpToFold = 2;
9188 }
9189
9190 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009191 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009192 Value *OOp = TVI->getOperand(2-OpToFold);
9193 // Avoid creating select between 2 constants unless it's selecting
9194 // between 0 and 1.
9195 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9196 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9197 InsertNewInstBefore(NewSel, SI);
9198 NewSel->takeName(TVI);
9199 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9200 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009201 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009202 }
9203 }
9204 }
9205 }
9206 }
9207
9208 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9209 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9210 !isa<Constant>(TrueVal)) {
9211 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9212 unsigned OpToFold = 0;
9213 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9214 OpToFold = 1;
9215 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9216 OpToFold = 2;
9217 }
9218
9219 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009220 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009221 Value *OOp = FVI->getOperand(2-OpToFold);
9222 // Avoid creating select between 2 constants unless it's selecting
9223 // between 0 and 1.
9224 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9225 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9226 InsertNewInstBefore(NewSel, SI);
9227 NewSel->takeName(FVI);
9228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9229 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Edwin Törökbd448e32009-07-14 16:55:14 +00009230 llvm_unreachable("Unknown instruction!!");
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009231 }
9232 }
9233 }
9234 }
9235 }
9236
9237 return 0;
9238}
9239
Dan Gohman58c09632008-09-16 18:46:06 +00009240/// visitSelectInstWithICmp - Visit a SelectInst that has an
9241/// ICmpInst as its first operand.
9242///
9243Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9244 ICmpInst *ICI) {
9245 bool Changed = false;
9246 ICmpInst::Predicate Pred = ICI->getPredicate();
9247 Value *CmpLHS = ICI->getOperand(0);
9248 Value *CmpRHS = ICI->getOperand(1);
9249 Value *TrueVal = SI.getTrueValue();
9250 Value *FalseVal = SI.getFalseValue();
9251
9252 // Check cases where the comparison is with a constant that
9253 // can be adjusted to fit the min/max idiom. We may edit ICI in
9254 // place here, so make sure the select is the only user.
9255 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009256 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009257 switch (Pred) {
9258 default: break;
9259 case ICmpInst::ICMP_ULT:
9260 case ICmpInst::ICMP_SLT: {
9261 // X < MIN ? T : F --> F
9262 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9263 return ReplaceInstUsesWith(SI, FalseVal);
9264 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Anderson24be4c12009-07-03 00:17:18 +00009265 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman58c09632008-09-16 18:46:06 +00009266 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9267 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9268 Pred = ICmpInst::getSwappedPredicate(Pred);
9269 CmpRHS = AdjustedRHS;
9270 std::swap(FalseVal, TrueVal);
9271 ICI->setPredicate(Pred);
9272 ICI->setOperand(1, CmpRHS);
9273 SI.setOperand(1, TrueVal);
9274 SI.setOperand(2, FalseVal);
9275 Changed = true;
9276 }
9277 break;
9278 }
9279 case ICmpInst::ICMP_UGT:
9280 case ICmpInst::ICMP_SGT: {
9281 // X > MAX ? T : F --> F
9282 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9283 return ReplaceInstUsesWith(SI, FalseVal);
9284 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Anderson24be4c12009-07-03 00:17:18 +00009285 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman58c09632008-09-16 18:46:06 +00009286 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9287 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9288 Pred = ICmpInst::getSwappedPredicate(Pred);
9289 CmpRHS = AdjustedRHS;
9290 std::swap(FalseVal, TrueVal);
9291 ICI->setPredicate(Pred);
9292 ICI->setOperand(1, CmpRHS);
9293 SI.setOperand(1, TrueVal);
9294 SI.setOperand(2, FalseVal);
9295 Changed = true;
9296 }
9297 break;
9298 }
9299 }
9300
Dan Gohman35b76162008-10-30 20:40:10 +00009301 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9302 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009303 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersona21eb582009-07-10 17:35:01 +00009304 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9305 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattner3b874082008-11-16 05:38:51 +00009306 Pred = ICI->getPredicate();
Owen Andersona21eb582009-07-10 17:35:01 +00009307 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9308 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattner3b874082008-11-16 05:38:51 +00009309 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9310
Dan Gohman35b76162008-10-30 20:40:10 +00009311 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9312 // If we are just checking for a icmp eq of a single bit and zext'ing it
9313 // to an integer, then shift the bit to the appropriate place and then
9314 // cast to integer to avoid the comparison.
9315 const APInt &Op1CV = CI->getValue();
9316
9317 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9318 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9319 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009320 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009321 Value *In = ICI->getOperand(0);
Owen Andersoneacb44d2009-07-24 23:12:02 +00009322 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009323 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009324 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christopher3e7381f2009-07-25 02:45:27 +00009325 In->getName()+".lobit"),
Dan Gohman35b76162008-10-30 20:40:10 +00009326 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009327 if (In->getType() != SI.getType())
9328 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009329 true/*SExt*/, "tmp", ICI);
9330
9331 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson035d41d2009-07-13 20:58:05 +00009332 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman35b76162008-10-30 20:40:10 +00009333 In->getName()+".not"), *ICI);
9334
9335 return ReplaceInstUsesWith(SI, In);
9336 }
9337 }
9338 }
9339
Dan Gohman58c09632008-09-16 18:46:06 +00009340 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9341 // Transform (X == Y) ? X : Y -> Y
9342 if (Pred == ICmpInst::ICMP_EQ)
9343 return ReplaceInstUsesWith(SI, FalseVal);
9344 // Transform (X != Y) ? X : Y -> X
9345 if (Pred == ICmpInst::ICMP_NE)
9346 return ReplaceInstUsesWith(SI, TrueVal);
9347 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9348
9349 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9350 // Transform (X == Y) ? Y : X -> X
9351 if (Pred == ICmpInst::ICMP_EQ)
9352 return ReplaceInstUsesWith(SI, FalseVal);
9353 // Transform (X != Y) ? Y : X -> Y
9354 if (Pred == ICmpInst::ICMP_NE)
9355 return ReplaceInstUsesWith(SI, TrueVal);
9356 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9357 }
9358
9359 /// NOTE: if we wanted to, this is where to detect integer ABS
9360
9361 return Changed ? &SI : 0;
9362}
9363
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009364Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9365 Value *CondVal = SI.getCondition();
9366 Value *TrueVal = SI.getTrueValue();
9367 Value *FalseVal = SI.getFalseValue();
9368
9369 // select true, X, Y -> X
9370 // select false, X, Y -> Y
9371 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9372 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9373
9374 // select C, X, X -> X
9375 if (TrueVal == FalseVal)
9376 return ReplaceInstUsesWith(SI, TrueVal);
9377
9378 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9379 return ReplaceInstUsesWith(SI, FalseVal);
9380 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9381 return ReplaceInstUsesWith(SI, TrueVal);
9382 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9383 if (isa<Constant>(TrueVal))
9384 return ReplaceInstUsesWith(SI, TrueVal);
9385 else
9386 return ReplaceInstUsesWith(SI, FalseVal);
9387 }
9388
9389 if (SI.getType() == Type::Int1Ty) {
9390 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9391 if (C->getZExtValue()) {
9392 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009393 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009394 } else {
9395 // Change: A = select B, false, C --> A = and !B, C
9396 Value *NotCond =
Owen Anderson035d41d2009-07-13 20:58:05 +00009397 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009398 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009399 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009400 }
9401 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9402 if (C->getZExtValue() == false) {
9403 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009404 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009405 } else {
9406 // Change: A = select B, C, true --> A = or !B, C
9407 Value *NotCond =
Owen Anderson035d41d2009-07-13 20:58:05 +00009408 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009409 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009410 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009411 }
9412 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009413
9414 // select a, b, a -> a&b
9415 // select a, a, b -> a|b
9416 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009417 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009418 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009419 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009420 }
9421
9422 // Selecting between two integer constants?
9423 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9424 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9425 // select C, 1, 0 -> zext C to int
9426 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009427 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009428 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9429 // select C, 0, 1 -> zext !C to int
9430 Value *NotCond =
Owen Anderson035d41d2009-07-13 20:58:05 +00009431 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009432 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009433 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009434 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435
9436 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009437 // If one of the constants is zero (we know they can't both be) and we
9438 // have an icmp instruction with zero, and we have an 'and' with the
9439 // non-constant value, eliminate this whole mess. This corresponds to
9440 // cases like this: ((X & 27) ? 27 : 0)
9441 if (TrueValC->isZero() || FalseValC->isZero())
9442 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9443 cast<Constant>(IC->getOperand(1))->isNullValue())
9444 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9445 if (ICA->getOpcode() == Instruction::And &&
9446 isa<ConstantInt>(ICA->getOperand(1)) &&
9447 (ICA->getOperand(1) == TrueValC ||
9448 ICA->getOperand(1) == FalseValC) &&
9449 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9450 // Okay, now we know that everything is set up, we just don't
9451 // know whether we have a icmp_ne or icmp_eq and whether the
9452 // true or false val is the zero.
9453 bool ShouldNotVal = !TrueValC->isZero();
9454 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9455 Value *V = ICA;
9456 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009457 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009458 Instruction::Xor, V, ICA->getOperand(1)), SI);
9459 return ReplaceInstUsesWith(SI, V);
9460 }
9461 }
9462 }
9463
9464 // See if we are selecting two values based on a comparison of the two values.
9465 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9466 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9467 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009468 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9469 // This is not safe in general for floating point:
9470 // consider X== -0, Y== +0.
9471 // It becomes safe if either operand is a nonzero constant.
9472 ConstantFP *CFPt, *CFPf;
9473 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9474 !CFPt->getValueAPF().isZero()) ||
9475 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9476 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009477 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009478 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009479 // Transform (X != Y) ? X : Y -> X
9480 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9481 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009482 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009483
9484 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9485 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009486 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9487 // This is not safe in general for floating point:
9488 // consider X== -0, Y== +0.
9489 // It becomes safe if either operand is a nonzero constant.
9490 ConstantFP *CFPt, *CFPf;
9491 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9492 !CFPt->getValueAPF().isZero()) ||
9493 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9494 !CFPf->getValueAPF().isZero()))
9495 return ReplaceInstUsesWith(SI, FalseVal);
9496 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009497 // Transform (X != Y) ? Y : X -> Y
9498 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9499 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009500 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009501 }
Dan Gohman58c09632008-09-16 18:46:06 +00009502 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009503 }
9504
9505 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009506 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9507 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9508 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009509
9510 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9511 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9512 if (TI->hasOneUse() && FI->hasOneUse()) {
9513 Instruction *AddOp = 0, *SubOp = 0;
9514
9515 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9516 if (TI->getOpcode() == FI->getOpcode())
9517 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9518 return IV;
9519
9520 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9521 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009522 if ((TI->getOpcode() == Instruction::Sub &&
9523 FI->getOpcode() == Instruction::Add) ||
9524 (TI->getOpcode() == Instruction::FSub &&
9525 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009526 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009527 } else if ((FI->getOpcode() == Instruction::Sub &&
9528 TI->getOpcode() == Instruction::Add) ||
9529 (FI->getOpcode() == Instruction::FSub &&
9530 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009531 AddOp = TI; SubOp = FI;
9532 }
9533
9534 if (AddOp) {
9535 Value *OtherAddOp = 0;
9536 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9537 OtherAddOp = AddOp->getOperand(1);
9538 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9539 OtherAddOp = AddOp->getOperand(0);
9540 }
9541
9542 if (OtherAddOp) {
9543 // So at this point we know we have (Y -> OtherAddOp):
9544 // select C, (add X, Y), (sub X, Z)
9545 Value *NegVal; // Compute -Z
9546 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +00009547 NegVal = ConstantExpr::getNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548 } else {
9549 NegVal = InsertNewInstBefore(
Owen Anderson15b39322009-07-13 04:09:18 +00009550 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9551 "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009552 }
9553
9554 Value *NewTrueOp = OtherAddOp;
9555 Value *NewFalseOp = NegVal;
9556 if (AddOp != TI)
9557 std::swap(NewTrueOp, NewFalseOp);
9558 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009559 SelectInst::Create(CondVal, NewTrueOp,
9560 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009561
9562 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009563 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009564 }
9565 }
9566 }
9567
9568 // See if we can fold the select into one of our operands.
9569 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009570 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9571 if (FoldI)
9572 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009573 }
9574
9575 if (BinaryOperator::isNot(CondVal)) {
9576 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9577 SI.setOperand(1, FalseVal);
9578 SI.setOperand(2, TrueVal);
9579 return &SI;
9580 }
9581
9582 return 0;
9583}
9584
Dan Gohman2d648bb2008-04-10 18:43:06 +00009585/// EnforceKnownAlignment - If the specified pointer points to an object that
9586/// we control, modify the object's alignment to PrefAlign. This isn't
9587/// often possible though. If alignment is important, a more reliable approach
9588/// is to simply align all global variables and allocation instructions to
9589/// their preferred alignment from the beginning.
9590///
9591static unsigned EnforceKnownAlignment(Value *V,
9592 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009593
Dan Gohman2d648bb2008-04-10 18:43:06 +00009594 User *U = dyn_cast<User>(V);
9595 if (!U) return Align;
9596
Dan Gohman9545fb02009-07-17 20:47:02 +00009597 switch (Operator::getOpcode(U)) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009598 default: break;
9599 case Instruction::BitCast:
9600 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9601 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009602 // If all indexes are zero, it is just the alignment of the base pointer.
9603 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009604 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009605 if (!isa<Constant>(*i) ||
9606 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009607 AllZeroOperands = false;
9608 break;
9609 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009610
9611 if (AllZeroOperands) {
9612 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009613 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009614 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009615 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009616 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009617 }
9618
9619 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9620 // If there is a large requested alignment and we can, bump up the alignment
9621 // of the global.
9622 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009623 if (GV->getAlignment() >= PrefAlign)
9624 Align = GV->getAlignment();
9625 else {
9626 GV->setAlignment(PrefAlign);
9627 Align = PrefAlign;
9628 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009629 }
9630 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9631 // If there is a requested alignment and if this is an alloca, round up. We
9632 // don't do this for malloc, because some systems can't respect the request.
9633 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009634 if (AI->getAlignment() >= PrefAlign)
9635 Align = AI->getAlignment();
9636 else {
9637 AI->setAlignment(PrefAlign);
9638 Align = PrefAlign;
9639 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009640 }
9641 }
9642
9643 return Align;
9644}
9645
9646/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9647/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9648/// and it is more than the alignment of the ultimate object, see if we can
9649/// increase the alignment of the ultimate object, making this check succeed.
9650unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9651 unsigned PrefAlign) {
9652 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9653 sizeof(PrefAlign) * CHAR_BIT;
9654 APInt Mask = APInt::getAllOnesValue(BitWidth);
9655 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9656 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9657 unsigned TrailZ = KnownZero.countTrailingOnes();
9658 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9659
9660 if (PrefAlign > Align)
9661 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9662
9663 // We don't need to make any adjustment.
9664 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009665}
9666
Chris Lattner00ae5132008-01-13 23:50:23 +00009667Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009668 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009669 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009670 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009671 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009672
9673 if (CopyAlign < MinAlign) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009674 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009675 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009676 return MI;
9677 }
9678
9679 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9680 // load/store.
9681 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9682 if (MemOpLength == 0) return 0;
9683
Chris Lattnerc669fb62008-01-14 00:28:35 +00009684 // Source and destination pointer types are always "i8*" for intrinsic. See
9685 // if the size is something we can handle with a single primitive load/store.
9686 // A single load+store correctly handles overlapping memory in the memmove
9687 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009688 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009689 if (Size == 0) return MI; // Delete this mem transfer.
9690
9691 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009692 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009693
Chris Lattnerc669fb62008-01-14 00:28:35 +00009694 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009695 Type *NewPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009696 PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009697
9698 // Memcpy forces the use of i8* for the source and destination. That means
9699 // that if you're using memcpy to move one double around, you'll get a cast
9700 // from double* to i8*. We'd much rather use a double load+store rather than
9701 // an i64 load+store, here because this improves the odds that the source or
9702 // dest address will be promotable. See if we can find a better type than the
9703 // integer datatype.
9704 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9705 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +00009706 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009707 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9708 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009709 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009710 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9711 if (STy->getNumElements() == 1)
9712 SrcETy = STy->getElementType(0);
9713 else
9714 break;
9715 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9716 if (ATy->getNumElements() == 1)
9717 SrcETy = ATy->getElementType();
9718 else
9719 break;
9720 } else
9721 break;
9722 }
9723
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009724 if (SrcETy->isSingleValueType())
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009725 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009726 }
9727 }
9728
9729
Chris Lattner00ae5132008-01-13 23:50:23 +00009730 // If the memcpy/memmove provides better alignment info than we can
9731 // infer, use it.
9732 SrcAlign = std::max(SrcAlign, CopyAlign);
9733 DstAlign = std::max(DstAlign, CopyAlign);
9734
9735 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9736 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009737 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9738 InsertNewInstBefore(L, *MI);
9739 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9740
9741 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009742 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009743 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009744}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009745
Chris Lattner5af8a912008-04-30 06:39:11 +00009746Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9747 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009748 if (MI->getAlignment() < Alignment) {
Owen Andersoneacb44d2009-07-24 23:12:02 +00009749 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersonf9f99362009-07-09 18:36:20 +00009750 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009751 return MI;
9752 }
9753
9754 // Extract the length and alignment and fill if they are constant.
9755 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9756 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9757 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9758 return 0;
9759 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009760 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009761
9762 // If the length is zero, this is a no-op
9763 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9764
9765 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9766 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009767 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009768
9769 Value *Dest = MI->getDest();
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009770 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009771
9772 // Alignment 0 is identity for alignment 1 for memset, but not store.
9773 if (Alignment == 0) Alignment = 1;
9774
9775 // Extract the fill value and store.
9776 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneacb44d2009-07-24 23:12:02 +00009777 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Anderson24be4c12009-07-03 00:17:18 +00009778 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009779
9780 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersonaac28372009-07-31 20:28:14 +00009781 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009782 return MI;
9783 }
9784
9785 return 0;
9786}
9787
9788
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009789/// visitCallInst - CallInst simplification. This mostly only handles folding
9790/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9791/// the heavy lifting.
9792///
9793Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009794 // If the caller function is nounwind, mark the call as nounwind, even if the
9795 // callee isn't.
9796 if (CI.getParent()->getParent()->doesNotThrow() &&
9797 !CI.doesNotThrow()) {
9798 CI.setDoesNotThrow();
9799 return &CI;
9800 }
9801
9802
9803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009804 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9805 if (!II) return visitCallSite(&CI);
9806
9807 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9808 // visitCallSite.
9809 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9810 bool Changed = false;
9811
9812 // memmove/cpy/set of zero bytes is a noop.
9813 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9814 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9815
9816 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9817 if (CI->getZExtValue() == 1) {
9818 // Replace the instruction with just byte operations. We would
9819 // transform other cases to loads/stores, but we don't know if
9820 // alignment is sufficient.
9821 }
9822 }
9823
9824 // If we have a memmove and the source operation is a constant global,
9825 // then the source and dest pointers can't alias, so we can change this
9826 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009827 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009828 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9829 if (GVSrc->isConstant()) {
9830 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009831 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9832 const Type *Tys[1];
9833 Tys[0] = CI.getOperand(3)->getType();
9834 CI.setOperand(0,
9835 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009836 Changed = true;
9837 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009838
9839 // memmove(x,x,size) -> noop.
9840 if (MMI->getSource() == MMI->getDest())
9841 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009842 }
9843
9844 // If we can determine a pointer alignment that is bigger than currently
9845 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009846 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009847 if (Instruction *I = SimplifyMemTransfer(MI))
9848 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009849 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9850 if (Instruction *I = SimplifyMemSet(MSI))
9851 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009852 }
9853
9854 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009855 }
9856
9857 switch (II->getIntrinsicID()) {
9858 default: break;
9859 case Intrinsic::bswap:
9860 // bswap(bswap(x)) -> x
9861 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9862 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9863 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9864 break;
9865 case Intrinsic::ppc_altivec_lvx:
9866 case Intrinsic::ppc_altivec_lvxl:
9867 case Intrinsic::x86_sse_loadu_ps:
9868 case Intrinsic::x86_sse2_loadu_pd:
9869 case Intrinsic::x86_sse2_loadu_dq:
9870 // Turn PPC lvx -> load if the pointer is known aligned.
9871 // Turn X86 loadups -> load if the pointer is known aligned.
9872 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9873 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009874 PointerType::getUnqual(II->getType()),
Chris Lattner989ba312008-06-18 04:33:20 +00009875 CI);
9876 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009877 }
Chris Lattner989ba312008-06-18 04:33:20 +00009878 break;
9879 case Intrinsic::ppc_altivec_stvx:
9880 case Intrinsic::ppc_altivec_stvxl:
9881 // Turn stvx -> store if the pointer is known aligned.
9882 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9883 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009884 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009885 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9886 return new StoreInst(II->getOperand(1), Ptr);
9887 }
9888 break;
9889 case Intrinsic::x86_sse_storeu_ps:
9890 case Intrinsic::x86_sse2_storeu_pd:
9891 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009892 // Turn X86 storeu -> store if the pointer is known aligned.
9893 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9894 const Type *OpPtrTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +00009895 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009896 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9897 return new StoreInst(II->getOperand(2), Ptr);
9898 }
9899 break;
9900
9901 case Intrinsic::x86_sse_cvttss2si: {
9902 // These intrinsics only demands the 0th element of its input vector. If
9903 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009904 unsigned VWidth =
9905 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9906 APInt DemandedElts(VWidth, 1);
9907 APInt UndefElts(VWidth, 0);
9908 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009909 UndefElts)) {
9910 II->setOperand(1, V);
9911 return II;
9912 }
9913 break;
9914 }
9915
9916 case Intrinsic::ppc_altivec_vperm:
9917 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9918 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9919 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009920
Chris Lattner989ba312008-06-18 04:33:20 +00009921 // Check that all of the elements are integer constants or undefs.
9922 bool AllEltsOk = true;
9923 for (unsigned i = 0; i != 16; ++i) {
9924 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9925 !isa<UndefValue>(Mask->getOperand(i))) {
9926 AllEltsOk = false;
9927 break;
9928 }
9929 }
9930
9931 if (AllEltsOk) {
9932 // Cast the input vectors to byte vectors.
9933 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9934 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersonb99ecca2009-07-30 23:03:37 +00009935 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009936
Chris Lattner989ba312008-06-18 04:33:20 +00009937 // Only extract each element once.
9938 Value *ExtractedElts[32];
9939 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9940
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009941 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009942 if (isa<UndefValue>(Mask->getOperand(i)))
9943 continue;
9944 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9945 Idx &= 31; // Match the hardware behavior.
9946
9947 if (ExtractedElts[Idx] == 0) {
9948 Instruction *Elt =
Eric Christopher1ba36872009-07-25 02:28:41 +00009949 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Andersoneacb44d2009-07-24 23:12:02 +00009950 ConstantInt::get(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009951 InsertNewInstBefore(Elt, CI);
9952 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009953 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009954
Chris Lattner989ba312008-06-18 04:33:20 +00009955 // Insert this value into the result vector.
9956 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Andersoneacb44d2009-07-24 23:12:02 +00009957 ConstantInt::get(Type::Int32Ty, i, false),
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00009958 "tmp");
Chris Lattner989ba312008-06-18 04:33:20 +00009959 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009960 }
Chris Lattner989ba312008-06-18 04:33:20 +00009961 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009962 }
Chris Lattner989ba312008-06-18 04:33:20 +00009963 }
9964 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009965
Chris Lattner989ba312008-06-18 04:33:20 +00009966 case Intrinsic::stackrestore: {
9967 // If the save is right next to the restore, remove the restore. This can
9968 // happen when variable allocas are DCE'd.
9969 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9970 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9971 BasicBlock::iterator BI = SS;
9972 if (&*++BI == II)
9973 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009974 }
Chris Lattner989ba312008-06-18 04:33:20 +00009975 }
9976
9977 // Scan down this block to see if there is another stack restore in the
9978 // same block without an intervening call/alloca.
9979 BasicBlock::iterator BI = II;
9980 TerminatorInst *TI = II->getParent()->getTerminator();
9981 bool CannotRemove = false;
9982 for (++BI; &*BI != TI; ++BI) {
9983 if (isa<AllocaInst>(BI)) {
9984 CannotRemove = true;
9985 break;
9986 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009987 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9988 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9989 // If there is a stackrestore below this one, remove this one.
9990 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9991 return EraseInstFromFunction(CI);
9992 // Otherwise, ignore the intrinsic.
9993 } else {
9994 // If we found a non-intrinsic call, we can't remove the stack
9995 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009996 CannotRemove = true;
9997 break;
9998 }
Chris Lattner989ba312008-06-18 04:33:20 +00009999 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010000 }
Chris Lattner989ba312008-06-18 04:33:20 +000010001
10002 // If the stack restore is in a return/unwind block and if there are no
10003 // allocas or calls between the restore and the return, nuke the restore.
10004 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10005 return EraseInstFromFunction(CI);
10006 break;
10007 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010008 }
10009
10010 return visitCallSite(II);
10011}
10012
10013// InvokeInst simplification
10014//
10015Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10016 return visitCallSite(&II);
10017}
10018
Dale Johannesen96021832008-04-25 21:16:07 +000010019/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10020/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010021static bool isSafeToEliminateVarargsCast(const CallSite CS,
10022 const CastInst * const CI,
10023 const TargetData * const TD,
10024 const int ix) {
10025 if (!CI->isLosslessCast())
10026 return false;
10027
10028 // The size of ByVal arguments is derived from the type, so we
10029 // can't change to a type with a different size. If the size were
10030 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010031 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010032 return true;
10033
10034 const Type* SrcTy =
10035 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10036 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10037 if (!SrcTy->isSized() || !DstTy->isSized())
10038 return false;
Dan Gohmana80e2712009-07-21 23:21:54 +000010039 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010040 return false;
10041 return true;
10042}
10043
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010044// visitCallSite - Improvements for call and invoke instructions.
10045//
10046Instruction *InstCombiner::visitCallSite(CallSite CS) {
10047 bool Changed = false;
10048
10049 // If the callee is a constexpr cast of a function, attempt to move the cast
10050 // to the arguments of the call/invoke.
10051 if (transformConstExprCastCall(CS)) return 0;
10052
10053 Value *Callee = CS.getCalledValue();
10054
10055 if (Function *CalleeF = dyn_cast<Function>(Callee))
10056 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10057 Instruction *OldCall = CS.getInstruction();
10058 // If the call and callee calling conventions don't match, this call must
10059 // be unreachable, as the call is undefined.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010060 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000010061 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Owen Anderson24be4c12009-07-03 00:17:18 +000010062 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010063 if (!OldCall->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000010064 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010065 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10066 return EraseInstFromFunction(*OldCall);
10067 return 0;
10068 }
10069
10070 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10071 // This instruction is not reachable, just remove it. We insert a store to
10072 // undef so that we know that this code is not reachable, despite the fact
10073 // that we can't modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000010074 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000010075 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010076 CS.getInstruction());
10077
10078 if (!CS.getInstruction()->use_empty())
10079 CS.getInstruction()->
Owen Andersonb99ecca2009-07-30 23:03:37 +000010080 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010081
10082 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10083 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010084 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson4f720fa2009-07-31 17:39:07 +000010085 ConstantInt::getTrue(*Context), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010086 }
10087 return EraseInstFromFunction(*CS.getInstruction());
10088 }
10089
Duncan Sands74833f22007-09-17 10:26:40 +000010090 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10091 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10092 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10093 return transformCallThroughTrampoline(CS);
10094
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010095 const PointerType *PTy = cast<PointerType>(Callee->getType());
10096 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10097 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010098 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010099 // See if we can optimize any arguments passed through the varargs area of
10100 // the call.
10101 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010102 E = CS.arg_end(); I != E; ++I, ++ix) {
10103 CastInst *CI = dyn_cast<CastInst>(*I);
10104 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10105 *I = CI->getOperand(0);
10106 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010107 }
Dale Johannesen35615462008-04-23 18:34:37 +000010108 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010109 }
10110
Duncan Sands2937e352007-12-19 21:13:37 +000010111 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010112 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010113 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010114 Changed = true;
10115 }
10116
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010117 return Changed ? CS.getInstruction() : 0;
10118}
10119
10120// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10121// attempt to move the cast to the arguments of the call/invoke.
10122//
10123bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10124 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10125 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10126 if (CE->getOpcode() != Instruction::BitCast ||
10127 !isa<Function>(CE->getOperand(0)))
10128 return false;
10129 Function *Callee = cast<Function>(CE->getOperand(0));
10130 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010131 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010132
10133 // Okay, this is a cast from a function to a different type. Unless doing so
10134 // would cause a type conversion of one of our arguments, change this call to
10135 // be a direct call with arguments casted to the appropriate types.
10136 //
10137 const FunctionType *FT = Callee->getFunctionType();
10138 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010139 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010140
Duncan Sands7901ce12008-06-01 07:38:42 +000010141 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010142 return false; // TODO: Handle multiple return values.
10143
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010144 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010145 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010146 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010147 // Conversion is ok if changing from one pointer type to another or from
10148 // a pointer to an integer of the same size.
Dan Gohmana80e2712009-07-21 23:21:54 +000010149 !((isa<PointerType>(OldRetTy) || !TD ||
10150 OldRetTy == TD->getIntPtrType()) &&
10151 (isa<PointerType>(NewRetTy) || !TD ||
10152 NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010153 return false; // Cannot transform this return value.
10154
Duncan Sands5c489582008-01-06 10:12:28 +000010155 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010156 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +000010157 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010158 return false; // Cannot transform this return value.
10159
Chris Lattner1c8733e2008-03-12 17:45:29 +000010160 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010161 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010162 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010163 return false; // Attribute not compatible with transformed value.
10164 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010165
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010166 // If the callsite is an invoke instruction, and the return value is used by
10167 // a PHI node in a successor, we cannot change the return type of the call
10168 // because there is no place to put the cast instruction (without breaking
10169 // the critical edge). Bail out in this case.
10170 if (!Caller->use_empty())
10171 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10172 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10173 UI != E; ++UI)
10174 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10175 if (PN->getParent() == II->getNormalDest() ||
10176 PN->getParent() == II->getUnwindDest())
10177 return false;
10178 }
10179
10180 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10181 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10182
10183 CallSite::arg_iterator AI = CS.arg_begin();
10184 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10185 const Type *ParamTy = FT->getParamType(i);
10186 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010187
10188 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010189 return false; // Cannot transform this parameter value.
10190
Devang Patelf2a4a922008-09-26 22:53:05 +000010191 if (CallerPAL.getParamAttributes(i + 1)
10192 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010193 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010194
Duncan Sands7901ce12008-06-01 07:38:42 +000010195 // Converting from one pointer type to another or between a pointer and an
10196 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010197 bool isConvertible = ActTy == ParamTy ||
Dan Gohmana80e2712009-07-21 23:21:54 +000010198 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10199 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010200 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010201 }
10202
10203 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10204 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010205 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010206
Chris Lattner1c8733e2008-03-12 17:45:29 +000010207 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10208 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010209 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010210 // won't be dropping them. Check that these extra arguments have attributes
10211 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010212 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10213 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010214 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010215 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010216 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010217 return false;
10218 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010219
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010220 // Okay, we decided that this is a safe thing to do: go ahead and start
10221 // inserting cast instructions as necessary...
10222 std::vector<Value*> Args;
10223 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010224 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010225 attrVec.reserve(NumCommonArgs);
10226
10227 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010228 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010229
10230 // If the return value is not being used, the type may not be compatible
10231 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010232 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010233
10234 // Add the new return attributes.
10235 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010236 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010237
10238 AI = CS.arg_begin();
10239 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10240 const Type *ParamTy = FT->getParamType(i);
10241 if ((*AI)->getType() == ParamTy) {
10242 Args.push_back(*AI);
10243 } else {
10244 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10245 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010246 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010247 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10248 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010249
10250 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010251 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010252 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010253 }
10254
10255 // If the function takes more arguments than the call was taking, add them
10256 // now...
10257 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersonaac28372009-07-31 20:28:14 +000010258 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010259
10260 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010261 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010262 if (!FT->isVarArg()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +000010263 errs() << "WARNING: While resolving call to function '"
10264 << Callee->getName() << "' arguments were dropped!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010265 } else {
10266 // Add all of the arguments in their promoted form to the arg list...
10267 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10268 const Type *PTy = getPromotedType((*AI)->getType());
10269 if (PTy != (*AI)->getType()) {
10270 // Must promote to pass through va_arg area!
10271 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10272 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010273 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010274 InsertNewInstBefore(Cast, *Caller);
10275 Args.push_back(Cast);
10276 } else {
10277 Args.push_back(*AI);
10278 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010279
Duncan Sands4ced1f82008-01-13 08:02:44 +000010280 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010281 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010282 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010283 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010284 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010285 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010286
Devang Patelf2a4a922008-09-26 22:53:05 +000010287 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10288 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10289
Duncan Sands7901ce12008-06-01 07:38:42 +000010290 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010291 Caller->setName(""); // Void type should not have a name.
10292
Eric Christopher3e7381f2009-07-25 02:45:27 +000010293 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10294 attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010295
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010296 Instruction *NC;
10297 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010298 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010299 Args.begin(), Args.end(),
10300 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010301 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010302 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010303 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010304 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10305 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010306 CallInst *CI = cast<CallInst>(Caller);
10307 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010308 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010309 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010310 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010311 }
10312
10313 // Insert a cast of the return type as necessary.
10314 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010315 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010316 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010317 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010318 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010319 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010320
10321 // If this is an invoke instruction, we should insert it after the first
10322 // non-phi, instruction in the normal successor block.
10323 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010324 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010325 InsertNewInstBefore(NC, *I);
10326 } else {
10327 // Otherwise, it's a call, just insert cast right after the call instr
10328 InsertNewInstBefore(NC, *Caller);
10329 }
10330 AddUsersToWorkList(*Caller);
10331 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010332 NV = UndefValue::get(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010333 }
10334 }
10335
10336 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10337 Caller->replaceAllUsesWith(NV);
10338 Caller->eraseFromParent();
10339 RemoveFromWorkList(Caller);
10340 return true;
10341}
10342
Duncan Sands74833f22007-09-17 10:26:40 +000010343// transformCallThroughTrampoline - Turn a call to a function created by the
10344// init_trampoline intrinsic into a direct call to the underlying function.
10345//
10346Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10347 Value *Callee = CS.getCalledValue();
10348 const PointerType *PTy = cast<PointerType>(Callee->getType());
10349 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010350 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010351
10352 // If the call already has the 'nest' attribute somewhere then give up -
10353 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010354 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010355 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010356
10357 IntrinsicInst *Tramp =
10358 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10359
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010360 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010361 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10362 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10363
Devang Pateld222f862008-09-25 21:00:45 +000010364 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010365 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010366 unsigned NestIdx = 1;
10367 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010368 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010369
10370 // Look for a parameter marked with the 'nest' attribute.
10371 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10372 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010373 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010374 // Record the parameter type and any other attributes.
10375 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010376 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010377 break;
10378 }
10379
10380 if (NestTy) {
10381 Instruction *Caller = CS.getInstruction();
10382 std::vector<Value*> NewArgs;
10383 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10384
Devang Pateld222f862008-09-25 21:00:45 +000010385 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010386 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010387
Duncan Sands74833f22007-09-17 10:26:40 +000010388 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010389 // mean appending it. Likewise for attributes.
10390
Devang Patelf2a4a922008-09-26 22:53:05 +000010391 // Add any result attributes.
10392 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010393 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010394
Duncan Sands74833f22007-09-17 10:26:40 +000010395 {
10396 unsigned Idx = 1;
10397 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10398 do {
10399 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010400 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010401 Value *NestVal = Tramp->getOperand(3);
10402 if (NestVal->getType() != NestTy)
10403 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10404 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010405 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010406 }
10407
10408 if (I == E)
10409 break;
10410
Duncan Sands48b81112008-01-14 19:52:09 +000010411 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010412 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010413 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010414 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010415 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010416
10417 ++Idx, ++I;
10418 } while (1);
10419 }
10420
Devang Patelf2a4a922008-09-26 22:53:05 +000010421 // Add any function attributes.
10422 if (Attributes Attr = Attrs.getFnAttributes())
10423 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10424
Duncan Sands74833f22007-09-17 10:26:40 +000010425 // The trampoline may have been bitcast to a bogus type (FTy).
10426 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010427 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010428
Duncan Sands74833f22007-09-17 10:26:40 +000010429 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010430 NewTypes.reserve(FTy->getNumParams()+1);
10431
Duncan Sands74833f22007-09-17 10:26:40 +000010432 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010433 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010434 {
10435 unsigned Idx = 1;
10436 FunctionType::param_iterator I = FTy->param_begin(),
10437 E = FTy->param_end();
10438
10439 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010440 if (Idx == NestIdx)
10441 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010442 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010443
10444 if (I == E)
10445 break;
10446
Duncan Sands48b81112008-01-14 19:52:09 +000010447 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010448 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010449
10450 ++Idx, ++I;
10451 } while (1);
10452 }
10453
10454 // Replace the trampoline call with a direct call. Let the generic
10455 // code sort out any function type mismatches.
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010456 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Anderson24be4c12009-07-03 00:17:18 +000010457 FTy->isVarArg());
10458 Constant *NewCallee =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010459 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Anderson02b48c32009-07-29 18:55:55 +000010460 NestF : ConstantExpr::getBitCast(NestF,
Owen Anderson6b6e2d92009-07-29 22:17:13 +000010461 PointerType::getUnqual(NewFTy));
Eric Christopher3e7381f2009-07-25 02:45:27 +000010462 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10463 NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010464
10465 Instruction *NewCaller;
10466 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010467 NewCaller = InvokeInst::Create(NewCallee,
10468 II->getNormalDest(), II->getUnwindDest(),
10469 NewArgs.begin(), NewArgs.end(),
10470 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010471 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010472 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010473 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010474 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10475 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010476 if (cast<CallInst>(Caller)->isTailCall())
10477 cast<CallInst>(NewCaller)->setTailCall();
10478 cast<CallInst>(NewCaller)->
10479 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010480 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010481 }
10482 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10483 Caller->replaceAllUsesWith(NewCaller);
10484 Caller->eraseFromParent();
10485 RemoveFromWorkList(Caller);
10486 return 0;
10487 }
10488 }
10489
10490 // Replace the trampoline call with a direct call. Since there is no 'nest'
10491 // parameter, there is no need to adjust the argument list. Let the generic
10492 // code sort out any function type mismatches.
10493 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010494 NestF->getType() == PTy ? NestF :
Owen Anderson02b48c32009-07-29 18:55:55 +000010495 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010496 CS.setCalledFunction(NewCallee);
10497 return CS.getInstruction();
10498}
10499
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010500/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10501/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10502/// and a single binop.
10503Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10504 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010505 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010506 unsigned Opc = FirstInst->getOpcode();
10507 Value *LHSVal = FirstInst->getOperand(0);
10508 Value *RHSVal = FirstInst->getOperand(1);
10509
10510 const Type *LHSType = LHSVal->getType();
10511 const Type *RHSType = RHSVal->getType();
10512
10513 // Scan to see if all operands are the same opcode, all have one use, and all
10514 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010515 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010516 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10517 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10518 // Verify type of the LHS matches so we don't fold cmp's of different
10519 // types or GEP's with different index types.
10520 I->getOperand(0)->getType() != LHSType ||
10521 I->getOperand(1)->getType() != RHSType)
10522 return 0;
10523
10524 // If they are CmpInst instructions, check their predicates
10525 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10526 if (cast<CmpInst>(I)->getPredicate() !=
10527 cast<CmpInst>(FirstInst)->getPredicate())
10528 return 0;
10529
10530 // Keep track of which operand needs a phi node.
10531 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10532 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10533 }
10534
Chris Lattner30078012008-12-01 03:42:51 +000010535 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010536
10537 Value *InLHS = FirstInst->getOperand(0);
10538 Value *InRHS = FirstInst->getOperand(1);
10539 PHINode *NewLHS = 0, *NewRHS = 0;
10540 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010541 NewLHS = PHINode::Create(LHSType,
10542 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010543 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10544 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10545 InsertNewInstBefore(NewLHS, PN);
10546 LHSVal = NewLHS;
10547 }
10548
10549 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010550 NewRHS = PHINode::Create(RHSType,
10551 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010552 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10553 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10554 InsertNewInstBefore(NewRHS, PN);
10555 RHSVal = NewRHS;
10556 }
10557
10558 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010559 if (NewLHS || NewRHS) {
10560 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10561 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10562 if (NewLHS) {
10563 Value *NewInLHS = InInst->getOperand(0);
10564 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10565 }
10566 if (NewRHS) {
10567 Value *NewInRHS = InInst->getOperand(1);
10568 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10569 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010570 }
10571 }
10572
10573 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010574 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010575 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson6601fcd2009-07-09 23:48:35 +000010576 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10577 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010578}
10579
Chris Lattner9e1916e2008-12-01 02:34:36 +000010580Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10581 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10582
10583 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10584 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010585 // This is true if all GEP bases are allocas and if all indices into them are
10586 // constants.
10587 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010588
10589 // Scan to see if all operands are the same opcode, all have one use, and all
10590 // kill their operands (i.e. the operands have one use).
10591 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10592 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10593 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10594 GEP->getNumOperands() != FirstInst->getNumOperands())
10595 return 0;
10596
Chris Lattneradf354b2009-02-21 00:46:50 +000010597 // Keep track of whether or not all GEPs are of alloca pointers.
10598 if (AllBasePointersAreAllocas &&
10599 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10600 !GEP->hasAllConstantIndices()))
10601 AllBasePointersAreAllocas = false;
10602
Chris Lattner9e1916e2008-12-01 02:34:36 +000010603 // Compare the operand lists.
10604 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10605 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10606 continue;
10607
10608 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10609 // if one of the PHIs has a constant for the index. The index may be
10610 // substantially cheaper to compute for the constants, so making it a
10611 // variable index could pessimize the path. This also handles the case
10612 // for struct indices, which must always be constant.
10613 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10614 isa<ConstantInt>(GEP->getOperand(op)))
10615 return 0;
10616
10617 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10618 return 0;
10619 FixedOperands[op] = 0; // Needs a PHI.
10620 }
10621 }
10622
Chris Lattneradf354b2009-02-21 00:46:50 +000010623 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010624 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010625 // offset calculation, but all the predecessors will have to materialize the
10626 // stack address into a register anyway. We'd actually rather *clone* the
10627 // load up into the predecessors so that we have a load of a gep of an alloca,
10628 // which can usually all be folded into the load.
10629 if (AllBasePointersAreAllocas)
10630 return 0;
10631
Chris Lattner9e1916e2008-12-01 02:34:36 +000010632 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10633 // that is variable.
10634 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10635
10636 bool HasAnyPHIs = false;
10637 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10638 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10639 Value *FirstOp = FirstInst->getOperand(i);
10640 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10641 FirstOp->getName()+".pn");
10642 InsertNewInstBefore(NewPN, PN);
10643
10644 NewPN->reserveOperandSpace(e);
10645 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10646 OperandPhis[i] = NewPN;
10647 FixedOperands[i] = NewPN;
10648 HasAnyPHIs = true;
10649 }
10650
10651
10652 // Add all operands to the new PHIs.
10653 if (HasAnyPHIs) {
10654 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10655 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10656 BasicBlock *InBB = PN.getIncomingBlock(i);
10657
10658 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10659 if (PHINode *OpPhi = OperandPhis[op])
10660 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10661 }
10662 }
10663
10664 Value *Base = FixedOperands[0];
Dan Gohman17f46f72009-07-28 01:40:03 +000010665 GetElementPtrInst *GEP =
10666 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10667 FixedOperands.end());
10668 if (cast<GEPOperator>(FirstInst)->isInBounds())
10669 cast<GEPOperator>(GEP)->setIsInBounds(true);
10670 return GEP;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010671}
10672
10673
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010674/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10675/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010676/// obvious the value of the load is not changed from the point of the load to
10677/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010678///
10679/// Finally, it is safe, but not profitable, to sink a load targetting a
10680/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10681/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010682static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010683 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10684
10685 for (++BBI; BBI != E; ++BBI)
10686 if (BBI->mayWriteToMemory())
10687 return false;
10688
10689 // Check for non-address taken alloca. If not address-taken already, it isn't
10690 // profitable to do this xform.
10691 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10692 bool isAddressTaken = false;
10693 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10694 UI != E; ++UI) {
10695 if (isa<LoadInst>(UI)) continue;
10696 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10697 // If storing TO the alloca, then the address isn't taken.
10698 if (SI->getOperand(1) == AI) continue;
10699 }
10700 isAddressTaken = true;
10701 break;
10702 }
10703
Chris Lattneradf354b2009-02-21 00:46:50 +000010704 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010705 return false;
10706 }
10707
Chris Lattneradf354b2009-02-21 00:46:50 +000010708 // If this load is a load from a GEP with a constant offset from an alloca,
10709 // then we don't want to sink it. In its present form, it will be
10710 // load [constant stack offset]. Sinking it will cause us to have to
10711 // materialize the stack addresses in each predecessor in a register only to
10712 // do a shared load from register in the successor.
10713 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10714 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10715 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10716 return false;
10717
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010718 return true;
10719}
10720
10721
10722// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10723// operator and they all are only used by the PHI, PHI together their
10724// inputs, and do the operation once, to the result of the PHI.
10725Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10726 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10727
10728 // Scan the instruction, looking for input operations that can be folded away.
10729 // If all input operands to the phi are the same instruction (e.g. a cast from
10730 // the same type or "+42") we can pull the operation through the PHI, reducing
10731 // code size and simplifying code.
10732 Constant *ConstantOp = 0;
10733 const Type *CastSrcTy = 0;
10734 bool isVolatile = false;
10735 if (isa<CastInst>(FirstInst)) {
10736 CastSrcTy = FirstInst->getOperand(0)->getType();
10737 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10738 // Can fold binop, compare or shift here if the RHS is a constant,
10739 // otherwise call FoldPHIArgBinOpIntoPHI.
10740 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10741 if (ConstantOp == 0)
10742 return FoldPHIArgBinOpIntoPHI(PN);
10743 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10744 isVolatile = LI->isVolatile();
10745 // We can't sink the load if the loaded value could be modified between the
10746 // load and the PHI.
10747 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010748 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010749 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010750
10751 // If the PHI is of volatile loads and the load block has multiple
10752 // successors, sinking it would remove a load of the volatile value from
10753 // the path through the other successor.
10754 if (isVolatile &&
10755 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10756 return 0;
10757
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010758 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010759 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010760 } else {
10761 return 0; // Cannot fold this operation.
10762 }
10763
10764 // Check to see if all arguments are the same operation.
10765 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10766 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10767 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10768 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10769 return 0;
10770 if (CastSrcTy) {
10771 if (I->getOperand(0)->getType() != CastSrcTy)
10772 return 0; // Cast operation must match.
10773 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10774 // We can't sink the load if the loaded value could be modified between
10775 // the load and the PHI.
10776 if (LI->isVolatile() != isVolatile ||
10777 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010778 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010779 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010780
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010781 // If the PHI is of volatile loads and the load block has multiple
10782 // successors, sinking it would remove a load of the volatile value from
10783 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010784 if (isVolatile &&
10785 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10786 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010787
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010788 } else if (I->getOperand(1) != ConstantOp) {
10789 return 0;
10790 }
10791 }
10792
10793 // Okay, they are all the same operation. Create a new PHI node of the
10794 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010795 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10796 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010797 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10798
10799 Value *InVal = FirstInst->getOperand(0);
10800 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10801
10802 // Add all operands to the new PHI.
10803 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10804 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10805 if (NewInVal != InVal)
10806 InVal = 0;
10807 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10808 }
10809
10810 Value *PhiVal;
10811 if (InVal) {
10812 // The new PHI unions all of the same values together. This is really
10813 // common, so we handle it intelligently here for compile-time speed.
10814 PhiVal = InVal;
10815 delete NewPN;
10816 } else {
10817 InsertNewInstBefore(NewPN, PN);
10818 PhiVal = NewPN;
10819 }
10820
10821 // Insert and return the new operation.
10822 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010823 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010824 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010825 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010826 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson6601fcd2009-07-09 23:48:35 +000010827 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010828 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010829 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10830
10831 // If this was a volatile load that we are merging, make sure to loop through
10832 // and mark all the input loads as non-volatile. If we don't do this, we will
10833 // insert a new volatile load and the old ones will not be deletable.
10834 if (isVolatile)
10835 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10836 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10837
10838 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010839}
10840
10841/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10842/// that is dead.
10843static bool DeadPHICycle(PHINode *PN,
10844 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10845 if (PN->use_empty()) return true;
10846 if (!PN->hasOneUse()) return false;
10847
10848 // Remember this node, and if we find the cycle, return.
10849 if (!PotentiallyDeadPHIs.insert(PN))
10850 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010851
10852 // Don't scan crazily complex things.
10853 if (PotentiallyDeadPHIs.size() == 16)
10854 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010855
10856 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10857 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10858
10859 return false;
10860}
10861
Chris Lattner27b695d2007-11-06 21:52:06 +000010862/// PHIsEqualValue - Return true if this phi node is always equal to
10863/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10864/// z = some value; x = phi (y, z); y = phi (x, z)
10865static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10866 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10867 // See if we already saw this PHI node.
10868 if (!ValueEqualPHIs.insert(PN))
10869 return true;
10870
10871 // Don't scan crazily complex things.
10872 if (ValueEqualPHIs.size() == 16)
10873 return false;
10874
10875 // Scan the operands to see if they are either phi nodes or are equal to
10876 // the value.
10877 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10878 Value *Op = PN->getIncomingValue(i);
10879 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10880 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10881 return false;
10882 } else if (Op != NonPhiInVal)
10883 return false;
10884 }
10885
10886 return true;
10887}
10888
10889
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010890// PHINode simplification
10891//
10892Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10893 // If LCSSA is around, don't mess with Phi nodes
10894 if (MustPreserveLCSSA) return 0;
10895
10896 if (Value *V = PN.hasConstantValue())
10897 return ReplaceInstUsesWith(PN, V);
10898
10899 // If all PHI operands are the same operation, pull them through the PHI,
10900 // reducing code size.
10901 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010902 isa<Instruction>(PN.getIncomingValue(1)) &&
10903 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10904 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10905 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10906 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010907 PN.getIncomingValue(0)->hasOneUse())
10908 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10909 return Result;
10910
10911 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10912 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10913 // PHI)... break the cycle.
10914 if (PN.hasOneUse()) {
10915 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10916 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10917 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10918 PotentiallyDeadPHIs.insert(&PN);
10919 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010920 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010921 }
10922
10923 // If this phi has a single use, and if that use just computes a value for
10924 // the next iteration of a loop, delete the phi. This occurs with unused
10925 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10926 // common case here is good because the only other things that catch this
10927 // are induction variable analysis (sometimes) and ADCE, which is only run
10928 // late.
10929 if (PHIUser->hasOneUse() &&
10930 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10931 PHIUser->use_back() == &PN) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000010932 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010933 }
10934 }
10935
Chris Lattner27b695d2007-11-06 21:52:06 +000010936 // We sometimes end up with phi cycles that non-obviously end up being the
10937 // same value, for example:
10938 // z = some value; x = phi (y, z); y = phi (x, z)
10939 // where the phi nodes don't necessarily need to be in the same block. Do a
10940 // quick check to see if the PHI node only contains a single non-phi value, if
10941 // so, scan to see if the phi cycle is actually equal to that value.
10942 {
10943 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10944 // Scan for the first non-phi operand.
10945 while (InValNo != NumOperandVals &&
10946 isa<PHINode>(PN.getIncomingValue(InValNo)))
10947 ++InValNo;
10948
10949 if (InValNo != NumOperandVals) {
10950 Value *NonPhiInVal = PN.getOperand(InValNo);
10951
10952 // Scan the rest of the operands to see if there are any conflicts, if so
10953 // there is no need to recursively scan other phis.
10954 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10955 Value *OpVal = PN.getIncomingValue(InValNo);
10956 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10957 break;
10958 }
10959
10960 // If we scanned over all operands, then we have one unique value plus
10961 // phi values. Scan PHI nodes to see if they all merge in each other or
10962 // the value.
10963 if (InValNo == NumOperandVals) {
10964 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10965 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10966 return ReplaceInstUsesWith(PN, NonPhiInVal);
10967 }
10968 }
10969 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010970 return 0;
10971}
10972
10973static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10974 Instruction *InsertPoint,
10975 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000010976 unsigned PtrSize = DTy->getScalarSizeInBits();
10977 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010978 // We must cast correctly to the pointer type. Ensure that we
10979 // sign extend the integer value if it is smaller as this is
10980 // used for address computation.
10981 Instruction::CastOps opcode =
10982 (VTySize < PtrSize ? Instruction::SExt :
10983 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10984 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10985}
10986
10987
10988Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10989 Value *PtrOp = GEP.getOperand(0);
10990 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10991 // If so, eliminate the noop.
10992 if (GEP.getNumOperands() == 1)
10993 return ReplaceInstUsesWith(GEP, PtrOp);
10994
10995 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000010996 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010997
10998 bool HasZeroPointerIndex = false;
10999 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11000 HasZeroPointerIndex = C->isNullValue();
11001
11002 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11003 return ReplaceInstUsesWith(GEP, PtrOp);
11004
11005 // Eliminate unneeded casts for indices.
11006 bool MadeChange = false;
11007
11008 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011009 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11010 i != e; ++i, ++GTI) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011011 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000011012 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011013 if (CI->getOpcode() == Instruction::ZExt ||
11014 CI->getOpcode() == Instruction::SExt) {
11015 const Type *SrcTy = CI->getOperand(0)->getType();
11016 // We can eliminate a cast from i32 to i64 iff the target
11017 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000011018 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011019 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000011020 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011021 }
11022 }
11023 }
11024 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000011025 // to what we need. If narrower, sign-extend it to what we need.
11026 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011027 // insert it. This explicit cast can make subsequent optimizations more
11028 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000011029 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011030 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011031 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson02b48c32009-07-29 18:55:55 +000011032 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011033 MadeChange = true;
11034 } else {
11035 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11036 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011037 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011038 MadeChange = true;
11039 }
Eric Christopher3e7381f2009-07-25 02:45:27 +000011040 } else if (TD->getTypeSizeInBits(Op->getType())
11041 < TD->getPointerSizeInBits()) {
Dan Gohman5d639ed2008-09-11 23:06:38 +000011042 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson02b48c32009-07-29 18:55:55 +000011043 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
Dan Gohman5d639ed2008-09-11 23:06:38 +000011044 MadeChange = true;
11045 } else {
11046 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11047 GEP);
11048 *i = Op;
11049 MadeChange = true;
11050 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011051 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011052 }
11053 }
11054 if (MadeChange) return &GEP;
11055
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011056 // Combine Indices - If the source pointer to this getelementptr instruction
11057 // is a getelementptr instruction, combine the indices of the two
11058 // getelementptr instructions into a single instruction.
11059 //
11060 SmallVector<Value*, 8> SrcGEPOperands;
Dan Gohman17f46f72009-07-28 01:40:03 +000011061 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11062 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011063 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011064 if (!Src->isInBounds())
11065 BothInBounds = false;
11066 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011067
11068 if (!SrcGEPOperands.empty()) {
11069 // Note that if our source is a gep chain itself that we wait for that
11070 // chain to be resolved before we perform this transformation. This
11071 // avoids us creating a TON of code in some cases.
11072 //
11073 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11074 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11075 return 0; // Wait until our source is folded to completion.
11076
11077 SmallVector<Value*, 8> Indices;
11078
11079 // Find out whether the last index in the source GEP is a sequential idx.
11080 bool EndsWithSequential = false;
11081 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11082 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11083 EndsWithSequential = !isa<StructType>(*I);
11084
11085 // Can we combine the two pointer arithmetics offsets?
11086 if (EndsWithSequential) {
11087 // Replace: gep (gep %P, long B), long A, ...
11088 // With: T = long A+B; gep %P, T, ...
11089 //
11090 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +000011091 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011092 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +000011093 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011094 Sum = SO1;
11095 } else {
11096 // If they aren't the same type, convert both to an integer of the
11097 // target's pointer size.
11098 if (SO1->getType() != GO1->getType()) {
11099 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011100 SO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011101 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011102 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011103 GO1 =
Owen Anderson02b48c32009-07-29 18:55:55 +000011104 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmana80e2712009-07-21 23:21:54 +000011105 } else if (TD) {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011106 unsigned PS = TD->getPointerSizeInBits();
11107 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011108 // Convert GO1 to SO1's type.
11109 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11110
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011111 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011112 // Convert SO1 to GO1's type.
11113 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11114 } else {
11115 const Type *PT = TD->getIntPtrType();
11116 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11117 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11118 }
11119 }
11120 }
11121 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Anderson02b48c32009-07-29 18:55:55 +000011122 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
Owen Anderson24be4c12009-07-03 00:17:18 +000011123 cast<Constant>(GO1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011124 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011125 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011126 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11127 }
11128 }
11129
11130 // Recycle the GEP we already have if possible.
11131 if (SrcGEPOperands.size() == 2) {
11132 GEP.setOperand(0, SrcGEPOperands[0]);
11133 GEP.setOperand(1, Sum);
11134 return &GEP;
11135 } else {
11136 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11137 SrcGEPOperands.end()-1);
11138 Indices.push_back(Sum);
11139 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11140 }
11141 } else if (isa<Constant>(*GEP.idx_begin()) &&
11142 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11143 SrcGEPOperands.size() != 1) {
11144 // Otherwise we can do the fold if the first index of the GEP is a zero
11145 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11146 SrcGEPOperands.end());
11147 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11148 }
11149
Dan Gohman17f46f72009-07-28 01:40:03 +000011150 if (!Indices.empty()) {
11151 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11152 Indices.begin(),
11153 Indices.end(),
11154 GEP.getName());
11155 if (BothInBounds)
11156 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11157 return NewGEP;
11158 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011159
11160 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11161 // GEP of global variable. If all of the indices for this GEP are
11162 // constants, we can promote this to a constexpr instead of an instruction.
11163
11164 // Scan for nonconstants...
11165 SmallVector<Constant*, 8> Indices;
11166 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11167 for (; I != E && isa<Constant>(*I); ++I)
11168 Indices.push_back(cast<Constant>(*I));
11169
11170 if (I == E) { // If they are all constants...
Owen Anderson02b48c32009-07-29 18:55:55 +000011171 Constant *CE = ConstantExpr::getGetElementPtr(GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011172 &Indices[0],Indices.size());
11173
11174 // Replace all uses of the GEP with the new constexpr...
11175 return ReplaceInstUsesWith(GEP, CE);
11176 }
11177 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11178 if (!isa<PointerType>(X->getType())) {
11179 // Not interesting. Source pointer must be a cast from pointer.
11180 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011181 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11182 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011183 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011184 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11185 // into : GEP i8* X, ...
11186 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011187 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011188 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11189 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011190 if (const ArrayType *CATy =
11191 dyn_cast<ArrayType>(CPTy->getElementType())) {
11192 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11193 if (CATy->getElementType() == XTy->getElementType()) {
11194 // -> GEP i8* X, ...
11195 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohman17f46f72009-07-28 01:40:03 +000011196 GetElementPtrInst *NewGEP =
11197 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11198 GEP.getName());
11199 if (cast<GEPOperator>(&GEP)->isInBounds())
11200 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11201 return NewGEP;
Duncan Sandscf866e62009-03-02 09:18:21 +000011202 } else if (const ArrayType *XATy =
11203 dyn_cast<ArrayType>(XTy->getElementType())) {
11204 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011205 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011206 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011207 // At this point, we know that the cast source type is a pointer
11208 // to an array of the same type as the destination pointer
11209 // array. Because the array type is never stepped over (there
11210 // is a leading zero) we can fold the cast into this GEP.
11211 GEP.setOperand(0, X);
11212 return &GEP;
11213 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011214 }
11215 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011216 } else if (GEP.getNumOperands() == 2) {
11217 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011218 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11219 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011220 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11221 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011222 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011223 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11224 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011225 Value *Idx[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011226 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011227 Idx[1] = GEP.getOperand(1);
Dan Gohman17f46f72009-07-28 01:40:03 +000011228 GetElementPtrInst *NewGEP =
11229 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11230 if (cast<GEPOperator>(&GEP)->isInBounds())
11231 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11232 Value *V = InsertNewInstBefore(NewGEP, GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011233 // V and GEP are both pointer types --> BitCast
11234 return new BitCastInst(V, GEP.getType());
11235 }
11236
11237 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011238 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011239 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011240 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011241
Dan Gohmana80e2712009-07-21 23:21:54 +000011242 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011243 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011244 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011245
11246 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11247 // allow either a mul, shift, or constant here.
11248 Value *NewIdx = 0;
11249 ConstantInt *Scale = 0;
11250 if (ArrayEltSize == 1) {
11251 NewIdx = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011252 Scale =
Owen Andersoneacb44d2009-07-24 23:12:02 +000011253 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011254 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011255 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011256 Scale = CI;
11257 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11258 if (Inst->getOpcode() == Instruction::Shl &&
11259 isa<ConstantInt>(Inst->getOperand(1))) {
11260 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11261 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +000011262 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011263 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011264 NewIdx = Inst->getOperand(0);
11265 } else if (Inst->getOpcode() == Instruction::Mul &&
11266 isa<ConstantInt>(Inst->getOperand(1))) {
11267 Scale = cast<ConstantInt>(Inst->getOperand(1));
11268 NewIdx = Inst->getOperand(0);
11269 }
11270 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011271
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011272 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011273 // out, perform the transformation. Note, we don't know whether Scale is
11274 // signed or not. We'll use unsigned version of division/modulo
11275 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011276 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011277 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000011278 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011279 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011280 if (Scale->getZExtValue() != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011281 Constant *C =
Owen Anderson02b48c32009-07-29 18:55:55 +000011282 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011283 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011284 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011285 NewIdx = InsertNewInstBefore(Sc, GEP);
11286 }
11287
11288 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011289 Value *Idx[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011290 Idx[0] = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011291 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011292 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011293 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohman17f46f72009-07-28 01:40:03 +000011294 if (cast<GEPOperator>(&GEP)->isInBounds())
11295 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011296 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11297 // The NewGEP must be pointer typed, so must the old one -> BitCast
11298 return new BitCastInst(NewGEP, GEP.getType());
11299 }
11300 }
11301 }
11302 }
Chris Lattner111ea772009-01-09 04:53:57 +000011303
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011304 /// See if we can simplify:
11305 /// X = bitcast A to B*
11306 /// Y = gep X, <...constant indices...>
11307 /// into a gep of the original struct. This is important for SROA and alias
11308 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011309 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011310 if (TD &&
11311 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011312 // Determine how much the GEP moves the pointer. We are guaranteed to get
11313 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011314 ConstantInt *OffsetV =
11315 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011316 int64_t Offset = OffsetV->getSExtValue();
11317
11318 // If this GEP instruction doesn't move the pointer, just replace the GEP
11319 // with a bitcast of the real input to the dest type.
11320 if (Offset == 0) {
11321 // If the bitcast is of an allocation, and the allocation will be
11322 // converted to match the type of the cast, don't touch this.
11323 if (isa<AllocationInst>(BCI->getOperand(0))) {
11324 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11325 if (Instruction *I = visitBitCast(*BCI)) {
11326 if (I != BCI) {
11327 I->takeName(BCI);
11328 BCI->getParent()->getInstList().insert(BCI, I);
11329 ReplaceInstUsesWith(*BCI, I);
11330 }
11331 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011332 }
Chris Lattner111ea772009-01-09 04:53:57 +000011333 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011334 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011335 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011336
11337 // Otherwise, if the offset is non-zero, we need to find out if there is a
11338 // field at Offset in 'A's type. If so, we can pull the cast through the
11339 // GEP.
11340 SmallVector<Value*, 8> NewIndices;
11341 const Type *InTy =
11342 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011343 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011344 Instruction *NGEP =
11345 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11346 NewIndices.end());
11347 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohman17f46f72009-07-28 01:40:03 +000011348 if (cast<GEPOperator>(&GEP)->isInBounds())
11349 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011350 InsertNewInstBefore(NGEP, GEP);
11351 NGEP->takeName(&GEP);
11352 return new BitCastInst(NGEP, GEP.getType());
11353 }
Chris Lattner111ea772009-01-09 04:53:57 +000011354 }
11355 }
11356
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011357 return 0;
11358}
11359
11360Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11361 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011362 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011363 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11364 const Type *NewTy =
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011365 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011366 AllocationInst *New = 0;
11367
11368 // Create and insert the replacement instruction...
11369 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +000011370 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011371 else {
11372 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson140166d2009-07-15 23:53:25 +000011373 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011374 }
11375
11376 InsertNewInstBefore(New, AI);
11377
11378 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011379 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011380 //
11381 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011382 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011383
11384 // Now that I is pointing to the first non-allocation-inst in the block,
11385 // insert our getelementptr instruction...
11386 //
Owen Andersonaac28372009-07-31 20:28:14 +000011387 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011388 Value *Idx[2];
11389 Idx[0] = NullIdx;
11390 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011391 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11392 New->getName()+".sub", It);
Dan Gohman17f46f72009-07-28 01:40:03 +000011393 cast<GEPOperator>(V)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011394
11395 // Now make everything use the getelementptr instead of the original
11396 // allocation.
11397 return ReplaceInstUsesWith(AI, V);
11398 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersonaac28372009-07-31 20:28:14 +000011399 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011400 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011401 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011402
Dan Gohmana80e2712009-07-21 23:21:54 +000011403 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011404 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011405 // Note that we only do this for alloca's, because malloc should allocate
11406 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011407 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersonaac28372009-07-31 20:28:14 +000011408 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011409
11410 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11411 if (AI.getAlignment() == 0)
11412 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11413 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011414
11415 return 0;
11416}
11417
11418Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11419 Value *Op = FI.getOperand(0);
11420
11421 // free undef -> unreachable.
11422 if (isa<UndefValue>(Op)) {
11423 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson4f720fa2009-07-31 17:39:07 +000011424 new StoreInst(ConstantInt::getTrue(*Context),
Owen Andersonb99ecca2009-07-30 23:03:37 +000011425 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011426 return EraseInstFromFunction(FI);
11427 }
11428
11429 // If we have 'free null' delete the instruction. This can happen in stl code
11430 // when lots of inlining happens.
11431 if (isa<ConstantPointerNull>(Op))
11432 return EraseInstFromFunction(FI);
11433
11434 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11435 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11436 FI.setOperand(0, CI->getOperand(0));
11437 return &FI;
11438 }
11439
11440 // Change free (gep X, 0,0,0,0) into free(X)
11441 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11442 if (GEPI->hasAllZeroIndices()) {
11443 AddToWorkList(GEPI);
11444 FI.setOperand(0, GEPI->getOperand(0));
11445 return &FI;
11446 }
11447 }
11448
11449 // Change free(malloc) into nothing, if the malloc has a single use.
11450 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11451 if (MI->hasOneUse()) {
11452 EraseInstFromFunction(FI);
11453 return EraseInstFromFunction(*MI);
11454 }
11455
11456 return 0;
11457}
11458
11459
11460/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011461static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011462 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011463 User *CI = cast<User>(LI.getOperand(0));
11464 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011465 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011466
Nick Lewycky291c5942009-05-08 06:47:37 +000011467 if (TD) {
11468 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11469 // Instead of loading constant c string, use corresponding integer value
11470 // directly if string length is small enough.
11471 std::string Str;
11472 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11473 unsigned len = Str.length();
11474 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11475 unsigned numBits = Ty->getPrimitiveSizeInBits();
11476 // Replace LI with immediate integer store.
11477 if ((numBits >> 3) == len + 1) {
11478 APInt StrVal(numBits, 0);
11479 APInt SingleChar(numBits, 0);
11480 if (TD->isLittleEndian()) {
11481 for (signed i = len-1; i >= 0; i--) {
11482 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11483 StrVal = (StrVal << 8) | SingleChar;
11484 }
11485 } else {
11486 for (unsigned i = 0; i < len; i++) {
11487 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11488 StrVal = (StrVal << 8) | SingleChar;
11489 }
11490 // Append NULL at the end.
11491 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011492 StrVal = (StrVal << 8) | SingleChar;
11493 }
Owen Andersoneacb44d2009-07-24 23:12:02 +000011494 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011495 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011496 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011497 }
11498 }
11499 }
11500
Mon P Wangbd05ed82009-02-07 22:19:29 +000011501 const PointerType *DestTy = cast<PointerType>(CI->getType());
11502 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011503 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011504
11505 // If the address spaces don't match, don't eliminate the cast.
11506 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11507 return 0;
11508
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011509 const Type *SrcPTy = SrcTy->getElementType();
11510
11511 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11512 isa<VectorType>(DestPTy)) {
11513 // If the source is an array, the code below will not succeed. Check to
11514 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11515 // constants.
11516 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11517 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11518 if (ASrcTy->getNumElements() != 0) {
11519 Value *Idxs[2];
Owen Andersonaac28372009-07-31 20:28:14 +000011520 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
Owen Anderson02b48c32009-07-29 18:55:55 +000011521 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011522 SrcTy = cast<PointerType>(CastOp->getType());
11523 SrcPTy = SrcTy->getElementType();
11524 }
11525
Dan Gohmana80e2712009-07-21 23:21:54 +000011526 if (IC.getTargetData() &&
11527 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011528 isa<VectorType>(SrcPTy)) &&
11529 // Do not allow turning this into a load of an integer, which is then
11530 // casted to a pointer, this pessimizes pointer analysis a lot.
11531 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011532 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11533 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011534
11535 // Okay, we are casting from one integer or pointer type to another of
11536 // the same size. Instead of casting the pointer before the load, cast
11537 // the result of the loaded value.
11538 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11539 CI->getName(),
11540 LI.isVolatile()),LI);
11541 // Now cast the result of the load.
11542 return new BitCastInst(NewLoad, LI.getType());
11543 }
11544 }
11545 }
11546 return 0;
11547}
11548
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011549Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11550 Value *Op = LI.getOperand(0);
11551
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011552 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011553 if (TD) {
11554 unsigned KnownAlign =
11555 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11556 if (KnownAlign >
11557 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11558 LI.getAlignment()))
11559 LI.setAlignment(KnownAlign);
11560 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011561
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011562 // load (cast X) --> cast (load X) iff safe
11563 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011564 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011565 return Res;
11566
11567 // None of the following transforms are legal for volatile loads.
11568 if (LI.isVolatile()) return 0;
11569
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011570 // Do really simple store-to-load forwarding and load CSE, to catch cases
11571 // where there are several consequtive memory accesses to the same location,
11572 // separated by a few arithmetic operations.
11573 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011574 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11575 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011576
Christopher Lamb2c175392007-12-29 07:56:53 +000011577 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11578 const Value *GEPI0 = GEPI->getOperand(0);
11579 // TODO: Consider a target hook for valid address spaces for this xform.
11580 if (isa<ConstantPointerNull>(GEPI0) &&
11581 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011582 // Insert a new store to null instruction before the load to indicate
11583 // that this code is not reachable. We do this instead of inserting
11584 // an unreachable instruction directly because we cannot modify the
11585 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011586 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011587 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011588 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011589 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011590 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011591
11592 if (Constant *C = dyn_cast<Constant>(Op)) {
11593 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011594 // TODO: Consider a target hook for valid address spaces for this xform.
11595 if (isa<UndefValue>(C) || (C->isNullValue() &&
11596 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011597 // Insert a new store to null instruction before the load to indicate that
11598 // this code is not reachable. We do this instead of inserting an
11599 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011600 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011601 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011602 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011603 }
11604
11605 // Instcombine load (constant global) into the value loaded.
11606 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011607 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011608 return ReplaceInstUsesWith(LI, GV->getInitializer());
11609
11610 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011611 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011612 if (CE->getOpcode() == Instruction::GetElementPtr) {
11613 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011614 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011615 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011616 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Anderson175b6542009-07-22 00:24:57 +000011617 *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011618 return ReplaceInstUsesWith(LI, V);
11619 if (CE->getOperand(0)->isNullValue()) {
11620 // Insert a new store to null instruction before the load to indicate
11621 // that this code is not reachable. We do this instead of inserting
11622 // an unreachable instruction directly because we cannot modify the
11623 // CFG.
Owen Andersonb99ecca2009-07-30 23:03:37 +000011624 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersonaac28372009-07-31 20:28:14 +000011625 Constant::getNullValue(Op->getType()), &LI);
Owen Andersonb99ecca2009-07-30 23:03:37 +000011626 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011627 }
11628
11629 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011630 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011631 return Res;
11632 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011633 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011634 }
Chris Lattner0270a112007-08-11 18:48:48 +000011635
11636 // If this load comes from anywhere in a constant global, and if the global
11637 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011638 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011639 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011640 if (GV->getInitializer()->isNullValue())
Owen Andersonaac28372009-07-31 20:28:14 +000011641 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011642 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersonb99ecca2009-07-30 23:03:37 +000011643 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011644 }
11645 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011646
11647 if (Op->hasOneUse()) {
11648 // Change select and PHI nodes to select values instead of addresses: this
11649 // helps alias analysis out a lot, allows many others simplifications, and
11650 // exposes redundancy in the code.
11651 //
11652 // Note that we cannot do the transformation unless we know that the
11653 // introduced loads cannot trap! Something like this is valid as long as
11654 // the condition is always false: load (select bool %C, int* null, int* %G),
11655 // but it would not be valid if we transformed it to load from null
11656 // unconditionally.
11657 //
11658 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11659 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11660 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11661 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11662 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11663 SI->getOperand(1)->getName()+".val"), LI);
11664 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11665 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011666 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011667 }
11668
11669 // load (select (cond, null, P)) -> load P
11670 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11671 if (C->isNullValue()) {
11672 LI.setOperand(0, SI->getOperand(2));
11673 return &LI;
11674 }
11675
11676 // load (select (cond, P, null)) -> load P
11677 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11678 if (C->isNullValue()) {
11679 LI.setOperand(0, SI->getOperand(1));
11680 return &LI;
11681 }
11682 }
11683 }
11684 return 0;
11685}
11686
11687/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011688/// when possible. This makes it generally easy to do alias analysis and/or
11689/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011690static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11691 User *CI = cast<User>(SI.getOperand(1));
11692 Value *CastOp = CI->getOperand(0);
11693
11694 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011695 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11696 if (SrcTy == 0) return 0;
11697
11698 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011699
Chris Lattnera032c0e2009-01-16 20:08:59 +000011700 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11701 return 0;
11702
Chris Lattner54dddc72009-01-24 01:00:13 +000011703 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11704 /// to its first element. This allows us to handle things like:
11705 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11706 /// on 32-bit hosts.
11707 SmallVector<Value*, 4> NewGEPIndices;
11708
Chris Lattnera032c0e2009-01-16 20:08:59 +000011709 // If the source is an array, the code below will not succeed. Check to
11710 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11711 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011712 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11713 // Index through pointer.
Owen Andersonaac28372009-07-31 20:28:14 +000011714 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
Chris Lattner54dddc72009-01-24 01:00:13 +000011715 NewGEPIndices.push_back(Zero);
11716
11717 while (1) {
11718 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011719 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011720 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011721 NewGEPIndices.push_back(Zero);
11722 SrcPTy = STy->getElementType(0);
11723 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11724 NewGEPIndices.push_back(Zero);
11725 SrcPTy = ATy->getElementType();
11726 } else {
11727 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011728 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011729 }
11730
Owen Anderson6b6e2d92009-07-29 22:17:13 +000011731 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011732 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011733
11734 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11735 return 0;
11736
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011737 // If the pointers point into different address spaces or if they point to
11738 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011739 if (!IC.getTargetData() ||
11740 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011741 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011742 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11743 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011744 return 0;
11745
11746 // Okay, we are casting from one integer or pointer type to another of
11747 // the same size. Instead of casting the pointer before
11748 // the store, cast the value to be stored.
11749 Value *NewCast;
11750 Value *SIOp0 = SI.getOperand(0);
11751 Instruction::CastOps opcode = Instruction::BitCast;
11752 const Type* CastSrcTy = SIOp0->getType();
11753 const Type* CastDstTy = SrcPTy;
11754 if (isa<PointerType>(CastDstTy)) {
11755 if (CastSrcTy->isInteger())
11756 opcode = Instruction::IntToPtr;
11757 } else if (isa<IntegerType>(CastDstTy)) {
11758 if (isa<PointerType>(SIOp0->getType()))
11759 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011760 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011761
11762 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11763 // emit a GEP to index into its first field.
11764 if (!NewGEPIndices.empty()) {
11765 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Anderson02b48c32009-07-29 18:55:55 +000011766 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner54dddc72009-01-24 01:00:13 +000011767 NewGEPIndices.size());
11768 else
11769 CastOp = IC.InsertNewInstBefore(
11770 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11771 NewGEPIndices.end()), SI);
Dan Gohman17f46f72009-07-28 01:40:03 +000011772 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner54dddc72009-01-24 01:00:13 +000011773 }
11774
Chris Lattnera032c0e2009-01-16 20:08:59 +000011775 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Anderson02b48c32009-07-29 18:55:55 +000011776 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnera032c0e2009-01-16 20:08:59 +000011777 else
11778 NewCast = IC.InsertNewInstBefore(
11779 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11780 SI);
11781 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011782}
11783
Chris Lattner6fd8c802008-11-27 08:56:30 +000011784/// equivalentAddressValues - Test if A and B will obviously have the same
11785/// value. This includes recognizing that %t0 and %t1 will have the same
11786/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011787/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011788/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011789/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011790/// %t2 = load i32* %t1
11791///
11792static bool equivalentAddressValues(Value *A, Value *B) {
11793 // Test if the values are trivially equivalent.
11794 if (A == B) return true;
11795
11796 // Test if the values come form identical arithmetic instructions.
11797 if (isa<BinaryOperator>(A) ||
11798 isa<CastInst>(A) ||
11799 isa<PHINode>(A) ||
11800 isa<GetElementPtrInst>(A))
11801 if (Instruction *BI = dyn_cast<Instruction>(B))
11802 if (cast<Instruction>(A)->isIdenticalTo(BI))
11803 return true;
11804
11805 // Otherwise they may not be equivalent.
11806 return false;
11807}
11808
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011809// If this instruction has two uses, one of which is a llvm.dbg.declare,
11810// return the llvm.dbg.declare.
11811DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11812 if (!V->hasNUses(2))
11813 return 0;
11814 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11815 UI != E; ++UI) {
11816 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11817 return DI;
11818 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11819 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11820 return DI;
11821 }
11822 }
11823 return 0;
11824}
11825
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011826Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11827 Value *Val = SI.getOperand(0);
11828 Value *Ptr = SI.getOperand(1);
11829
11830 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11831 EraseInstFromFunction(SI);
11832 ++NumCombined;
11833 return 0;
11834 }
11835
11836 // If the RHS is an alloca with a single use, zapify the store, making the
11837 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011838 // If the RHS is an alloca with a two uses, the other one being a
11839 // llvm.dbg.declare, zapify the store and the declare, making the
11840 // alloca dead. We must do this to prevent declare's from affecting
11841 // codegen.
11842 if (!SI.isVolatile()) {
11843 if (Ptr->hasOneUse()) {
11844 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011845 EraseInstFromFunction(SI);
11846 ++NumCombined;
11847 return 0;
11848 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011849 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11850 if (isa<AllocaInst>(GEP->getOperand(0))) {
11851 if (GEP->getOperand(0)->hasOneUse()) {
11852 EraseInstFromFunction(SI);
11853 ++NumCombined;
11854 return 0;
11855 }
11856 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11857 EraseInstFromFunction(*DI);
11858 EraseInstFromFunction(SI);
11859 ++NumCombined;
11860 return 0;
11861 }
11862 }
11863 }
11864 }
11865 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11866 EraseInstFromFunction(*DI);
11867 EraseInstFromFunction(SI);
11868 ++NumCombined;
11869 return 0;
11870 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011871 }
11872
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011873 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011874 if (TD) {
11875 unsigned KnownAlign =
11876 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11877 if (KnownAlign >
11878 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11879 SI.getAlignment()))
11880 SI.setAlignment(KnownAlign);
11881 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011882
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011883 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011884 // stores to the same location, separated by a few arithmetic operations. This
11885 // situation often occurs with bitfield accesses.
11886 BasicBlock::iterator BBI = &SI;
11887 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11888 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011889 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011890 // Don't count debug info directives, lest they affect codegen,
11891 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11892 // It is necessary for correctness to skip those that feed into a
11893 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011894 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011895 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011896 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011897 continue;
11898 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011899
11900 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11901 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011902 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11903 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011904 ++NumDeadStore;
11905 ++BBI;
11906 EraseInstFromFunction(*PrevSI);
11907 continue;
11908 }
11909 break;
11910 }
11911
11912 // If this is a load, we have to stop. However, if the loaded value is from
11913 // the pointer we're loading and is producing the pointer we're storing,
11914 // then *this* store is dead (X = load P; store X -> P).
11915 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011916 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11917 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011918 EraseInstFromFunction(SI);
11919 ++NumCombined;
11920 return 0;
11921 }
11922 // Otherwise, this is a load from some other location. Stores before it
11923 // may not be dead.
11924 break;
11925 }
11926
11927 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011928 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011929 break;
11930 }
11931
11932
11933 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11934
11935 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011936 if (isa<ConstantPointerNull>(Ptr) &&
11937 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011938 if (!isa<UndefValue>(Val)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000011939 SI.setOperand(0, UndefValue::get(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011940 if (Instruction *U = dyn_cast<Instruction>(Val))
11941 AddToWorkList(U); // Dropped a use.
11942 ++NumCombined;
11943 }
11944 return 0; // Do not modify these!
11945 }
11946
11947 // store undef, Ptr -> noop
11948 if (isa<UndefValue>(Val)) {
11949 EraseInstFromFunction(SI);
11950 ++NumCombined;
11951 return 0;
11952 }
11953
11954 // If the pointer destination is a cast, see if we can fold the cast into the
11955 // source instead.
11956 if (isa<CastInst>(Ptr))
11957 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11958 return Res;
11959 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11960 if (CE->isCast())
11961 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11962 return Res;
11963
11964
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011965 // If this store is the last instruction in the basic block (possibly
11966 // excepting debug info instructions and the pointer bitcasts that feed
11967 // into them), and if the block ends with an unconditional branch, try
11968 // to move it to the successor block.
11969 BBI = &SI;
11970 do {
11971 ++BBI;
11972 } while (isa<DbgInfoIntrinsic>(BBI) ||
11973 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011974 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11975 if (BI->isUnconditional())
11976 if (SimplifyStoreAtEndOfBlock(SI))
11977 return 0; // xform done!
11978
11979 return 0;
11980}
11981
11982/// SimplifyStoreAtEndOfBlock - Turn things like:
11983/// if () { *P = v1; } else { *P = v2 }
11984/// into a phi node with a store in the successor.
11985///
11986/// Simplify things like:
11987/// *P = v1; if () { *P = v2; }
11988/// into a phi node with a store in the successor.
11989///
11990bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11991 BasicBlock *StoreBB = SI.getParent();
11992
11993 // Check to see if the successor block has exactly two incoming edges. If
11994 // so, see if the other predecessor contains a store to the same location.
11995 // if so, insert a PHI node (if needed) and move the stores down.
11996 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11997
11998 // Determine whether Dest has exactly two predecessors and, if so, compute
11999 // the other predecessor.
12000 pred_iterator PI = pred_begin(DestBB);
12001 BasicBlock *OtherBB = 0;
12002 if (*PI != StoreBB)
12003 OtherBB = *PI;
12004 ++PI;
12005 if (PI == pred_end(DestBB))
12006 return false;
12007
12008 if (*PI != StoreBB) {
12009 if (OtherBB)
12010 return false;
12011 OtherBB = *PI;
12012 }
12013 if (++PI != pred_end(DestBB))
12014 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012015
12016 // Bail out if all the relevant blocks aren't distinct (this can happen,
12017 // for example, if SI is in an infinite loop)
12018 if (StoreBB == DestBB || OtherBB == DestBB)
12019 return false;
12020
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012021 // Verify that the other block ends in a branch and is not otherwise empty.
12022 BasicBlock::iterator BBI = OtherBB->getTerminator();
12023 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12024 if (!OtherBr || BBI == OtherBB->begin())
12025 return false;
12026
12027 // If the other block ends in an unconditional branch, check for the 'if then
12028 // else' case. there is an instruction before the branch.
12029 StoreInst *OtherStore = 0;
12030 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012031 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012032 // Skip over debugging info.
12033 while (isa<DbgInfoIntrinsic>(BBI) ||
12034 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12035 if (BBI==OtherBB->begin())
12036 return false;
12037 --BBI;
12038 }
12039 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012040 OtherStore = dyn_cast<StoreInst>(BBI);
12041 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12042 return false;
12043 } else {
12044 // Otherwise, the other block ended with a conditional branch. If one of the
12045 // destinations is StoreBB, then we have the if/then case.
12046 if (OtherBr->getSuccessor(0) != StoreBB &&
12047 OtherBr->getSuccessor(1) != StoreBB)
12048 return false;
12049
12050 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12051 // if/then triangle. See if there is a store to the same ptr as SI that
12052 // lives in OtherBB.
12053 for (;; --BBI) {
12054 // Check to see if we find the matching store.
12055 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12056 if (OtherStore->getOperand(1) != SI.getOperand(1))
12057 return false;
12058 break;
12059 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012060 // If we find something that may be using or overwriting the stored
12061 // value, or if we run out of instructions, we can't do the xform.
12062 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012063 BBI == OtherBB->begin())
12064 return false;
12065 }
12066
12067 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012068 // make sure nothing reads or overwrites the stored value in
12069 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012070 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12071 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012072 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012073 return false;
12074 }
12075 }
12076
12077 // Insert a PHI node now if we need it.
12078 Value *MergedVal = OtherStore->getOperand(0);
12079 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012080 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012081 PN->reserveOperandSpace(2);
12082 PN->addIncoming(SI.getOperand(0), SI.getParent());
12083 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12084 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12085 }
12086
12087 // Advance to a place where it is safe to insert the new store and
12088 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012089 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012090 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12091 OtherStore->isVolatile()), *BBI);
12092
12093 // Nuke the old stores.
12094 EraseInstFromFunction(SI);
12095 EraseInstFromFunction(*OtherStore);
12096 ++NumCombined;
12097 return true;
12098}
12099
12100
12101Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12102 // Change br (not X), label True, label False to: br X, label False, True
12103 Value *X = 0;
12104 BasicBlock *TrueDest;
12105 BasicBlock *FalseDest;
Owen Andersona21eb582009-07-10 17:35:01 +000012106 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012107 !isa<Constant>(X)) {
12108 // Swap Destinations and condition...
12109 BI.setCondition(X);
12110 BI.setSuccessor(0, FalseDest);
12111 BI.setSuccessor(1, TrueDest);
12112 return &BI;
12113 }
12114
12115 // Cannonicalize fcmp_one -> fcmp_oeq
12116 FCmpInst::Predicate FPred; Value *Y;
12117 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersona21eb582009-07-10 17:35:01 +000012118 TrueDest, FalseDest), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012119 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12120 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12121 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12122 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012123 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012124 NewSCC->takeName(I);
12125 // Swap Destinations and condition...
12126 BI.setCondition(NewSCC);
12127 BI.setSuccessor(0, FalseDest);
12128 BI.setSuccessor(1, TrueDest);
12129 RemoveFromWorkList(I);
12130 I->eraseFromParent();
12131 AddToWorkList(NewSCC);
12132 return &BI;
12133 }
12134
12135 // Cannonicalize icmp_ne -> icmp_eq
12136 ICmpInst::Predicate IPred;
12137 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersona21eb582009-07-10 17:35:01 +000012138 TrueDest, FalseDest), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012139 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12140 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12141 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12142 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12143 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012144 Instruction *NewSCC = new ICmpInst(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 return 0;
12157}
12158
12159Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12160 Value *Cond = SI.getCondition();
12161 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12162 if (I->getOpcode() == Instruction::Add)
12163 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12164 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12165 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012166 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +000012167 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012168 AddRHS));
12169 SI.setOperand(0, I->getOperand(0));
12170 AddToWorkList(I);
12171 return &SI;
12172 }
12173 }
12174 return 0;
12175}
12176
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012177Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012178 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012179
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012180 if (!EV.hasIndices())
12181 return ReplaceInstUsesWith(EV, Agg);
12182
12183 if (Constant *C = dyn_cast<Constant>(Agg)) {
12184 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012185 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012186
12187 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +000012188 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012189
12190 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12191 // Extract the element indexed by the first index out of the constant
12192 Value *V = C->getOperand(*EV.idx_begin());
12193 if (EV.getNumIndices() > 1)
12194 // Extract the remaining indices out of the constant indexed by the
12195 // first index
12196 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12197 else
12198 return ReplaceInstUsesWith(EV, V);
12199 }
12200 return 0; // Can't handle other constants
12201 }
12202 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12203 // We're extracting from an insertvalue instruction, compare the indices
12204 const unsigned *exti, *exte, *insi, *inse;
12205 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12206 exte = EV.idx_end(), inse = IV->idx_end();
12207 exti != exte && insi != inse;
12208 ++exti, ++insi) {
12209 if (*insi != *exti)
12210 // The insert and extract both reference distinctly different elements.
12211 // This means the extract is not influenced by the insert, and we can
12212 // replace the aggregate operand of the extract with the aggregate
12213 // operand of the insert. i.e., replace
12214 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12215 // %E = extractvalue { i32, { i32 } } %I, 0
12216 // with
12217 // %E = extractvalue { i32, { i32 } } %A, 0
12218 return ExtractValueInst::Create(IV->getAggregateOperand(),
12219 EV.idx_begin(), EV.idx_end());
12220 }
12221 if (exti == exte && insi == inse)
12222 // Both iterators are at the end: Index lists are identical. Replace
12223 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12224 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12225 // with "i32 42"
12226 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12227 if (exti == exte) {
12228 // The extract list is a prefix of the insert list. i.e. replace
12229 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12230 // %E = extractvalue { i32, { i32 } } %I, 1
12231 // with
12232 // %X = extractvalue { i32, { i32 } } %A, 1
12233 // %E = insertvalue { i32 } %X, i32 42, 0
12234 // by switching the order of the insert and extract (though the
12235 // insertvalue should be left in, since it may have other uses).
12236 Value *NewEV = InsertNewInstBefore(
12237 ExtractValueInst::Create(IV->getAggregateOperand(),
12238 EV.idx_begin(), EV.idx_end()),
12239 EV);
12240 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12241 insi, inse);
12242 }
12243 if (insi == inse)
12244 // The insert list is a prefix of the extract list
12245 // We can simply remove the common indices from the extract and make it
12246 // operate on the inserted value instead of the insertvalue result.
12247 // i.e., replace
12248 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12249 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12250 // with
12251 // %E extractvalue { i32 } { i32 42 }, 0
12252 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12253 exti, exte);
12254 }
12255 // Can't simplify extracts from other values. Note that nested extracts are
12256 // already simplified implicitely by the above (extract ( extract (insert) )
12257 // will be translated into extract ( insert ( extract ) ) first and then just
12258 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012259 return 0;
12260}
12261
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012262/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12263/// is to leave as a vector operation.
12264static bool CheapToScalarize(Value *V, bool isConstant) {
12265 if (isa<ConstantAggregateZero>(V))
12266 return true;
12267 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12268 if (isConstant) return true;
12269 // If all elts are the same, we can extract.
12270 Constant *Op0 = C->getOperand(0);
12271 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12272 if (C->getOperand(i) != Op0)
12273 return false;
12274 return true;
12275 }
12276 Instruction *I = dyn_cast<Instruction>(V);
12277 if (!I) return false;
12278
12279 // Insert element gets simplified to the inserted element or is deleted if
12280 // this is constant idx extract element and its a constant idx insertelt.
12281 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12282 isa<ConstantInt>(I->getOperand(2)))
12283 return true;
12284 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12285 return true;
12286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12287 if (BO->hasOneUse() &&
12288 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12289 CheapToScalarize(BO->getOperand(1), isConstant)))
12290 return true;
12291 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12292 if (CI->hasOneUse() &&
12293 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12294 CheapToScalarize(CI->getOperand(1), isConstant)))
12295 return true;
12296
12297 return false;
12298}
12299
12300/// Read and decode a shufflevector mask.
12301///
12302/// It turns undef elements into values that are larger than the number of
12303/// elements in the input.
12304static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12305 unsigned NElts = SVI->getType()->getNumElements();
12306 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12307 return std::vector<unsigned>(NElts, 0);
12308 if (isa<UndefValue>(SVI->getOperand(2)))
12309 return std::vector<unsigned>(NElts, 2*NElts);
12310
12311 std::vector<unsigned> Result;
12312 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012313 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12314 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012315 Result.push_back(NElts*2); // undef -> 8
12316 else
Gabor Greif17396002008-06-12 21:37:33 +000012317 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012318 return Result;
12319}
12320
12321/// FindScalarElement - Given a vector and an element number, see if the scalar
12322/// value is already around as a register, for example if it were inserted then
12323/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012324static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012325 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012326 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12327 const VectorType *PTy = cast<VectorType>(V->getType());
12328 unsigned Width = PTy->getNumElements();
12329 if (EltNo >= Width) // Out of range access.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012330 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012331
12332 if (isa<UndefValue>(V))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012333 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012334 else if (isa<ConstantAggregateZero>(V))
Owen Andersonaac28372009-07-31 20:28:14 +000012335 return Constant::getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012336 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12337 return CP->getOperand(EltNo);
12338 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12339 // If this is an insert to a variable element, we don't know what it is.
12340 if (!isa<ConstantInt>(III->getOperand(2)))
12341 return 0;
12342 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12343
12344 // If this is an insert to the element we are looking for, return the
12345 // inserted value.
12346 if (EltNo == IIElt)
12347 return III->getOperand(1);
12348
12349 // Otherwise, the insertelement doesn't modify the value, recurse on its
12350 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012351 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012352 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012353 unsigned LHSWidth =
12354 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012355 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012356 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012357 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012358 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012359 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012360 else
Owen Andersonb99ecca2009-07-30 23:03:37 +000012361 return UndefValue::get(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012362 }
12363
12364 // Otherwise, we don't know.
12365 return 0;
12366}
12367
12368Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012369 // If vector val is undef, replace extract with scalar undef.
12370 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012371 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012372
12373 // If vector val is constant 0, replace extract with scalar 0.
12374 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersonaac28372009-07-31 20:28:14 +000012375 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012376
12377 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012378 // If vector val is constant with all elements the same, replace EI with
12379 // that element. When the elements are not identical, we cannot replace yet
12380 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012381 Constant *op0 = C->getOperand(0);
12382 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12383 if (C->getOperand(i) != op0) {
12384 op0 = 0;
12385 break;
12386 }
12387 if (op0)
12388 return ReplaceInstUsesWith(EI, op0);
12389 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012390
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012391 // If extracting a specified index from the vector, see if we can recursively
12392 // find a previously computed scalar that was inserted into the vector.
12393 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12394 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedmanf34209b2009-07-18 19:04:16 +000012395 unsigned VectorWidth =
12396 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012397
12398 // If this is extracting an invalid index, turn this into undef, to avoid
12399 // crashing the code below.
12400 if (IndexVal >= VectorWidth)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012401 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012402
12403 // This instruction only demands the single element from the input vector.
12404 // If the input vector has a single use, simplify it based on this use
12405 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012406 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012407 APInt UndefElts(VectorWidth, 0);
12408 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012409 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012410 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012411 EI.setOperand(0, V);
12412 return &EI;
12413 }
12414 }
12415
Owen Anderson24be4c12009-07-03 00:17:18 +000012416 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012417 return ReplaceInstUsesWith(EI, Elt);
12418
12419 // If the this extractelement is directly using a bitcast from a vector of
12420 // the same number of elements, see if we can find the source element from
12421 // it. In this case, we will end up needing to bitcast the scalars.
12422 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12423 if (const VectorType *VT =
12424 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12425 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012426 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12427 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012428 return new BitCastInst(Elt, EI.getType());
12429 }
12430 }
12431
12432 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12433 if (I->hasOneUse()) {
12434 // Push extractelement into predecessor operation if legal and
12435 // profitable to do so
12436 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12437 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12438 if (CheapToScalarize(BO, isConstantElt)) {
12439 ExtractElementInst *newEI0 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012440 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012441 EI.getName()+".lhs");
12442 ExtractElementInst *newEI1 =
Eric Christopher1ba36872009-07-25 02:28:41 +000012443 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012444 EI.getName()+".rhs");
12445 InsertNewInstBefore(newEI0, EI);
12446 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012447 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012448 }
12449 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012450 unsigned AS =
12451 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012452 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Anderson6b6e2d92009-07-29 22:17:13 +000012453 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012454 GetElementPtrInst *GEP =
12455 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohman17f46f72009-07-28 01:40:03 +000012456 cast<GEPOperator>(GEP)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012457 InsertNewInstBefore(GEP, EI);
12458 return new LoadInst(GEP);
12459 }
12460 }
12461 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12462 // Extracting the inserted element?
12463 if (IE->getOperand(2) == EI.getOperand(1))
12464 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12465 // If the inserted and extracted elements are constants, they must not
12466 // be the same value, extract from the pre-inserted value instead.
12467 if (isa<Constant>(IE->getOperand(2)) &&
12468 isa<Constant>(EI.getOperand(1))) {
12469 AddUsesToWorkList(EI);
12470 EI.setOperand(0, IE->getOperand(0));
12471 return &EI;
12472 }
12473 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12474 // If this is extracting an element from a shufflevector, figure out where
12475 // it came from and extract from the appropriate input element instead.
12476 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12477 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12478 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012479 unsigned LHSWidth =
12480 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12481
12482 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012483 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012484 else if (SrcIdx < LHSWidth*2) {
12485 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012486 Src = SVI->getOperand(1);
12487 } else {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012488 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012489 }
Eric Christopher1ba36872009-07-25 02:28:41 +000012490 return ExtractElementInst::Create(Src,
Owen Andersoneacb44d2009-07-24 23:12:02 +000012491 ConstantInt::get(Type::Int32Ty, SrcIdx, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012492 }
12493 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012494 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012495 }
12496 return 0;
12497}
12498
12499/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12500/// elements from either LHS or RHS, return the shuffle mask and true.
12501/// Otherwise, return false.
12502static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012503 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012504 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012505 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12506 "Invalid CollectSingleShuffleElements");
12507 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12508
12509 if (isa<UndefValue>(V)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012510 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012511 return true;
12512 } else if (V == LHS) {
12513 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012514 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012515 return true;
12516 } else if (V == RHS) {
12517 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012518 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012519 return true;
12520 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12521 // If this is an insert of an extract from some other vector, include it.
12522 Value *VecOp = IEI->getOperand(0);
12523 Value *ScalarOp = IEI->getOperand(1);
12524 Value *IdxOp = IEI->getOperand(2);
12525
12526 if (!isa<ConstantInt>(IdxOp))
12527 return false;
12528 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12529
12530 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12531 // Okay, we can handle this if the vector we are insertinting into is
12532 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012533 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012534 // If so, update the mask to reflect the inserted undef.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012535 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012536 return true;
12537 }
12538 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12539 if (isa<ConstantInt>(EI->getOperand(1)) &&
12540 EI->getOperand(0)->getType() == V->getType()) {
12541 unsigned ExtractedIdx =
12542 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12543
12544 // This must be extracting from either LHS or RHS.
12545 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12546 // Okay, we can handle this if the vector we are insertinting into is
12547 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012548 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012549 // If so, update the mask to reflect the inserted value.
12550 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012551 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012552 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012553 } else {
12554 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012555 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012556 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012557
12558 }
12559 return true;
12560 }
12561 }
12562 }
12563 }
12564 }
12565 // TODO: Handle shufflevector here!
12566
12567 return false;
12568}
12569
12570/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12571/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12572/// that computes V and the LHS value of the shuffle.
12573static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012574 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012575 assert(isa<VectorType>(V->getType()) &&
12576 (RHS == 0 || V->getType() == RHS->getType()) &&
12577 "Invalid shuffle!");
12578 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12579
12580 if (isa<UndefValue>(V)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012581 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012582 return V;
12583 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012584 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012585 return V;
12586 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12587 // If this is an insert of an extract from some other vector, include it.
12588 Value *VecOp = IEI->getOperand(0);
12589 Value *ScalarOp = IEI->getOperand(1);
12590 Value *IdxOp = IEI->getOperand(2);
12591
12592 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12593 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12594 EI->getOperand(0)->getType() == V->getType()) {
12595 unsigned ExtractedIdx =
12596 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12597 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12598
12599 // Either the extracted from or inserted into vector must be RHSVec,
12600 // otherwise we'd end up with a shuffle of three inputs.
12601 if (EI->getOperand(0) == RHS || RHS == 0) {
12602 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012603 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012604 Mask[InsertedIdx % NumElts] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012605 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012606 return V;
12607 }
12608
12609 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012610 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12611 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012612 // Everything but the extracted element is replaced with the RHS.
12613 for (unsigned i = 0; i != NumElts; ++i) {
12614 if (i != InsertedIdx)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012615 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012616 }
12617 return V;
12618 }
12619
12620 // If this insertelement is a chain that comes from exactly these two
12621 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012622 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12623 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012624 return EI->getOperand(0);
12625
12626 }
12627 }
12628 }
12629 // TODO: Handle shufflevector here!
12630
12631 // Otherwise, can't do anything fancy. Return an identity vector.
12632 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +000012633 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012634 return V;
12635}
12636
12637Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12638 Value *VecOp = IE.getOperand(0);
12639 Value *ScalarOp = IE.getOperand(1);
12640 Value *IdxOp = IE.getOperand(2);
12641
12642 // Inserting an undef or into an undefined place, remove this.
12643 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12644 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012645
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012646 // If the inserted element was extracted from some other vector, and if the
12647 // indexes are constant, try to turn this into a shufflevector operation.
12648 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12649 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12650 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012651 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012652 unsigned ExtractedIdx =
12653 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12654 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12655
12656 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12657 return ReplaceInstUsesWith(IE, VecOp);
12658
12659 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012660 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012661
12662 // If we are extracting a value from a vector, then inserting it right
12663 // back into the same place, just use the input vector.
12664 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12665 return ReplaceInstUsesWith(IE, VecOp);
12666
12667 // We could theoretically do this for ANY input. However, doing so could
12668 // turn chains of insertelement instructions into a chain of shufflevector
12669 // instructions, and right now we do not merge shufflevectors. As such,
12670 // only do this in a situation where it is clear that there is benefit.
12671 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12672 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12673 // the values of VecOp, except then one read from EIOp0.
12674 // Build a new shuffle mask.
12675 std::vector<Constant*> Mask;
12676 if (isa<UndefValue>(VecOp))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012677 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012678 else {
12679 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersoneacb44d2009-07-24 23:12:02 +000012680 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012681 NumVectorElts));
12682 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012683 Mask[InsertedIdx] =
Owen Andersoneacb44d2009-07-24 23:12:02 +000012684 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012685 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson2f422e02009-07-28 21:19:26 +000012686 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012687 }
12688
12689 // If this insertelement isn't used by some other insertelement, turn it
12690 // (and any insertelements it points to), into one big shuffle.
12691 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12692 std::vector<Constant*> Mask;
12693 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012694 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Andersonb99ecca2009-07-30 23:03:37 +000012695 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012696 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012697 return new ShuffleVectorInst(LHS, RHS,
Owen Anderson2f422e02009-07-28 21:19:26 +000012698 ConstantVector::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012699 }
12700 }
12701 }
12702
Eli Friedmanbefee262009-06-06 20:08:03 +000012703 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12704 APInt UndefElts(VWidth, 0);
12705 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12706 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12707 return &IE;
12708
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012709 return 0;
12710}
12711
12712
12713Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12714 Value *LHS = SVI.getOperand(0);
12715 Value *RHS = SVI.getOperand(1);
12716 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12717
12718 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012719
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012720 // Undefined shuffle mask -> undefined value.
12721 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersonb99ecca2009-07-30 23:03:37 +000012722 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012723
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012724 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012725
12726 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12727 return 0;
12728
Evan Cheng63295ab2009-02-03 10:05:09 +000012729 APInt UndefElts(VWidth, 0);
12730 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12731 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012732 LHS = SVI.getOperand(0);
12733 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012734 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012735 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012736
12737 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12738 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12739 if (LHS == RHS || isa<UndefValue>(LHS)) {
12740 if (isa<UndefValue>(LHS) && LHS == RHS) {
12741 // shuffle(undef,undef,mask) -> undef.
12742 return ReplaceInstUsesWith(SVI, LHS);
12743 }
12744
12745 // Remap any references to RHS to use LHS.
12746 std::vector<Constant*> Elts;
12747 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12748 if (Mask[i] >= 2*e)
Owen Andersonb99ecca2009-07-30 23:03:37 +000012749 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012750 else {
12751 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012752 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012753 Mask[i] = 2*e; // Turn into undef.
Owen Andersonb99ecca2009-07-30 23:03:37 +000012754 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012755 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012756 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersoneacb44d2009-07-24 23:12:02 +000012757 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012758 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012759 }
12760 }
12761 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersonb99ecca2009-07-30 23:03:37 +000012762 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Anderson2f422e02009-07-28 21:19:26 +000012763 SVI.setOperand(2, ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012764 LHS = SVI.getOperand(0);
12765 RHS = SVI.getOperand(1);
12766 MadeChange = true;
12767 }
12768
12769 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12770 bool isLHSID = true, isRHSID = true;
12771
12772 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12773 if (Mask[i] >= e*2) continue; // Ignore undef values.
12774 // Is this an identity shuffle of the LHS value?
12775 isLHSID &= (Mask[i] == i);
12776
12777 // Is this an identity shuffle of the RHS value?
12778 isRHSID &= (Mask[i]-e == i);
12779 }
12780
12781 // Eliminate identity shuffles.
12782 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12783 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12784
12785 // If the LHS is a shufflevector itself, see if we can combine it with this
12786 // one without producing an unusual shuffle. Here we are really conservative:
12787 // we are absolutely afraid of producing a shuffle mask not in the input
12788 // program, because the code gen may not be smart enough to turn a merged
12789 // shuffle into two specific shuffles: it may produce worse code. As such,
12790 // we only merge two shuffles if the result is one of the two input shuffle
12791 // masks. In this case, merging the shuffles just removes one instruction,
12792 // which we know is safe. This is good for things like turning:
12793 // (splat(splat)) -> splat.
12794 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12795 if (isa<UndefValue>(RHS)) {
12796 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12797
12798 std::vector<unsigned> NewMask;
12799 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12800 if (Mask[i] >= 2*e)
12801 NewMask.push_back(2*e);
12802 else
12803 NewMask.push_back(LHSMask[Mask[i]]);
12804
12805 // If the result mask is equal to the src shuffle or this shuffle mask, do
12806 // the replacement.
12807 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012808 unsigned LHSInNElts =
12809 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012810 std::vector<Constant*> Elts;
12811 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012812 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersonb99ecca2009-07-30 23:03:37 +000012813 Elts.push_back(UndefValue::get(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012814 } else {
Owen Andersoneacb44d2009-07-24 23:12:02 +000012815 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012816 }
12817 }
12818 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12819 LHSSVI->getOperand(1),
Owen Anderson2f422e02009-07-28 21:19:26 +000012820 ConstantVector::get(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012821 }
12822 }
12823 }
12824
12825 return MadeChange ? &SVI : 0;
12826}
12827
12828
12829
12830
12831/// TryToSinkInstruction - Try to move the specified instruction from its
12832/// current block into the beginning of DestBlock, which can only happen if it's
12833/// safe to move the instruction past all of the instructions between it and the
12834/// end of its block.
12835static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12836 assert(I->hasOneUse() && "Invariants didn't hold!");
12837
12838 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012839 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012840 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012841
12842 // Do not sink alloca instructions out of the entry block.
12843 if (isa<AllocaInst>(I) && I->getParent() ==
12844 &DestBlock->getParent()->getEntryBlock())
12845 return false;
12846
12847 // We can only sink load instructions if there is nothing between the load and
12848 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012849 if (I->mayReadFromMemory()) {
12850 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012851 Scan != E; ++Scan)
12852 if (Scan->mayWriteToMemory())
12853 return false;
12854 }
12855
Dan Gohman514277c2008-05-23 21:05:58 +000012856 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012857
Dale Johannesen24339f12009-03-03 01:09:07 +000012858 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012859 I->moveBefore(InsertPos);
12860 ++NumSunkInst;
12861 return true;
12862}
12863
12864
12865/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12866/// all reachable code to the worklist.
12867///
12868/// This has a couple of tricks to make the code faster and more powerful. In
12869/// particular, we constant fold and DCE instructions as we go, to avoid adding
12870/// them to the worklist (this significantly speeds up instcombine on code where
12871/// many instructions are dead or constant). Additionally, if we find a branch
12872/// whose condition is a known constant, we only visit the reachable successors.
12873///
12874static void AddReachableCodeToWorklist(BasicBlock *BB,
12875 SmallPtrSet<BasicBlock*, 64> &Visited,
12876 InstCombiner &IC,
12877 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012878 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012879 Worklist.push_back(BB);
12880
12881 while (!Worklist.empty()) {
12882 BB = Worklist.back();
12883 Worklist.pop_back();
12884
12885 // We have now visited this block! If we've already been here, ignore it.
12886 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012887
12888 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012889 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12890 Instruction *Inst = BBI++;
12891
12892 // DCE instruction if trivially dead.
12893 if (isInstructionTriviallyDead(Inst)) {
12894 ++NumDeadInst;
12895 DOUT << "IC: DCE: " << *Inst;
12896 Inst->eraseFromParent();
12897 continue;
12898 }
12899
12900 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012901 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012902 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12903 Inst->replaceAllUsesWith(C);
12904 ++NumConstProp;
12905 Inst->eraseFromParent();
12906 continue;
12907 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012908
Devang Patel794140c2008-11-19 18:56:50 +000012909 // If there are two consecutive llvm.dbg.stoppoint calls then
12910 // it is likely that the optimizer deleted code in between these
12911 // two intrinsics.
12912 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12913 if (DBI_Next) {
12914 if (DBI_Prev
12915 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12916 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12917 IC.RemoveFromWorkList(DBI_Prev);
12918 DBI_Prev->eraseFromParent();
12919 }
12920 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012921 } else {
12922 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012923 }
12924
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012925 IC.AddToWorkList(Inst);
12926 }
12927
12928 // Recursively visit successors. If this is a branch or switch on a
12929 // constant, only visit the reachable successor.
12930 TerminatorInst *TI = BB->getTerminator();
12931 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12932 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12933 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012934 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012935 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012936 continue;
12937 }
12938 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12939 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12940 // See if this is an explicit destination.
12941 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12942 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012943 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012944 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012945 continue;
12946 }
12947
12948 // Otherwise it is the default destination.
12949 Worklist.push_back(SI->getSuccessor(0));
12950 continue;
12951 }
12952 }
12953
12954 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12955 Worklist.push_back(TI->getSuccessor(i));
12956 }
12957}
12958
12959bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12960 bool Changed = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012961 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012962
Daniel Dunbar005975c2009-07-25 00:23:56 +000012963 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12964 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012965
12966 {
12967 // Do a depth-first traversal of the function, populate the worklist with
12968 // the reachable instructions. Ignore blocks that are not reachable. Keep
12969 // track of which blocks we visit.
12970 SmallPtrSet<BasicBlock*, 64> Visited;
12971 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12972
12973 // Do a quick scan over the function. If we find any blocks that are
12974 // unreachable, remove any instructions inside of them. This prevents
12975 // the instcombine code from having to deal with some bad special cases.
12976 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12977 if (!Visited.count(BB)) {
12978 Instruction *Term = BB->getTerminator();
12979 while (Term != BB->begin()) { // Remove instrs bottom-up
12980 BasicBlock::iterator I = Term; --I;
12981
12982 DOUT << "IC: DCE: " << *I;
Dale Johannesendf356c62009-03-10 21:19:49 +000012983 // A debug intrinsic shouldn't force another iteration if we weren't
12984 // going to do one without it.
12985 if (!isa<DbgInfoIntrinsic>(I)) {
12986 ++NumDeadInst;
12987 Changed = true;
12988 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012989 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +000012990 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012991 I->eraseFromParent();
12992 }
12993 }
12994 }
12995
12996 while (!Worklist.empty()) {
12997 Instruction *I = RemoveOneFromWorkList();
12998 if (I == 0) continue; // skip null values.
12999
13000 // Check to see if we can DCE the instruction.
13001 if (isInstructionTriviallyDead(I)) {
13002 // Add operands to the worklist.
13003 if (I->getNumOperands() < 4)
13004 AddUsesToWorkList(*I);
13005 ++NumDeadInst;
13006
13007 DOUT << "IC: DCE: " << *I;
13008
13009 I->eraseFromParent();
13010 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013011 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013012 continue;
13013 }
13014
13015 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000013016 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013017 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13018
13019 // Add operands to the worklist.
13020 AddUsesToWorkList(*I);
13021 ReplaceInstUsesWith(*I, C);
13022
13023 ++NumConstProp;
13024 I->eraseFromParent();
13025 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013026 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013027 continue;
13028 }
13029
Eli Friedman5c619182009-07-15 22:13:34 +000013030 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000013031 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000013032 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13033 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000013034 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13035 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000013036 if (NewC != CE) {
13037 i->set(NewC);
13038 Changed = true;
13039 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000013040 }
13041
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013042 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013043 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013044 BasicBlock *BB = I->getParent();
13045 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13046 if (UserParent != BB) {
13047 bool UserIsSuccessor = false;
13048 // See if the user is one of our successors.
13049 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13050 if (*SI == UserParent) {
13051 UserIsSuccessor = true;
13052 break;
13053 }
13054
13055 // If the user is one of our immediate successors, and if that successor
13056 // only has us as a predecessors (we'd have to split the critical edge
13057 // otherwise), we can keep going.
13058 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13059 next(pred_begin(UserParent)) == pred_end(UserParent))
13060 // Okay, the CFG is simple enough, try to sink this instruction.
13061 Changed |= TryToSinkInstruction(I, UserParent);
13062 }
13063 }
13064
13065 // Now that we have an instruction, try combining it to simplify it...
13066#ifndef NDEBUG
13067 std::string OrigI;
13068#endif
13069 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13070 if (Instruction *Result = visit(*I)) {
13071 ++NumCombined;
13072 // Should we replace the old instruction with a new one?
13073 if (Result != I) {
13074 DOUT << "IC: Old = " << *I
13075 << " New = " << *Result;
13076
13077 // Everything uses the new instruction now.
13078 I->replaceAllUsesWith(Result);
13079
13080 // Push the new instruction and any users onto the worklist.
13081 AddToWorkList(Result);
13082 AddUsersToWorkList(*Result);
13083
13084 // Move the name to the new instruction first.
13085 Result->takeName(I);
13086
13087 // Insert the new instruction into the basic block...
13088 BasicBlock *InstParent = I->getParent();
13089 BasicBlock::iterator InsertPos = I;
13090
13091 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13092 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13093 ++InsertPos;
13094
13095 InstParent->getInstList().insert(InsertPos, Result);
13096
13097 // Make sure that we reprocess all operands now that we reduced their
13098 // use counts.
13099 AddUsesToWorkList(*I);
13100
13101 // Instructions can end up on the worklist more than once. Make sure
13102 // we do not process an instruction that has been deleted.
13103 RemoveFromWorkList(I);
13104
13105 // Erase the old instruction.
13106 InstParent->getInstList().erase(I);
13107 } else {
13108#ifndef NDEBUG
13109 DOUT << "IC: Mod = " << OrigI
13110 << " New = " << *I;
13111#endif
13112
13113 // If the instruction was modified, it's possible that it is now dead.
13114 // if so, remove it.
13115 if (isInstructionTriviallyDead(I)) {
13116 // Make sure we process all operands now that we are reducing their
13117 // use counts.
13118 AddUsesToWorkList(*I);
13119
13120 // Instructions may end up in the worklist more than once. Erase all
13121 // occurrences of this instruction.
13122 RemoveFromWorkList(I);
13123 I->eraseFromParent();
13124 } else {
13125 AddToWorkList(I);
13126 AddUsersToWorkList(*I);
13127 }
13128 }
13129 Changed = true;
13130 }
13131 }
13132
13133 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013134
13135 // Do an explicit clear, this shrinks the map if needed.
13136 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013137 return Changed;
13138}
13139
13140
13141bool InstCombiner::runOnFunction(Function &F) {
13142 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013143 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013144
13145 bool EverMadeChange = false;
13146
13147 // Iterate while there is work to do.
13148 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013149 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013150 EverMadeChange = true;
13151 return EverMadeChange;
13152}
13153
13154FunctionPass *llvm::createInstructionCombiningPass() {
13155 return new InstCombiner();
13156}