blob: 000243ae64f0e1ae96382a60679561de0d22c863 [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"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/SmallVector.h"
60#include "llvm/ADT/SmallPtrSet.h"
61#include "llvm/ADT/Statistic.h"
62#include "llvm/ADT/STLExtras.h"
63#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000064#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065#include <sstream>
66using namespace llvm;
67using namespace llvm::PatternMatch;
68
69STATISTIC(NumCombined , "Number of insts combined");
70STATISTIC(NumConstProp, "Number of constant folds");
71STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73STATISTIC(NumSunkInst , "Number of instructions sunk");
74
75namespace {
76 class VISIBILITY_HIDDEN InstCombiner
77 : public FunctionPass,
78 public InstVisitor<InstCombiner, Instruction*> {
79 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000080 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 DenseMap<Instruction*, unsigned> WorklistMap;
82 TargetData *TD;
83 bool MustPreserveLCSSA;
84 public:
85 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000086 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087
Owen Anderson175b6542009-07-22 00:24:57 +000088 LLVMContext *Context;
89 LLVMContext *getContext() const { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +000090
Dan Gohmanf17a25c2007-07-18 16:29:46 +000091 /// AddToWorkList - Add the specified instruction to the worklist if it
92 /// isn't already in it.
93 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 Worklist.push_back(I);
96 }
97
98 // RemoveFromWorkList - remove I from the worklist if it exists.
99 void RemoveFromWorkList(Instruction *I) {
100 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
101 if (It == WorklistMap.end()) return; // Not in worklist.
102
103 // Don't bother moving everything down, just null out the slot.
104 Worklist[It->second] = 0;
105
106 WorklistMap.erase(It);
107 }
108
109 Instruction *RemoveOneFromWorkList() {
110 Instruction *I = Worklist.back();
111 Worklist.pop_back();
112 WorklistMap.erase(I);
113 return I;
114 }
115
116
117 /// AddUsersToWorkList - When an instruction is simplified, add all users of
118 /// the instruction to the work lists because they might get more simplified
119 /// now.
120 ///
121 void AddUsersToWorkList(Value &I) {
122 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
123 UI != UE; ++UI)
124 AddToWorkList(cast<Instruction>(*UI));
125 }
126
127 /// AddUsesToWorkList - When an instruction is simplified, add operands to
128 /// the work lists because they might get more simplified now.
129 ///
130 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000131 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
132 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 AddToWorkList(Op);
134 }
135
136 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
137 /// dead. Add all of its operands to the worklist, turning them into
138 /// undef's to reduce the number of uses of those instructions.
139 ///
140 /// Return the specified operand before it is turned into an undef.
141 ///
142 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
143 Value *R = I.getOperand(op);
144
Gabor Greif17396002008-06-12 21:37:33 +0000145 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
146 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147 AddToWorkList(Op);
148 // Set the operand to undef to drop the use.
Owen Anderson24be4c12009-07-03 00:17:18 +0000149 *i = Context->getUndef(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 }
151
152 return R;
153 }
154
155 public:
156 virtual bool runOnFunction(Function &F);
157
158 bool DoOneIteration(Function &F, unsigned ItNum);
159
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 AU.addPreservedID(LCSSAID);
162 AU.setPreservesCFG();
163 }
164
Dan Gohmana80e2712009-07-21 23:21:54 +0000165 TargetData *getTargetData() const { return TD; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166
167 // Visitation implementation - Implement instruction combining for different
168 // instruction types. The semantics are as follows:
169 // Return Value:
170 // null - No change was made
171 // I - Change was made, I is still valid, I may be dead though
172 // otherwise - Change was made, replace I with returned instruction
173 //
174 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000175 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000177 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000179 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 Instruction *visitURem(BinaryOperator &I);
181 Instruction *visitSRem(BinaryOperator &I);
182 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000183 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 Instruction *commonRemTransforms(BinaryOperator &I);
185 Instruction *commonIRemTransforms(BinaryOperator &I);
186 Instruction *commonDivTransforms(BinaryOperator &I);
187 Instruction *commonIDivTransforms(BinaryOperator &I);
188 Instruction *visitUDiv(BinaryOperator &I);
189 Instruction *visitSDiv(BinaryOperator &I);
190 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000191 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner93a359a2009-07-23 05:14:02 +0000192 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000194 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000195 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000196 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 Instruction *visitOr (BinaryOperator &I);
198 Instruction *visitXor(BinaryOperator &I);
199 Instruction *visitShl(BinaryOperator &I);
200 Instruction *visitAShr(BinaryOperator &I);
201 Instruction *visitLShr(BinaryOperator &I);
202 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000203 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
204 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 Instruction *visitFCmpInst(FCmpInst &I);
206 Instruction *visitICmpInst(ICmpInst &I);
207 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
208 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
209 Instruction *LHS,
210 ConstantInt *RHS);
211 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
212 ConstantInt *DivRHS);
213
214 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
215 ICmpInst::Predicate Cond, Instruction &I);
216 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
217 BinaryOperator &I);
218 Instruction *commonCastTransforms(CastInst &CI);
219 Instruction *commonIntCastTransforms(CastInst &CI);
220 Instruction *commonPointerCastTransforms(CastInst &CI);
221 Instruction *visitTrunc(TruncInst &CI);
222 Instruction *visitZExt(ZExtInst &CI);
223 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000224 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000226 Instruction *visitFPToUI(FPToUIInst &FI);
227 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 Instruction *visitUIToFP(CastInst &CI);
229 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000230 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000231 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 Instruction *visitBitCast(BitCastInst &CI);
233 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
234 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000235 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000236 Instruction *visitSelectInst(SelectInst &SI);
237 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 Instruction *visitCallInst(CallInst &CI);
239 Instruction *visitInvokeInst(InvokeInst &II);
240 Instruction *visitPHINode(PHINode &PN);
241 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
242 Instruction *visitAllocationInst(AllocationInst &AI);
243 Instruction *visitFreeInst(FreeInst &FI);
244 Instruction *visitLoadInst(LoadInst &LI);
245 Instruction *visitStoreInst(StoreInst &SI);
246 Instruction *visitBranchInst(BranchInst &BI);
247 Instruction *visitSwitchInst(SwitchInst &SI);
248 Instruction *visitInsertElementInst(InsertElementInst &IE);
249 Instruction *visitExtractElementInst(ExtractElementInst &EI);
250 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000251 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252
253 // visitInstruction - Specify what to return for unhandled instructions...
254 Instruction *visitInstruction(Instruction &I) { return 0; }
255
256 private:
257 Instruction *visitCallSite(CallSite CS);
258 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000259 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000260 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
261 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000262 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000263 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
264
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265
266 public:
267 // InsertNewInstBefore - insert an instruction New before instruction Old
268 // in the program. Add the new instruction to the worklist.
269 //
270 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
271 assert(New && New->getParent() == 0 &&
272 "New instruction already inserted into a basic block!");
273 BasicBlock *BB = Old.getParent();
274 BB->getInstList().insert(&Old, New); // Insert inst
275 AddToWorkList(New);
276 return New;
277 }
278
279 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
280 /// This also adds the cast to the worklist. Finally, this returns the
281 /// cast.
282 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
283 Instruction &Pos) {
284 if (V->getType() == Ty) return V;
285
286 if (Constant *CV = dyn_cast<Constant>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000287 return Context->getConstantExprCast(opc, CV, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288
Gabor Greifa645dd32008-05-16 19:29:10 +0000289 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 AddToWorkList(C);
291 return C;
292 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000293
294 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
295 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
296 }
297
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298
299 // ReplaceInstUsesWith - This method is to be used when an instruction is
300 // found to be dead, replacable with another preexisting expression. Here
301 // we add all uses of I to the worklist, replace all uses of I with the new
302 // value, then return I, so that the inst combiner will know that I was
303 // modified.
304 //
305 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
306 AddUsersToWorkList(I); // Add all modified instrs to worklist
307 if (&I != V) {
308 I.replaceAllUsesWith(V);
309 return &I;
310 } else {
311 // If we are replacing the instruction with itself, this must be in a
312 // segment of unreachable code, so just clobber the instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +0000313 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 return &I;
315 }
316 }
317
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
321 // this function.
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
325 RemoveFromWorkList(&I);
326 I.eraseFromParent();
327 return 0; // Don't do anything with FI
328 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000329
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333 }
334
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 }
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
341 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342
343 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344
345 /// SimplifyCommutative - This performs a few simplifications for
346 /// commutative operators.
347 bool SimplifyCommutative(BinaryOperator &I);
348
349 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
350 /// most-complex to least-complex order.
351 bool SimplifyCompare(CmpInst &I);
352
Chris Lattner676c78e2009-01-31 08:15:18 +0000353 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
354 /// based on the demanded bits.
355 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
356 APInt& KnownZero, APInt& KnownOne,
357 unsigned Depth);
358 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000360 unsigned Depth=0);
361
362 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
363 /// SimplifyDemandedBits knows about. See if the instruction has any
364 /// properties that allow us to simplify its operands.
365 bool SimplifyDemandedInstructionBits(Instruction &Inst);
366
Evan Cheng63295ab2009-02-03 10:05:09 +0000367 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
368 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369
370 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
371 // PHI node as operand #0, see if we can fold the instruction into the PHI
372 // (which is only possible if all operands to the PHI are constants).
373 Instruction *FoldOpIntoPhi(Instruction &I);
374
375 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
376 // operator and they all are only used by the PHI, PHI together their
377 // inputs, and do the operation once, to the result of the PHI.
378 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
379 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000380 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
381
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382
383 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
384 ConstantInt *AndRHS, BinaryOperator &TheAnd);
385
386 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
387 bool isSub, Instruction &I);
388 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
389 bool isSigned, bool Inside, Instruction &IB);
390 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
391 Instruction *MatchBSwap(BinaryOperator &I);
392 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000393 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000394 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000395
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396
397 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000398
Dan Gohman8fd520a2009-06-15 22:12:54 +0000399 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000400 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000401 unsigned GetOrEnforceKnownAlignment(Value *V,
402 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000403
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405}
406
Dan Gohman089efff2008-05-13 00:00:25 +0000407char InstCombiner::ID = 0;
408static RegisterPass<InstCombiner>
409X("instcombine", "Combine redundant instructions");
410
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411// getComplexity: Assign a complexity or rank value to LLVM Values...
412// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson15b39322009-07-13 04:09:18 +0000413static unsigned getComplexity(LLVMContext *Context, Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 if (isa<Instruction>(V)) {
Owen Anderson76f49252009-07-13 22:18:28 +0000415 if (BinaryOperator::isNeg(V) ||
416 BinaryOperator::isFNeg(V) ||
Dan Gohman7ce405e2009-06-04 22:49:04 +0000417 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 return 3;
419 return 4;
420 }
421 if (isa<Argument>(V)) return 3;
422 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
423}
424
425// isOnlyUse - Return true if this instruction will be deleted if we stop using
426// it.
427static bool isOnlyUse(Value *V) {
428 return V->hasOneUse() || isa<Constant>(V);
429}
430
431// getPromotedType - Return the specified type promoted as it would be to pass
432// though a va_arg area...
433static const Type *getPromotedType(const Type *Ty) {
434 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
435 if (ITy->getBitWidth() < 32)
436 return Type::Int32Ty;
437 }
438 return Ty;
439}
440
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000441/// getBitCastOperand - If the specified operand is a CastInst, a constant
442/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
443/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444static Value *getBitCastOperand(Value *V) {
Dan Gohmanae402b02009-07-17 23:55:56 +0000445 if (Operator *O = dyn_cast<Operator>(V)) {
446 if (O->getOpcode() == Instruction::BitCast)
447 return O->getOperand(0);
448 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
449 if (GEP->hasAllZeroIndices())
450 return GEP->getPointerOperand();
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000451 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 return 0;
453}
454
455/// This function is a wrapper around CastInst::isEliminableCastPair. It
456/// simply extracts arguments and returns what that function returns.
457static Instruction::CastOps
458isEliminableCastPair(
459 const CastInst *CI, ///< The first cast instruction
460 unsigned opcode, ///< The opcode of the second cast instruction
461 const Type *DstTy, ///< The target type for the second cast instruction
462 TargetData *TD ///< The target data for pointer size
463) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000464
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
466 const Type *MidTy = CI->getType(); // B from above
467
468 // Get the opcodes of the two Cast instructions
469 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
470 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
471
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000472 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmana80e2712009-07-21 23:21:54 +0000473 DstTy,
474 TD ? TD->getIntPtrType() : 0);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000475
476 // We don't want to form an inttoptr or ptrtoint that converts to an integer
477 // type that differs from the pointer size.
478 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
479 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
480 Res = 0;
481
482 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483}
484
485/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
486/// in any code being generated. It does not require codegen if V is simple
487/// enough or if the cast can be folded into other casts.
488static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
489 const Type *Ty, TargetData *TD) {
490 if (V->getType() == Ty || isa<Constant>(V)) return false;
491
492 // If this is another cast that can be eliminated, it isn't codegen either.
493 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmana80e2712009-07-21 23:21:54 +0000494 if (isEliminableCastPair(CI, opcode, Ty, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000495 return false;
496 return true;
497}
498
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499// SimplifyCommutative - This performs a few simplifications for commutative
500// operators:
501//
502// 1. Order operands such that they are listed from right (least complex) to
503// left (most complex). This puts constants before unary operators before
504// binary operators.
505//
506// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
508//
509bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
510 bool Changed = false;
Owen Anderson15b39322009-07-13 04:09:18 +0000511 if (getComplexity(Context, I.getOperand(0)) <
512 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 Changed = !I.swapOperands();
514
515 if (!I.isAssociative()) return Changed;
516 Instruction::BinaryOps Opcode = I.getOpcode();
517 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
518 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
519 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +0000520 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 cast<Constant>(I.getOperand(1)),
522 cast<Constant>(Op->getOperand(1)));
523 I.setOperand(0, Op->getOperand(0));
524 I.setOperand(1, Folded);
525 return true;
526 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
527 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
528 isOnlyUse(Op) && isOnlyUse(Op1)) {
529 Constant *C1 = cast<Constant>(Op->getOperand(1));
530 Constant *C2 = cast<Constant>(Op1->getOperand(1));
531
532 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson24be4c12009-07-03 00:17:18 +0000533 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000534 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 Op1->getOperand(0),
536 Op1->getName(), &I);
537 AddToWorkList(New);
538 I.setOperand(0, New);
539 I.setOperand(1, Folded);
540 return true;
541 }
542 }
543 return Changed;
544}
545
546/// SimplifyCompare - For a CmpInst this function just orders the operands
547/// so that theyare listed from right (least complex) to left (most complex).
548/// This puts constants before unary operators before binary operators.
549bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson15b39322009-07-13 04:09:18 +0000550 if (getComplexity(Context, I.getOperand(0)) >=
551 getComplexity(Context, I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552 return false;
553 I.swapOperands();
554 // Compare instructions are not associative so there's nothing else we can do.
555 return true;
556}
557
558// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
559// if the LHS is a constant zero (which is the 'negate' form).
560//
Owen Anderson5349f052009-07-06 23:00:19 +0000561static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Anderson76f49252009-07-13 22:18:28 +0000562 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563 return BinaryOperator::getNegArgument(V);
564
565 // Constants can be considered to be negated values if they can be folded.
566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000567 return Context->getConstantExprNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000568
569 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
570 if (C->getType()->getElementType()->isInteger())
Owen Anderson24be4c12009-07-03 00:17:18 +0000571 return Context->getConstantExprNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000572
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573 return 0;
574}
575
Dan Gohman7ce405e2009-06-04 22:49:04 +0000576// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
577// instruction if the LHS is a constant negative zero (which is the 'negate'
578// form).
579//
Owen Anderson5349f052009-07-06 23:00:19 +0000580static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Anderson76f49252009-07-13 22:18:28 +0000581 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000582 return BinaryOperator::getFNegArgument(V);
583
584 // Constants can be considered to be negated values if they can be folded.
585 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000586 return Context->getConstantExprFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000587
588 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
589 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson24be4c12009-07-03 00:17:18 +0000590 return Context->getConstantExprFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000591
592 return 0;
593}
594
Owen Anderson5349f052009-07-06 23:00:19 +0000595static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 if (BinaryOperator::isNot(V))
597 return BinaryOperator::getNotArgument(V);
598
599 // Constants can be considered to be not'ed values...
600 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000601 return Context->getConstantInt(~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 return 0;
603}
604
605// dyn_castFoldableMul - If this value is a multiply that can be folded into
606// other computations (because it has a constant operand), return the
607// non-constant operand of the multiply, and set CST to point to the multiplier.
608// Otherwise, return null.
609//
Owen Anderson24be4c12009-07-03 00:17:18 +0000610static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson5349f052009-07-06 23:00:19 +0000611 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612 if (V->hasOneUse() && V->getType()->isInteger())
613 if (Instruction *I = dyn_cast<Instruction>(V)) {
614 if (I->getOpcode() == Instruction::Mul)
615 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
616 return I->getOperand(0);
617 if (I->getOpcode() == Instruction::Shl)
618 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
619 // The multiplier is really 1 << CST.
620 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
621 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Anderson24be4c12009-07-03 00:17:18 +0000622 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 return I->getOperand(0);
624 }
625 }
626 return 0;
627}
628
629/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
630/// expression, return it.
631static User *dyn_castGetElementPtr(Value *V) {
632 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
633 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
634 if (CE->getOpcode() == Instruction::GetElementPtr)
635 return cast<User>(V);
636 return false;
637}
638
639/// AddOne - Add one to a ConstantInt
Owen Anderson5349f052009-07-06 23:00:19 +0000640static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Anderson24be4c12009-07-03 00:17:18 +0000641 return Context->getConstantExprAdd(C,
642 Context->getConstantInt(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643}
644/// SubOne - Subtract one from a ConstantInt
Owen Anderson5349f052009-07-06 23:00:19 +0000645static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Anderson24be4c12009-07-03 00:17:18 +0000646 return Context->getConstantExprSub(C,
647 Context->getConstantInt(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000649/// MultiplyOverflows - True if the multiply can not be expressed in an int
650/// this size.
Owen Anderson24be4c12009-07-03 00:17:18 +0000651static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson5349f052009-07-06 23:00:19 +0000652 LLVMContext *Context) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000653 uint32_t W = C1->getBitWidth();
654 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
655 if (sign) {
656 LHSExt.sext(W * 2);
657 RHSExt.sext(W * 2);
658 } else {
659 LHSExt.zext(W * 2);
660 RHSExt.zext(W * 2);
661 }
662
663 APInt MulExt = LHSExt * RHSExt;
664
665 if (sign) {
666 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
667 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
668 return MulExt.slt(Min) || MulExt.sgt(Max);
669 } else
670 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
671}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673
674/// ShrinkDemandedConstant - Check to see if the specified operand of the
675/// specified instruction is a constant integer. If so, check to see if there
676/// are any bits set in the constant that are not demanded. If so, shrink the
677/// constant and return true.
678static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson5349f052009-07-06 23:00:19 +0000679 APInt Demanded, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 assert(I && "No instruction?");
681 assert(OpNo < I->getNumOperands() && "Operand index too large");
682
683 // If the operand is not a constant integer, nothing to do.
684 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
685 if (!OpC) return false;
686
687 // If there are no bits set that aren't demanded, nothing to do.
688 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
689 if ((~Demanded & OpC->getValue()) == 0)
690 return false;
691
692 // This instruction is producing bits that are not demanded. Shrink the RHS.
693 Demanded &= OpC->getValue();
Owen Anderson24be4c12009-07-03 00:17:18 +0000694 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 return true;
696}
697
698// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
699// set of known zero and one bits, compute the maximum and minimum values that
700// could have the specified known zero and known one bits, returning them in
701// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000702static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000705 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
706 KnownZero.getBitWidth() == Min.getBitWidth() &&
707 KnownZero.getBitWidth() == Max.getBitWidth() &&
708 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 APInt UnknownBits = ~(KnownZero|KnownOne);
710
711 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
712 // bit if it is unknown.
713 Min = KnownOne;
714 Max = KnownOne|UnknownBits;
715
Dan Gohman7934d592009-04-25 17:12:48 +0000716 if (UnknownBits.isNegative()) { // Sign bit is unknown
717 Min.set(Min.getBitWidth()-1);
718 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 }
720}
721
722// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
723// a set of known zero and one bits, compute the maximum and minimum values that
724// could have the specified known zero and known one bits, returning them in
725// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000726static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000727 const APInt &KnownOne,
728 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000729 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
730 KnownZero.getBitWidth() == Min.getBitWidth() &&
731 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
733 APInt UnknownBits = ~(KnownZero|KnownOne);
734
735 // The minimum value is when the unknown bits are all zeros.
736 Min = KnownOne;
737 // The maximum value is when the unknown bits are all ones.
738 Max = KnownOne|UnknownBits;
739}
740
Chris Lattner676c78e2009-01-31 08:15:18 +0000741/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
742/// SimplifyDemandedBits knows about. See if the instruction has any
743/// properties that allow us to simplify its operands.
744bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000745 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000746 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
747 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
748
749 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
750 KnownZero, KnownOne, 0);
751 if (V == 0) return false;
752 if (V == &Inst) return true;
753 ReplaceInstUsesWith(Inst, V);
754 return true;
755}
756
757/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
758/// specified instruction operand if possible, updating it in place. It returns
759/// true if it made any change and false otherwise.
760bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
761 APInt &KnownZero, APInt &KnownOne,
762 unsigned Depth) {
763 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
764 KnownZero, KnownOne, Depth);
765 if (NewVal == 0) return false;
766 U.set(NewVal);
767 return true;
768}
769
770
771/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
772/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773/// that only the bits set in DemandedMask of the result of V are ever used
774/// downstream. Consequently, depending on the mask and V, it may be possible
775/// to replace V with a constant or one of its operands. In such cases, this
776/// function does the replacement and returns true. In all other cases, it
777/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000778/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779/// to be zero in the expression. These are provided to potentially allow the
780/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
781/// the expression. KnownOne and KnownZero always follow the invariant that
782/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
783/// the bits in KnownOne and KnownZero may only be accurate for those bits set
784/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
785/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000786///
787/// This returns null if it did not change anything and it permits no
788/// simplification. This returns V itself if it did some simplification of V's
789/// operands based on the information about what bits are demanded. This returns
790/// some other non-null value if it found out that V is equal to another value
791/// in the context where the specified bits are demanded, but not for all users.
792Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
793 APInt &KnownZero, APInt &KnownOne,
794 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 assert(V != 0 && "Null pointer of Value???");
796 assert(Depth <= 6 && "Limit Search Depth");
797 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000798 const Type *VTy = V->getType();
799 assert((TD || !isa<PointerType>(VTy)) &&
800 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000801 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
802 (!VTy->isIntOrIntVector() ||
803 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000804 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000806 "Value *V, DemandedMask, KnownZero and KnownOne "
807 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
809 // We know all of the bits for a constant!
810 KnownOne = CI->getValue() & DemandedMask;
811 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000812 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 }
Dan Gohman7934d592009-04-25 17:12:48 +0000814 if (isa<ConstantPointerNull>(V)) {
815 // We know all of the bits for a constant!
816 KnownOne.clear();
817 KnownZero = DemandedMask;
818 return 0;
819 }
820
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000821 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000823 if (DemandedMask == 0) { // Not demanding any bits from V.
824 if (isa<UndefValue>(V))
825 return 0;
Owen Anderson24be4c12009-07-03 00:17:18 +0000826 return Context->getUndef(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 }
828
Chris Lattner08817332009-01-31 08:24:16 +0000829 if (Depth == 6) // Limit search depth.
830 return 0;
831
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000832 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
833 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
834
Dan Gohman7934d592009-04-25 17:12:48 +0000835 Instruction *I = dyn_cast<Instruction>(V);
836 if (!I) {
837 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
838 return 0; // Only analyze instructions.
839 }
840
Chris Lattner08817332009-01-31 08:24:16 +0000841 // If there are multiple uses of this value and we aren't at the root, then
842 // we can't do any simplifications of the operands, because DemandedMask
843 // only reflects the bits demanded by *one* of the users.
844 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000845 // Despite the fact that we can't simplify this instruction in all User's
846 // context, we can at least compute the knownzero/knownone bits, and we can
847 // do simplifications that apply to *just* the one user if we know that
848 // this instruction has a simpler value in that context.
849 if (I->getOpcode() == Instruction::And) {
850 // If either the LHS or the RHS are Zero, the result is zero.
851 ComputeMaskedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1);
853 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
854 LHSKnownZero, LHSKnownOne, Depth+1);
855
856 // If all of the demanded bits are known 1 on one side, return the other.
857 // These bits cannot contribute to the result of the 'and' in this
858 // context.
859 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
860 (DemandedMask & ~LHSKnownZero))
861 return I->getOperand(0);
862 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
863 (DemandedMask & ~RHSKnownZero))
864 return I->getOperand(1);
865
866 // If all of the demanded bits in the inputs are known zeros, return zero.
867 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Anderson24be4c12009-07-03 00:17:18 +0000868 return Context->getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000869
870 } else if (I->getOpcode() == Instruction::Or) {
871 // We can simplify (X|Y) -> X or Y in the user's context if we know that
872 // only bits from X or Y are demanded.
873
874 // If either the LHS or the RHS are One, the result is One.
875 ComputeMaskedBits(I->getOperand(1), DemandedMask,
876 RHSKnownZero, RHSKnownOne, Depth+1);
877 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
878 LHSKnownZero, LHSKnownOne, Depth+1);
879
880 // If all of the demanded bits are known zero on one side, return the
881 // other. These bits cannot contribute to the result of the 'or' in this
882 // context.
883 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
884 (DemandedMask & ~LHSKnownOne))
885 return I->getOperand(0);
886 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
887 (DemandedMask & ~RHSKnownOne))
888 return I->getOperand(1);
889
890 // If all of the potentially set bits on one side are known to be set on
891 // the other side, just use the 'other' side.
892 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
893 (DemandedMask & (~RHSKnownZero)))
894 return I->getOperand(0);
895 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
896 (DemandedMask & (~LHSKnownZero)))
897 return I->getOperand(1);
898 }
899
Chris Lattner08817332009-01-31 08:24:16 +0000900 // Compute the KnownZero/KnownOne bits to simplify things downstream.
901 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
902 return 0;
903 }
904
905 // If this is the root being simplified, allow it to have multiple uses,
906 // just set the DemandedMask to all bits so that we can try to simplify the
907 // operands. This allows visitTruncInst (for example) to simplify the
908 // operand of a trunc without duplicating all the logic below.
909 if (Depth == 0 && !V->hasOneUse())
910 DemandedMask = APInt::getAllOnesValue(BitWidth);
911
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000913 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000914 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000915 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 case Instruction::And:
917 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000918 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
919 RHSKnownZero, RHSKnownOne, Depth+1) ||
920 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000922 return I;
923 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
924 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and'.
928 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
929 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000930 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
932 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000933 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 // If all of the demanded bits in the inputs are known zeros, return zero.
936 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Anderson24be4c12009-07-03 00:17:18 +0000937 return Context->getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938
939 // If the RHS is a constant, see if we can simplify it.
Owen Anderson24be4c12009-07-03 00:17:18 +0000940 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +0000941 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942
943 // Output known-1 bits are only known if set in both the LHS & RHS.
944 RHSKnownOne &= LHSKnownOne;
945 // Output known-0 are known to be clear if zero in either the LHS | RHS.
946 RHSKnownZero |= LHSKnownZero;
947 break;
948 case Instruction::Or:
949 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000950 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1) ||
952 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000954 return I;
955 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
956 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957
958 // If all of the demanded bits are known zero on one side, return the other.
959 // These bits cannot contribute to the result of the 'or'.
960 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
961 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
964 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966
967 // If all of the potentially set bits on one side are known to be set on
968 // the other side, just use the 'other' side.
969 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
970 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000971 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
973 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000974 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975
976 // If the RHS is a constant, see if we can simplify it.
Owen Anderson24be4c12009-07-03 00:17:18 +0000977 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +0000978 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979
980 // Output known-0 bits are only known if clear in both the LHS & RHS.
981 RHSKnownZero &= LHSKnownZero;
982 // Output known-1 are known to be set if set in either the LHS | RHS.
983 RHSKnownOne |= LHSKnownOne;
984 break;
985 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +0000986 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
987 RHSKnownZero, RHSKnownOne, Depth+1) ||
988 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000990 return I;
991 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
992 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
994 // If all of the demanded bits are known zero on one side, return the other.
995 // These bits cannot contribute to the result of the 'xor'.
996 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000997 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000999 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000
1001 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1002 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1003 (RHSKnownOne & LHSKnownOne);
1004 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1005 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1006 (RHSKnownOne & LHSKnownZero);
1007
1008 // If all of the demanded bits are known to be zero on one side or the
1009 // other, turn this into an *inclusive* or.
1010 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1011 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1012 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001013 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001015 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 }
1017
1018 // If all of the demanded bits on one side are known, and all of the set
1019 // bits on that side are also known to be set on the other side, turn this
1020 // into an AND, as we know the bits will be cleared.
1021 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1022 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1023 // all known
1024 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001025 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001027 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001028 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001029 }
1030 }
1031
1032 // If the RHS is a constant, see if we can simplify it.
1033 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Anderson24be4c12009-07-03 00:17:18 +00001034 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001035 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036
1037 RHSKnownZero = KnownZeroOut;
1038 RHSKnownOne = KnownOneOut;
1039 break;
1040 }
1041 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001042 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1043 RHSKnownZero, RHSKnownOne, Depth+1) ||
1044 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001046 return I;
1047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1048 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001049
1050 // If the operands are constants, see if we can simplify them.
Owen Anderson24be4c12009-07-03 00:17:18 +00001051 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1052 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001053 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054
1055 // Only known if known in both the LHS and RHS.
1056 RHSKnownOne &= LHSKnownOne;
1057 RHSKnownZero &= LHSKnownZero;
1058 break;
1059 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001060 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061 DemandedMask.zext(truncBf);
1062 RHSKnownZero.zext(truncBf);
1063 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001064 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001066 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067 DemandedMask.trunc(BitWidth);
1068 RHSKnownZero.trunc(BitWidth);
1069 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001070 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 break;
1072 }
1073 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001074 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001075 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001076
1077 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1078 if (const VectorType *SrcVTy =
1079 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1080 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1081 // Don't touch a bitcast between vectors of different element counts.
1082 return false;
1083 } else
1084 // Don't touch a scalar-to-vector bitcast.
1085 return false;
1086 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1087 // Don't touch a vector-to-scalar bitcast.
1088 return false;
1089
Chris Lattner676c78e2009-01-31 08:15:18 +00001090 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001092 return I;
1093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 break;
1095 case Instruction::ZExt: {
1096 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001097 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098
1099 DemandedMask.trunc(SrcBitWidth);
1100 RHSKnownZero.trunc(SrcBitWidth);
1101 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001104 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 DemandedMask.zext(BitWidth);
1106 RHSKnownZero.zext(BitWidth);
1107 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109 // The top bits are known to be zero.
1110 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1111 break;
1112 }
1113 case Instruction::SExt: {
1114 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116
1117 APInt InputDemandedBits = DemandedMask &
1118 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1119
1120 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1121 // If any of the sign extended bits are demanded, we know that the sign
1122 // bit is demanded.
1123 if ((NewBits & DemandedMask) != 0)
1124 InputDemandedBits.set(SrcBitWidth-1);
1125
1126 InputDemandedBits.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001129 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001131 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 InputDemandedBits.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136
1137 // If the sign bit of the input is known set or clear, then we know the
1138 // top bits of the result.
1139
1140 // If the input sign bit is known zero, or if the NewBits are not demanded
1141 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001142 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001144 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1147 RHSKnownOne |= NewBits;
1148 }
1149 break;
1150 }
1151 case Instruction::Add: {
1152 // Figure out what the input bits are. If the top bits of the and result
1153 // are not demanded, then the add doesn't demand them from its input
1154 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001155 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156
1157 // If there is a constant on the RHS, there are a variety of xformations
1158 // we can do.
1159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 // If null, this should be simplified elsewhere. Some of the xforms here
1161 // won't work if the RHS is zero.
1162 if (RHS->isZero())
1163 break;
1164
1165 // If the top bit of the output is demanded, demand everything from the
1166 // input. Otherwise, we demand all the input bits except NLZ top bits.
1167 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1168
1169 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001170 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001172 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173
1174 // If the RHS of the add has bits set that can't affect the input, reduce
1175 // the constant.
Owen Anderson24be4c12009-07-03 00:17:18 +00001176 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001177 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178
1179 // Avoid excess work.
1180 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1181 break;
1182
1183 // Turn it into OR if input bits are zero.
1184 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001186 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001188 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001189 }
1190
1191 // We can say something about the output known-zero and known-one bits,
1192 // depending on potential carries from the input constant and the
1193 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1194 // bits set and the RHS constant is 0x01001, then we know we have a known
1195 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196
1197 // To compute this, we first compute the potential carry bits. These are
1198 // the bits which may be modified. I'm not aware of a better way to do
1199 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001200 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1202
1203 // Now that we know which bits have carries, compute the known-1/0 sets.
1204
1205 // Bits are known one if they are known zero in one operand and one in the
1206 // other, and there is no input carry.
1207 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1208 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209
1210 // Bits are known zero if they are known zero in both operands and there
1211 // is no input carry.
1212 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213 } else {
1214 // If the high-bits of this ADD are not demanded, then it does not demand
1215 // the high bits of its LHS or RHS.
1216 if (DemandedMask[BitWidth-1] == 0) {
1217 // Right fill the mask of bits for this ADD to demand the most
1218 // significant bit and all those below it.
1219 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221 LHSKnownZero, LHSKnownOne, Depth+1) ||
1222 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001224 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 }
1226 }
1227 break;
1228 }
1229 case Instruction::Sub:
1230 // If the high-bits of this SUB are not demanded, then it does not demand
1231 // the high bits of its LHS or RHS.
1232 if (DemandedMask[BitWidth-1] == 0) {
1233 // Right fill the mask of bits for this SUB to demand the most
1234 // significant bit and all those below it.
1235 uint32_t NLZ = DemandedMask.countLeadingZeros();
1236 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001237 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238 LHSKnownZero, LHSKnownOne, Depth+1) ||
1239 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001241 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001243 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244 // the known zeros and ones.
1245 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 break;
1247 case Instruction::Shl:
1248 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1249 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1250 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001253 return I;
1254 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 RHSKnownZero <<= ShiftAmt;
1256 RHSKnownOne <<= ShiftAmt;
1257 // low bits known zero.
1258 if (ShiftAmt)
1259 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1260 }
1261 break;
1262 case Instruction::LShr:
1263 // For a logical shift right
1264 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1265 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1266
1267 // Unsigned shift right.
1268 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001271 return I;
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1275 if (ShiftAmt) {
1276 // Compute the new bits that are at the top now.
1277 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1278 RHSKnownZero |= HighBits; // high bits known zero.
1279 }
1280 }
1281 break;
1282 case Instruction::AShr:
1283 // If this is an arithmetic shift right and only the low-bit is set, we can
1284 // always convert this into a logical shr, even if the shift amount is
1285 // variable. The low bit of the shift cannot be an input sign bit unless
1286 // the shift amount is >= the size of the datatype, which is undefined.
1287 if (DemandedMask == 1) {
1288 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001289 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001291 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 }
1293
1294 // If the sign bit is the only bit demanded by this ashr, then there is no
1295 // need to do it, the shift doesn't change the high bit.
1296 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001297 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298
1299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1300 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1301
1302 // Signed shift right.
1303 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1304 // If any of the "high bits" are demanded, we should set the sign bit as
1305 // demanded.
1306 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001308 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001310 return I;
1311 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 // Compute the new bits that are at the top now.
1313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1314 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316
1317 // Handle the sign bits.
1318 APInt SignBit(APInt::getSignBit(BitWidth));
1319 // Adjust to where it is now in the mask.
1320 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1321
1322 // If the input sign bit is known to be zero, or if none of the top bits
1323 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001324 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 (HighBits & ~DemandedMask) == HighBits) {
1326 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001327 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001329 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001330 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331 RHSKnownOne |= HighBits;
1332 }
1333 }
1334 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001335 case Instruction::SRem:
1336 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001337 APInt RA = Rem->getValue().abs();
1338 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001339 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001340 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001341
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001342 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001343 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001344 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001345 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001346 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001347
1348 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001350
1351 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001352
Chris Lattner676c78e2009-01-31 08:15:18 +00001353 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001354 }
1355 }
1356 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001357 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001358 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001360 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361 KnownZero2, KnownOne2, Depth+1) ||
1362 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001363 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001364 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001365
Chris Lattneree5417c2009-01-21 18:09:24 +00001366 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001367 Leaders = std::max(Leaders,
1368 KnownZero2.countLeadingOnes());
1369 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001370 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 }
Chris Lattner989ba312008-06-18 04:33:20 +00001372 case Instruction::Call:
1373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374 switch (II->getIntrinsicID()) {
1375 default: break;
1376 case Intrinsic::bswap: {
1377 // If the only bits demanded come from one byte of the bswap result,
1378 // just shift the input byte into position to eliminate the bswap.
1379 unsigned NLZ = DemandedMask.countLeadingZeros();
1380 unsigned NTZ = DemandedMask.countTrailingZeros();
1381
1382 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1383 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1384 // have 14 leading zeros, round to 8.
1385 NLZ &= ~7;
1386 NTZ &= ~7;
1387 // If we need exactly one byte, we can do this transformation.
1388 if (BitWidth-NLZ-NTZ == 8) {
1389 unsigned ResultBit = NTZ;
1390 unsigned InputBit = BitWidth-NTZ-8;
1391
1392 // Replace this with either a left or right shift to get the byte into
1393 // the right place.
1394 Instruction *NewVal;
1395 if (InputBit > ResultBit)
1396 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Anderson24be4c12009-07-03 00:17:18 +00001397 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001398 else
1399 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Anderson24be4c12009-07-03 00:17:18 +00001400 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001401 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001402 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001403 }
1404
1405 // TODO: Could compute known zero/one bits based on the input.
1406 break;
1407 }
1408 }
1409 }
Chris Lattner4946e222008-06-18 18:11:55 +00001410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001411 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001412 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413
1414 // If the client is only demanding bits that we know, return the known
1415 // constant.
Dan Gohman7934d592009-04-25 17:12:48 +00001416 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001417 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman7934d592009-04-25 17:12:48 +00001418 if (isa<PointerType>(V->getType()))
Owen Anderson24be4c12009-07-03 00:17:18 +00001419 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman7934d592009-04-25 17:12:48 +00001420 return C;
1421 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 return false;
1423}
1424
1425
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001426/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001427/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428/// actually used by the caller. This method analyzes which elements of the
1429/// operand are undef and returns that information in UndefElts.
1430///
1431/// If the information about demanded elements can be used to simplify the
1432/// operation, the operation is simplified, then the resultant value is
1433/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001434Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1435 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 unsigned Depth) {
1437 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001438 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001439 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440
1441 if (isa<UndefValue>(V)) {
1442 // If the entire vector is undefined, just return this info.
1443 UndefElts = EltMask;
1444 return 0;
1445 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1446 UndefElts = EltMask;
Owen Anderson24be4c12009-07-03 00:17:18 +00001447 return Context->getUndef(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001449
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 UndefElts = 0;
1451 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +00001453 Constant *Undef = Context->getUndef(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454
1455 std::vector<Constant*> Elts;
1456 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001457 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001459 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001460 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1461 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001462 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 } else { // Otherwise, defined.
1464 Elts.push_back(CP->getOperand(i));
1465 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 // If we changed the constant, return it.
Owen Anderson24be4c12009-07-03 00:17:18 +00001468 Constant *NewCP = Context->getConstantVector(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 return NewCP != CP ? NewCP : 0;
1470 } else if (isa<ConstantAggregateZero>(V)) {
1471 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1472 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001473
1474 // Check if this is identity. If so, return 0 since we are not simplifying
1475 // anything.
1476 if (DemandedElts == ((1ULL << VWidth) -1))
1477 return 0;
1478
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +00001480 Constant *Zero = Context->getNullValue(EltTy);
1481 Constant *Undef = Context->getUndef(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001482 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001483 for (unsigned i = 0; i != VWidth; ++i) {
1484 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1485 Elts.push_back(Elt);
1486 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 UndefElts = DemandedElts ^ EltMask;
Owen Anderson24be4c12009-07-03 00:17:18 +00001488 return Context->getConstantVector(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 }
1490
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001491 // Limit search depth.
1492 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001493 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001494
1495 // If multiple users are using the root value, procede with
1496 // simplification conservatively assuming that all elements
1497 // are needed.
1498 if (!V->hasOneUse()) {
1499 // Quit if we find multiple users of a non-root value though.
1500 // They'll be handled when it's their turn to be visited by
1501 // the main instcombine process.
1502 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001504 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001505
1506 // Conservatively assume that all elements are needed.
1507 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001508 }
1509
1510 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001511 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512
1513 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001514 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 Value *TmpV;
1516 switch (I->getOpcode()) {
1517 default: break;
1518
1519 case Instruction::InsertElement: {
1520 // If this is a variable index, we don't know which element it overwrites.
1521 // demand exactly the same input as we produce.
1522 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1523 if (Idx == 0) {
1524 // Note that we can't propagate undef elt info, because we don't know
1525 // which elt is getting updated.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts2, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529 break;
1530 }
1531
1532 // If this is inserting an element that isn't demanded, remove this
1533 // insertelement.
1534 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001535 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001536 return AddSoonDeadInstToWorklist(*I, 0);
1537
1538 // Otherwise, the element inserted overwrites whatever was there, so the
1539 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001540 APInt DemandedElts2 = DemandedElts;
1541 DemandedElts2.clear(IdxNo);
1542 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543 UndefElts, Depth+1);
1544 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
1546 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001547 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001548 break;
1549 }
1550 case Instruction::ShuffleVector: {
1551 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001552 uint64_t LHSVWidth =
1553 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001554 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001555 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001556 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001557 unsigned MaskVal = Shuffle->getMaskValue(i);
1558 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001559 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001560 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001561 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001562 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001563 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001564 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001565 }
1566 }
1567 }
1568
Nate Begemanb4d176f2009-02-11 22:36:25 +00001569 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001570 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001571 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001572 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1573
Nate Begemanb4d176f2009-02-11 22:36:25 +00001574 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001575 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1576 UndefElts3, Depth+1);
1577 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1578
1579 bool NewUndefElts = false;
1580 for (unsigned i = 0; i < VWidth; i++) {
1581 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001582 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001583 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001584 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001585 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001586 NewUndefElts = true;
1587 UndefElts.set(i);
1588 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001589 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001590 if (UndefElts3[MaskVal - LHSVWidth]) {
1591 NewUndefElts = true;
1592 UndefElts.set(i);
1593 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001594 }
1595 }
1596
1597 if (NewUndefElts) {
1598 // Add additional discovered undefs.
1599 std::vector<Constant*> Elts;
1600 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001601 if (UndefElts[i])
Owen Anderson24be4c12009-07-03 00:17:18 +00001602 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001603 else
Owen Anderson24be4c12009-07-03 00:17:18 +00001604 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001605 Shuffle->getMaskValue(i)));
1606 }
Owen Anderson24be4c12009-07-03 00:17:18 +00001607 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001608 MadeChange = true;
1609 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610 break;
1611 }
1612 case Instruction::BitCast: {
1613 // Vector->vector casts only.
1614 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1615 if (!VTy) break;
1616 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001617 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 unsigned Ratio;
1619
1620 if (VWidth == InVWidth) {
1621 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1622 // elements as are demanded of us.
1623 Ratio = 1;
1624 InputDemandedElts = DemandedElts;
1625 } else if (VWidth > InVWidth) {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the result than there are in the source,
1630 // then an input element is live if any of the corresponding output
1631 // elements are live.
1632 Ratio = VWidth/InVWidth;
1633 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001634 if (DemandedElts[OutIdx])
1635 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 }
1637 } else {
1638 // Untested so far.
1639 break;
1640
1641 // If there are more elements in the source than there are in the result,
1642 // then an input element is live if the corresponding output element is
1643 // live.
1644 Ratio = InVWidth/VWidth;
1645 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001646 if (DemandedElts[InIdx/Ratio])
1647 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 }
1649
1650 // div/rem demand all inputs, because they don't want divide by zero.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1652 UndefElts2, Depth+1);
1653 if (TmpV) {
1654 I->setOperand(0, TmpV);
1655 MadeChange = true;
1656 }
1657
1658 UndefElts = UndefElts2;
1659 if (VWidth > InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001660 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001661 // If there are more elements in the result than there are in the source,
1662 // then an output element is undef if the corresponding input element is
1663 // undef.
1664 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001665 if (UndefElts2[OutIdx/Ratio])
1666 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001667 } else if (VWidth < InVWidth) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001668 llvm_unreachable("Unimp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669 // If there are more elements in the source than there are in the result,
1670 // then a result element is undef if all of the corresponding input
1671 // elements are undef.
1672 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1673 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001674 if (!UndefElts2[InIdx]) // Not undef?
1675 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676 }
1677 break;
1678 }
1679 case Instruction::And:
1680 case Instruction::Or:
1681 case Instruction::Xor:
1682 case Instruction::Add:
1683 case Instruction::Sub:
1684 case Instruction::Mul:
1685 // div/rem demand all inputs, because they don't want divide by zero.
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687 UndefElts, Depth+1);
1688 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1690 UndefElts2, Depth+1);
1691 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1692
1693 // Output elements are undefined if both are undefined. Consider things
1694 // like undef&0. The result is known zero, not undef.
1695 UndefElts &= UndefElts2;
1696 break;
1697
1698 case Instruction::Call: {
1699 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1700 if (!II) break;
1701 switch (II->getIntrinsicID()) {
1702 default: break;
1703
1704 // Binary vector operations that work column-wise. A dest element is a
1705 // function of the corresponding input elements from the two inputs.
1706 case Intrinsic::x86_sse_sub_ss:
1707 case Intrinsic::x86_sse_mul_ss:
1708 case Intrinsic::x86_sse_min_ss:
1709 case Intrinsic::x86_sse_max_ss:
1710 case Intrinsic::x86_sse2_sub_sd:
1711 case Intrinsic::x86_sse2_mul_sd:
1712 case Intrinsic::x86_sse2_min_sd:
1713 case Intrinsic::x86_sse2_max_sd:
1714 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1715 UndefElts, Depth+1);
1716 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1717 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1718 UndefElts2, Depth+1);
1719 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1720
1721 // If only the low elt is demanded and this is a scalarizable intrinsic,
1722 // scalarize it now.
1723 if (DemandedElts == 1) {
1724 switch (II->getIntrinsicID()) {
1725 default: break;
1726 case Intrinsic::x86_sse_sub_ss:
1727 case Intrinsic::x86_sse_mul_ss:
1728 case Intrinsic::x86_sse2_sub_sd:
1729 case Intrinsic::x86_sse2_mul_sd:
1730 // TODO: Lower MIN/MAX/ABS/etc
1731 Value *LHS = II->getOperand(1);
1732 Value *RHS = II->getOperand(2);
1733 // Extract the element as scalars.
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00001734 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1735 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1736 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1737 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738
1739 switch (II->getIntrinsicID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00001740 default: llvm_unreachable("Case stmts out of sync!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741 case Intrinsic::x86_sse_sub_ss:
1742 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001743 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 II->getName()), *II);
1745 break;
1746 case Intrinsic::x86_sse_mul_ss:
1747 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001748 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749 II->getName()), *II);
1750 break;
1751 }
1752
1753 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001754 InsertElementInst::Create(
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00001755 Context->getUndef(II->getType()), TmpV,
1756 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757 InsertNewInstBefore(New, *II);
1758 AddSoonDeadInstToWorklist(*II, 0);
1759 return New;
1760 }
1761 }
1762
1763 // Output elements are undefined if both are undefined. Consider things
1764 // like undef&0. The result is known zero, not undef.
1765 UndefElts &= UndefElts2;
1766 break;
1767 }
1768 break;
1769 }
1770 }
1771 return MadeChange ? I : 0;
1772}
1773
Dan Gohman5d56fd42008-05-19 22:14:15 +00001774
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001775/// AssociativeOpt - Perform an optimization on an associative operator. This
1776/// function is designed to check a chain of associative operators for a
1777/// potential to apply a certain optimization. Since the optimization may be
1778/// applicable if the expression was reassociated, this checks the chain, then
1779/// reassociates the expression as necessary to expose the optimization
1780/// opportunity. This makes use of a special Functor, which must define
1781/// 'shouldApply' and 'apply' methods.
1782///
1783template<typename Functor>
Owen Anderson24be4c12009-07-03 00:17:18 +00001784static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson5349f052009-07-06 23:00:19 +00001785 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786 unsigned Opcode = Root.getOpcode();
1787 Value *LHS = Root.getOperand(0);
1788
1789 // Quick check, see if the immediate LHS matches...
1790 if (F.shouldApply(LHS))
1791 return F.apply(Root);
1792
1793 // Otherwise, if the LHS is not of the same opcode as the root, return.
1794 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1795 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1796 // Should we apply this transform to the RHS?
1797 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1798
1799 // If not to the RHS, check to see if we should apply to the LHS...
1800 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1801 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1802 ShouldApply = true;
1803 }
1804
1805 // If the functor wants to apply the optimization to the RHS of LHSI,
1806 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1807 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001808 // Now all of the instructions are in the current basic block, go ahead
1809 // and perform the reassociation.
1810 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1811
1812 // First move the selected RHS to the LHS of the root...
1813 Root.setOperand(0, LHSI->getOperand(1));
1814
1815 // Make what used to be the LHS of the root be the user of the root...
1816 Value *ExtraOperand = TmpLHSI->getOperand(1);
1817 if (&Root == TmpLHSI) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001818 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001819 return 0;
1820 }
1821 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1822 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001823 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001824 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001825 ARI = Root;
1826
1827 // Now propagate the ExtraOperand down the chain of instructions until we
1828 // get to LHSI.
1829 while (TmpLHSI != LHSI) {
1830 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1831 // Move the instruction to immediately before the chain we are
1832 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001833 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 ARI = NextLHSI;
1835
1836 Value *NextOp = NextLHSI->getOperand(1);
1837 NextLHSI->setOperand(1, ExtraOperand);
1838 TmpLHSI = NextLHSI;
1839 ExtraOperand = NextOp;
1840 }
1841
1842 // Now that the instructions are reassociated, have the functor perform
1843 // the transformation...
1844 return F.apply(Root);
1845 }
1846
1847 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1848 }
1849 return 0;
1850}
1851
Dan Gohman089efff2008-05-13 00:00:25 +00001852namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001853
Nick Lewycky27f6c132008-05-23 04:34:58 +00001854// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001855struct AddRHS {
1856 Value *RHS;
Owen Anderson5349f052009-07-06 23:00:19 +00001857 LLVMContext *Context;
1858 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001859 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1860 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001861 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00001862 Context->getConstantInt(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 }
1864};
1865
1866// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1867// iff C1&C2 == 0
1868struct AddMaskingAnd {
1869 Constant *C2;
Owen Anderson5349f052009-07-06 23:00:19 +00001870 LLVMContext *Context;
1871 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 bool shouldApply(Value *LHS) const {
1873 ConstantInt *C1;
Owen Andersona21eb582009-07-10 17:35:01 +00001874 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Anderson24be4c12009-07-03 00:17:18 +00001875 Context->getConstantExprAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001876 }
1877 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001878 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879 }
1880};
1881
Dan Gohman089efff2008-05-13 00:00:25 +00001882}
1883
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001884static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1885 InstCombiner *IC) {
Owen Anderson5349f052009-07-06 23:00:19 +00001886 LLVMContext *Context = IC->getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00001887
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001889 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001890 }
1891
1892 // Figure out if the constant is the left or the right argument.
1893 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1894 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1895
1896 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1897 if (ConstIsRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00001898 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1899 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 }
1901
1902 Value *Op0 = SO, *Op1 = ConstOperand;
1903 if (!ConstIsRHS)
1904 std::swap(Op0, Op1);
1905 Instruction *New;
1906 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001907 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001908 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001909 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1910 Op0, Op1, SO->getName()+".cmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911 else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001912 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913 }
1914 return IC->InsertNewInstBefore(New, I);
1915}
1916
1917// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1918// constant as the other operand, try to fold the binary operator into the
1919// select arguments. This also works for Cast instructions, which obviously do
1920// not have a second operand.
1921static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1922 InstCombiner *IC) {
1923 // Don't modify shared select instructions
1924 if (!SI->hasOneUse()) return 0;
1925 Value *TV = SI->getOperand(1);
1926 Value *FV = SI->getOperand(2);
1927
1928 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1929 // Bool selects with constant operands can be folded to logical ops.
1930 if (SI->getType() == Type::Int1Ty) return 0;
1931
1932 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1933 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1934
Gabor Greifd6da1d02008-04-06 20:25:17 +00001935 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1936 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001937 }
1938 return 0;
1939}
1940
1941
1942/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1943/// node as operand #0, see if we can fold the instruction into the PHI (which
1944/// is only possible if all operands to the PHI are constants).
1945Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1946 PHINode *PN = cast<PHINode>(I.getOperand(0));
1947 unsigned NumPHIValues = PN->getNumIncomingValues();
1948 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1949
1950 // Check to see if all of the operands of the PHI are constants. If there is
1951 // one non-constant value, remember the BB it is. If there is more than one
1952 // or if *it* is a PHI, bail out.
1953 BasicBlock *NonConstBB = 0;
1954 for (unsigned i = 0; i != NumPHIValues; ++i)
1955 if (!isa<Constant>(PN->getIncomingValue(i))) {
1956 if (NonConstBB) return 0; // More than one non-const value.
1957 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1958 NonConstBB = PN->getIncomingBlock(i);
1959
1960 // If the incoming non-constant value is in I's block, we have an infinite
1961 // loop.
1962 if (NonConstBB == I.getParent())
1963 return 0;
1964 }
1965
1966 // If there is exactly one non-constant value, we can insert a copy of the
1967 // operation in that block. However, if this is a critical edge, we would be
1968 // inserting the computation one some other paths (e.g. inside a loop). Only
1969 // do this if the pred block is unconditionally branching into the phi block.
1970 if (NonConstBB) {
1971 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1972 if (!BI || !BI->isUnconditional()) return 0;
1973 }
1974
1975 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001976 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1978 InsertNewInstBefore(NewPN, *PN);
1979 NewPN->takeName(PN);
1980
1981 // Next, add all of the operands to the PHI.
1982 if (I.getNumOperands() == 2) {
1983 Constant *C = cast<Constant>(I.getOperand(1));
1984 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001985 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1987 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson24be4c12009-07-03 00:17:18 +00001988 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 else
Owen Anderson24be4c12009-07-03 00:17:18 +00001990 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001991 } else {
1992 assert(PN->getIncomingBlock(i) == NonConstBB);
1993 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001994 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995 PN->getIncomingValue(i), C, "phitmp",
1996 NonConstBB->getTerminator());
1997 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001998 InV = CmpInst::Create(*Context, CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001999 CI->getPredicate(),
2000 PN->getIncomingValue(i), C, "phitmp",
2001 NonConstBB->getTerminator());
2002 else
Edwin Törökbd448e32009-07-14 16:55:14 +00002003 llvm_unreachable("Unknown binop!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004
2005 AddToWorkList(cast<Instruction>(InV));
2006 }
2007 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2008 }
2009 } else {
2010 CastInst *CI = cast<CastInst>(&I);
2011 const Type *RetTy = CI->getType();
2012 for (unsigned i = 0; i != NumPHIValues; ++i) {
2013 Value *InV;
2014 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002015 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002016 } else {
2017 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002018 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002019 I.getType(), "phitmp",
2020 NonConstBB->getTerminator());
2021 AddToWorkList(cast<Instruction>(InV));
2022 }
2023 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2024 }
2025 }
2026 return ReplaceInstUsesWith(I, NewPN);
2027}
2028
Chris Lattner55476162008-01-29 06:52:45 +00002029
Chris Lattner3554f972008-05-20 05:46:13 +00002030/// WillNotOverflowSignedAdd - Return true if we can prove that:
2031/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2032/// This basically requires proving that the add in the original type would not
2033/// overflow to change the sign bit or have a carry out.
2034bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2035 // There are different heuristics we can use for this. Here are some simple
2036 // ones.
2037
2038 // Add has the property that adding any two 2's complement numbers can only
2039 // have one carry bit which can change a sign. As such, if LHS and RHS each
2040 // have at least two sign bits, we know that the addition of the two values will
2041 // sign extend fine.
2042 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2043 return true;
2044
2045
2046 // If one of the operands only has one non-zero bit, and if the other operand
2047 // has a known-zero bit in a more significant place than it (not including the
2048 // sign bit) the ripple may go up to and fill the zero, but won't change the
2049 // sign. For example, (X & ~4) + 1.
2050
2051 // TODO: Implement.
2052
2053 return false;
2054}
2055
Chris Lattner55476162008-01-29 06:52:45 +00002056
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2058 bool Changed = SimplifyCommutative(I);
2059 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2060
2061 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2062 // X + undef -> undef
2063 if (isa<UndefValue>(RHS))
2064 return ReplaceInstUsesWith(I, RHS);
2065
2066 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002067 if (RHSC->isNullValue())
2068 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002069
2070 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2071 // X + (signbit) --> X ^ signbit
2072 const APInt& Val = CI->getValue();
2073 uint32_t BitWidth = Val.getBitWidth();
2074 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002075 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076
2077 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2078 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002079 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002080 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002081
Eli Friedmana21526d2009-07-13 22:27:52 +00002082 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman35b76162008-10-30 20:40:10 +00002083 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedmana21526d2009-07-13 22:27:52 +00002084 if (ZI->getSrcTy() == Type::Int1Ty)
2085 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002086 }
2087
2088 if (isa<PHINode>(LHS))
2089 if (Instruction *NV = FoldOpIntoPhi(I))
2090 return NV;
2091
2092 ConstantInt *XorRHS = 0;
2093 Value *XorLHS = 0;
2094 if (isa<ConstantInt>(RHSC) &&
Owen Andersona21eb582009-07-10 17:35:01 +00002095 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002096 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002097 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2098
2099 uint32_t Size = TySizeBits / 2;
2100 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2101 APInt CFF80Val(-C0080Val);
2102 do {
2103 if (TySizeBits > Size) {
2104 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2105 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2106 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2107 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2108 // This is a sign extend if the top bits are known zero.
2109 if (!MaskedValueIsZero(XorLHS,
2110 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2111 Size = 0; // Not a sign ext, but can't be any others either.
2112 break;
2113 }
2114 }
2115 Size >>= 1;
2116 C0080Val = APIntOps::lshr(C0080Val, Size);
2117 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2118 } while (Size >= 1);
2119
2120 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002121 // with funny bit widths then this switch statement should be removed. It
2122 // is just here to get the size of the "middle" type back up to something
2123 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002124 const Type *MiddleType = 0;
2125 switch (Size) {
2126 default: break;
2127 case 32: MiddleType = Type::Int32Ty; break;
2128 case 16: MiddleType = Type::Int16Ty; break;
2129 case 8: MiddleType = Type::Int8Ty; break;
2130 }
2131 if (MiddleType) {
2132 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2133 InsertNewInstBefore(NewTrunc, I);
2134 return new SExtInst(NewTrunc, I.getType(), I.getName());
2135 }
2136 }
2137 }
2138
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002139 if (I.getType() == Type::Int1Ty)
2140 return BinaryOperator::CreateXor(LHS, RHS);
2141
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002142 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002143 if (I.getType()->isInteger()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002144 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2145 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002146
2147 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2148 if (RHSI->getOpcode() == Instruction::Sub)
2149 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2150 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2151 }
2152 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2153 if (LHSI->getOpcode() == Instruction::Sub)
2154 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2155 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2156 }
2157 }
2158
2159 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002160 // -A + -B --> -(A + B)
Owen Anderson24be4c12009-07-03 00:17:18 +00002161 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002162 if (LHS->getType()->isIntOrIntVector()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002163 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002164 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002165 InsertNewInstBefore(NewAdd, I);
Owen Anderson15b39322009-07-13 04:09:18 +00002166 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002167 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002168 }
2169
Gabor Greifa645dd32008-05-16 19:29:10 +00002170 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002171 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172
2173 // A + -B --> A - B
2174 if (!isa<Constant>(RHS))
Owen Anderson24be4c12009-07-03 00:17:18 +00002175 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002176 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177
2178
2179 ConstantInt *C2;
Owen Anderson24be4c12009-07-03 00:17:18 +00002180 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181 if (X == RHS) // X*C + X --> X * (C+1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002182 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183
2184 // X*C1 + X*C2 --> X * (C1+C2)
2185 ConstantInt *C1;
Owen Anderson24be4c12009-07-03 00:17:18 +00002186 if (X == dyn_castFoldableMul(RHS, C1, Context))
2187 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 }
2189
2190 // X + X*C --> X * (C+1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002191 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2192 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002193
2194 // X + ~X --> -1 since ~X = -X-1
Owen Anderson24be4c12009-07-03 00:17:18 +00002195 if (dyn_castNotVal(LHS, Context) == RHS ||
2196 dyn_castNotVal(RHS, Context) == LHS)
2197 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002198
2199
2200 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersona21eb582009-07-10 17:35:01 +00002201 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Anderson24be4c12009-07-03 00:17:18 +00002202 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002204
2205 // A+B --> A|B iff A and B have no bits set in common.
2206 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2207 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2208 APInt LHSKnownOne(IT->getBitWidth(), 0);
2209 APInt LHSKnownZero(IT->getBitWidth(), 0);
2210 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2211 if (LHSKnownZero != 0) {
2212 APInt RHSKnownOne(IT->getBitWidth(), 0);
2213 APInt RHSKnownZero(IT->getBitWidth(), 0);
2214 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2215
2216 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002217 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002218 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002219 }
2220 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221
Nick Lewycky83598a72008-02-03 07:42:09 +00002222 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002223 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002224 Value *W, *X, *Y, *Z;
Owen Andersona21eb582009-07-10 17:35:01 +00002225 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2226 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002227 if (W != Y) {
2228 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002229 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002230 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002231 std::swap(W, X);
2232 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002233 std::swap(Y, Z);
2234 std::swap(W, X);
2235 }
2236 }
2237
2238 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002239 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002240 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002241 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002242 }
2243 }
2244 }
2245
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002246 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2247 Value *X = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00002248 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Anderson24be4c12009-07-03 00:17:18 +00002249 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002250
2251 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002252 if (LHS->hasOneUse() &&
2253 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002254 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255 if (Anded == CRHS) {
2256 // See if all bits from the first bit set in the Add RHS up are included
2257 // in the mask. First, get the rightmost bit.
2258 const APInt& AddRHSV = CRHS->getValue();
2259
2260 // Form a mask of all bits from the lowest bit added through the top.
2261 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2262
2263 // See if the and mask includes all of these bits.
2264 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2265
2266 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2267 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002268 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002270 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271 }
2272 }
2273 }
2274
2275 // Try to fold constant add into select arguments.
2276 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2277 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2278 return R;
2279 }
2280
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002281 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002282 {
2283 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002284 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002285 if (!SI) {
2286 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002287 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002288 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002289 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002290 Value *TV = SI->getTrueValue();
2291 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002292 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002293
2294 // Can we fold the add into the argument of the select?
2295 // We check both true and false select arguments for a matching subtract.
Owen Andersona21eb582009-07-10 17:35:01 +00002296 if (match(FV, m_Zero(), *Context) &&
2297 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner641ea462008-11-16 04:46:19 +00002298 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002299 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersona21eb582009-07-10 17:35:01 +00002300 if (match(TV, m_Zero(), *Context) &&
2301 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner641ea462008-11-16 04:46:19 +00002302 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002303 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002304 }
2305 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002306
Chris Lattner3554f972008-05-20 05:46:13 +00002307 // Check for (add (sext x), y), see if we can merge this into an
2308 // integer add followed by a sext.
2309 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2310 // (add (sext x), cst) --> (sext (add x, cst'))
2311 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2312 Constant *CI =
Owen Anderson24be4c12009-07-03 00:17:18 +00002313 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002314 if (LHSConv->hasOneUse() &&
Owen Anderson24be4c12009-07-03 00:17:18 +00002315 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002316 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2317 // Insert the new, smaller add.
2318 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2319 CI, "addconv");
2320 InsertNewInstBefore(NewAdd, I);
2321 return new SExtInst(NewAdd, I.getType());
2322 }
2323 }
2324
2325 // (add (sext x), (sext y)) --> (sext (add int x, y))
2326 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2327 // Only do this if x/y have the same type, if at last one of them has a
2328 // single use (so we don't increase the number of sexts), and if the
2329 // integer add will not overflow.
2330 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2331 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2332 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2333 RHSConv->getOperand(0))) {
2334 // Insert the new integer add.
2335 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2336 RHSConv->getOperand(0),
2337 "addconv");
2338 InsertNewInstBefore(NewAdd, I);
2339 return new SExtInst(NewAdd, I.getType());
2340 }
2341 }
2342 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002343
2344 return Changed ? &I : 0;
2345}
2346
2347Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2348 bool Changed = SimplifyCommutative(I);
2349 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2350
2351 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2352 // X + 0 --> X
2353 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002354 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002355 (I.getType())->getValueAPF()))
2356 return ReplaceInstUsesWith(I, LHS);
2357 }
2358
2359 if (isa<PHINode>(LHS))
2360 if (Instruction *NV = FoldOpIntoPhi(I))
2361 return NV;
2362 }
2363
2364 // -A + B --> B - A
2365 // -A + -B --> -(A + B)
Owen Anderson24be4c12009-07-03 00:17:18 +00002366 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002367 return BinaryOperator::CreateFSub(RHS, LHSV);
2368
2369 // A + -B --> A - B
2370 if (!isa<Constant>(RHS))
Owen Anderson24be4c12009-07-03 00:17:18 +00002371 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002372 return BinaryOperator::CreateFSub(LHS, V);
2373
2374 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2375 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2376 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2377 return ReplaceInstUsesWith(I, LHS);
2378
Chris Lattner3554f972008-05-20 05:46:13 +00002379 // Check for (add double (sitofp x), y), see if we can merge this into an
2380 // integer add followed by a promotion.
2381 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2382 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2383 // ... if the constant fits in the integer value. This is useful for things
2384 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2385 // requires a constant pool load, and generally allows the add to be better
2386 // instcombined.
2387 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2388 Constant *CI =
Owen Anderson24be4c12009-07-03 00:17:18 +00002389 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002390 if (LHSConv->hasOneUse() &&
Owen Anderson24be4c12009-07-03 00:17:18 +00002391 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002392 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2393 // Insert the new integer add.
2394 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2395 CI, "addconv");
2396 InsertNewInstBefore(NewAdd, I);
2397 return new SIToFPInst(NewAdd, I.getType());
2398 }
2399 }
2400
2401 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2402 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2403 // Only do this if x/y have the same type, if at last one of them has a
2404 // single use (so we don't increase the number of int->fp conversions),
2405 // and if the integer add will not overflow.
2406 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2407 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2408 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2409 RHSConv->getOperand(0))) {
2410 // Insert the new integer add.
2411 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2412 RHSConv->getOperand(0),
2413 "addconv");
2414 InsertNewInstBefore(NewAdd, I);
2415 return new SIToFPInst(NewAdd, I.getType());
2416 }
2417 }
2418 }
2419
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002420 return Changed ? &I : 0;
2421}
2422
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2425
Dan Gohman7ce405e2009-06-04 22:49:04 +00002426 if (Op0 == Op1) // sub X, X -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00002427 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002428
2429 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Anderson24be4c12009-07-03 00:17:18 +00002430 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002431 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432
2433 if (isa<UndefValue>(Op0))
2434 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2435 if (isa<UndefValue>(Op1))
2436 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2437
2438 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2439 // Replace (-1 - A) with (~A)...
2440 if (C->isAllOnesValue())
Owen Anderson035d41d2009-07-13 20:58:05 +00002441 return BinaryOperator::CreateNot(*Context, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442
2443 // C - ~X == X + (1+C)
2444 Value *X = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00002445 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Anderson24be4c12009-07-03 00:17:18 +00002446 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002447
2448 // -(X >>u 31) -> (X >>s 31)
2449 // -(X >>s 31) -> (X >>u 31)
2450 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002451 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452 if (SI->getOpcode() == Instruction::LShr) {
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 AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002458 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459 SI->getOperand(0), CU, SI->getName());
2460 }
2461 }
2462 }
2463 else if (SI->getOpcode() == Instruction::AShr) {
2464 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2465 // Check to see if we are shifting out everything but the sign bit.
2466 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2467 SI->getType()->getPrimitiveSizeInBits()-1) {
2468 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002469 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002470 SI->getOperand(0), CU, SI->getName());
2471 }
2472 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002473 }
2474 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002475 }
2476
2477 // Try to fold constant sub into select arguments.
2478 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2479 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2480 return R;
Eli Friedmana21526d2009-07-13 22:27:52 +00002481
2482 // C - zext(bool) -> bool ? C - 1 : C
2483 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2484 if (ZI->getSrcTy() == Type::Int1Ty)
2485 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486 }
2487
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002488 if (I.getType() == Type::Int1Ty)
2489 return BinaryOperator::CreateXor(Op0, Op1);
2490
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002492 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002494 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2495 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002496 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002497 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2498 I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2500 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2501 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002502 return BinaryOperator::CreateSub(
2503 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002504 }
2505 }
2506
2507 if (Op1I->hasOneUse()) {
2508 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2509 // is not used by anyone else...
2510 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002511 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002512 // Swap the two operands of the subexpr...
2513 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2514 Op1I->setOperand(0, IIOp1);
2515 Op1I->setOperand(1, IIOp0);
2516
2517 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002518 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 }
2520
2521 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2522 //
2523 if (Op1I->getOpcode() == Instruction::And &&
2524 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2525 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2526
2527 Value *NewNot =
Owen Anderson035d41d2009-07-13 20:58:05 +00002528 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2529 OtherOp, "B.not"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002531 }
2532
2533 // 0 - (X sdiv C) -> (X sdiv -C)
2534 if (Op1I->getOpcode() == Instruction::SDiv)
2535 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2536 if (CSI->isZero())
2537 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002539 Context->getConstantExprNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002540
2541 // X - X*C --> X * (1-C)
2542 ConstantInt *C2 = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +00002543 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2544 Constant *CP1 =
2545 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002546 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002547 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 }
2549 }
2550 }
2551
Dan Gohman7ce405e2009-06-04 22:49:04 +00002552 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2553 if (Op0I->getOpcode() == Instruction::Add) {
2554 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2555 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2556 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2557 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2558 } else if (Op0I->getOpcode() == Instruction::Sub) {
2559 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002560 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2561 I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002562 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002563 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002564
2565 ConstantInt *C1;
Owen Anderson24be4c12009-07-03 00:17:18 +00002566 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567 if (X == Op1) // X*C - X --> X * (C-1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002568 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569
2570 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Anderson24be4c12009-07-03 00:17:18 +00002571 if (X == dyn_castFoldableMul(Op1, C2, Context))
2572 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002573 }
2574 return 0;
2575}
2576
Dan Gohman7ce405e2009-06-04 22:49:04 +00002577Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2578 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2579
2580 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Anderson24be4c12009-07-03 00:17:18 +00002581 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002582 return BinaryOperator::CreateFAdd(Op0, V);
2583
2584 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2585 if (Op1I->getOpcode() == Instruction::FAdd) {
2586 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002587 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2588 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002589 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson15b39322009-07-13 04:09:18 +00002590 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2591 I.getName());
Dan Gohman7ce405e2009-06-04 22:49:04 +00002592 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002593 }
2594
2595 return 0;
2596}
2597
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2599/// comparison only checks the sign bit. If it only checks the sign bit, set
2600/// TrueIfSigned if the result of the comparison is true when the input value is
2601/// signed.
2602static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2603 bool &TrueIfSigned) {
2604 switch (pred) {
2605 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2606 TrueIfSigned = true;
2607 return RHS->isZero();
2608 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2609 TrueIfSigned = true;
2610 return RHS->isAllOnesValue();
2611 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2612 TrueIfSigned = false;
2613 return RHS->isAllOnesValue();
2614 case ICmpInst::ICMP_UGT:
2615 // True if LHS u> RHS and RHS == high-bit-mask - 1
2616 TrueIfSigned = true;
2617 return RHS->getValue() ==
2618 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2619 case ICmpInst::ICMP_UGE:
2620 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2621 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002622 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623 default:
2624 return false;
2625 }
2626}
2627
2628Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2629 bool Changed = SimplifyCommutative(I);
2630 Value *Op0 = I.getOperand(0);
2631
Eli Friedmane426ded2009-07-18 09:12:15 +00002632 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00002633 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002634
2635 // Simplify mul instructions with a constant RHS...
2636 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2637 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2638
2639 // ((X << C1)*C2) == (X * (C2 << C1))
2640 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2641 if (SI->getOpcode() == Instruction::Shl)
2642 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002643 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002644 Context->getConstantExprShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645
2646 if (CI->isZero())
2647 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2648 if (CI->equalsInt(1)) // X * 1 == X
2649 return ReplaceInstUsesWith(I, Op0);
2650 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson15b39322009-07-13 04:09:18 +00002651 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002652
2653 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2654 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002655 return BinaryOperator::CreateShl(Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00002656 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002657 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002658 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedman6e058402009-07-14 02:01:53 +00002659 if (Op1->isNullValue())
2660 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002661
2662 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2663 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson15b39322009-07-13 04:09:18 +00002664 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky94418732008-11-27 20:21:08 +00002665
2666 // As above, vector X*splat(1.0) -> X in all defined cases.
2667 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002668 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2669 if (CI->equalsInt(1))
2670 return ReplaceInstUsesWith(I, Op0);
2671 }
2672 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 }
2674
2675 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2676 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002677 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002679 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680 Op1, "tmp");
2681 InsertNewInstBefore(Add, I);
Owen Anderson24be4c12009-07-03 00:17:18 +00002682 Value *C1C2 = Context->getConstantExprMul(Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002683 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002685
2686 }
2687
2688 // Try to fold constant mul into select arguments.
2689 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2690 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2691 return R;
2692
2693 if (isa<PHINode>(Op0))
2694 if (Instruction *NV = FoldOpIntoPhi(I))
2695 return NV;
2696 }
2697
Owen Anderson24be4c12009-07-03 00:17:18 +00002698 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2699 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002700 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002701
Nick Lewycky1c246402008-11-21 07:33:58 +00002702 // (X / Y) * Y = X - (X % Y)
2703 // (X / Y) * -Y = (X % Y) - X
2704 {
2705 Value *Op1 = I.getOperand(1);
2706 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2707 if (!BO ||
2708 (BO->getOpcode() != Instruction::UDiv &&
2709 BO->getOpcode() != Instruction::SDiv)) {
2710 Op1 = Op0;
2711 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2712 }
Owen Anderson24be4c12009-07-03 00:17:18 +00002713 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky1c246402008-11-21 07:33:58 +00002714 if (BO && BO->hasOneUse() &&
2715 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2716 (BO->getOpcode() == Instruction::UDiv ||
2717 BO->getOpcode() == Instruction::SDiv)) {
2718 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2719
2720 Instruction *Rem;
2721 if (BO->getOpcode() == Instruction::UDiv)
2722 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2723 else
2724 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2725
2726 InsertNewInstBefore(Rem, I);
2727 Rem->takeName(BO);
2728
2729 if (Op1BO == Op1)
2730 return BinaryOperator::CreateSub(Op0BO, Rem);
2731 else
2732 return BinaryOperator::CreateSub(Rem, Op0BO);
2733 }
2734 }
2735
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002736 if (I.getType() == Type::Int1Ty)
2737 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2738
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 // If one of the operands of the multiply is a cast from a boolean value, then
2740 // we know the bool is either zero or one, so this is a 'masking' multiply.
2741 // See if we can simplify things based on how the boolean was originally
2742 // formed.
2743 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002744 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2746 BoolCast = CI;
2747 if (!BoolCast)
2748 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2749 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2750 BoolCast = CI;
2751 if (BoolCast) {
2752 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2753 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2754 const Type *SCOpTy = SCIOp0->getType();
2755 bool TIS = false;
2756
2757 // If the icmp is true iff the sign bit of X is set, then convert this
2758 // multiply into a shift/and combination.
2759 if (isa<ConstantInt>(SCIOp1) &&
2760 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2761 TIS) {
2762 // Shift the X value right to turn it into "all signbits".
Owen Anderson24be4c12009-07-03 00:17:18 +00002763 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002764 SCOpTy->getPrimitiveSizeInBits()-1);
2765 Value *V =
2766 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002767 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 BoolCast->getOperand(0)->getName()+
2769 ".mask"), I);
2770
2771 // If the multiply type is not the same as the source type, sign extend
2772 // or truncate to the multiply type.
2773 if (I.getType() != V->getType()) {
2774 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2775 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2776 Instruction::CastOps opcode =
2777 (SrcBits == DstBits ? Instruction::BitCast :
2778 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2779 V = InsertCastBefore(opcode, V, I.getType(), I);
2780 }
2781
2782 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002783 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002784 }
2785 }
2786 }
2787
2788 return Changed ? &I : 0;
2789}
2790
Dan Gohman7ce405e2009-06-04 22:49:04 +00002791Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2792 bool Changed = SimplifyCommutative(I);
2793 Value *Op0 = I.getOperand(0);
2794
2795 // Simplify mul instructions with a constant RHS...
2796 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2797 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2798 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2799 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2800 if (Op1F->isExactlyValue(1.0))
2801 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2802 } else if (isa<VectorType>(Op1->getType())) {
2803 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2804 // As above, vector X*splat(1.0) -> X in all defined cases.
2805 if (Constant *Splat = Op1V->getSplatValue()) {
2806 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2807 if (F->isExactlyValue(1.0))
2808 return ReplaceInstUsesWith(I, Op0);
2809 }
2810 }
2811 }
2812
2813 // Try to fold constant mul into select arguments.
2814 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2815 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2816 return R;
2817
2818 if (isa<PHINode>(Op0))
2819 if (Instruction *NV = FoldOpIntoPhi(I))
2820 return NV;
2821 }
2822
Owen Anderson24be4c12009-07-03 00:17:18 +00002823 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2824 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002825 return BinaryOperator::CreateFMul(Op0v, Op1v);
2826
2827 return Changed ? &I : 0;
2828}
2829
Chris Lattner76972db2008-07-14 00:15:52 +00002830/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2831/// instruction.
2832bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2833 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2834
2835 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2836 int NonNullOperand = -1;
2837 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2838 if (ST->isNullValue())
2839 NonNullOperand = 2;
2840 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2841 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2842 if (ST->isNullValue())
2843 NonNullOperand = 1;
2844
2845 if (NonNullOperand == -1)
2846 return false;
2847
2848 Value *SelectCond = SI->getOperand(0);
2849
2850 // Change the div/rem to use 'Y' instead of the select.
2851 I.setOperand(1, SI->getOperand(NonNullOperand));
2852
2853 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2854 // problem. However, the select, or the condition of the select may have
2855 // multiple uses. Based on our knowledge that the operand must be non-zero,
2856 // propagate the known value for the select into other uses of it, and
2857 // propagate a known value of the condition into its other users.
2858
2859 // If the select and condition only have a single use, don't bother with this,
2860 // early exit.
2861 if (SI->use_empty() && SelectCond->hasOneUse())
2862 return true;
2863
2864 // Scan the current block backward, looking for other uses of SI.
2865 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2866
2867 while (BBI != BBFront) {
2868 --BBI;
2869 // If we found a call to a function, we can't assume it will return, so
2870 // information from below it cannot be propagated above it.
2871 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2872 break;
2873
2874 // Replace uses of the select or its condition with the known values.
2875 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2876 I != E; ++I) {
2877 if (*I == SI) {
2878 *I = SI->getOperand(NonNullOperand);
2879 AddToWorkList(BBI);
2880 } else if (*I == SelectCond) {
Owen Anderson71f286c62009-07-21 18:03:38 +00002881 *I = NonNullOperand == 1 ? Context->getTrue() :
2882 Context->getFalse();
Chris Lattner76972db2008-07-14 00:15:52 +00002883 AddToWorkList(BBI);
2884 }
2885 }
2886
2887 // If we past the instruction, quit looking for it.
2888 if (&*BBI == SI)
2889 SI = 0;
2890 if (&*BBI == SelectCond)
2891 SelectCond = 0;
2892
2893 // If we ran out of things to eliminate, break out of the loop.
2894 if (SelectCond == 0 && SI == 0)
2895 break;
2896
2897 }
2898 return true;
2899}
2900
2901
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002902/// This function implements the transforms on div instructions that work
2903/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2904/// used by the visitors to those instructions.
2905/// @brief Transforms common to all three div instructions
2906Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2908
Chris Lattner653ef3c2008-02-19 06:12:18 +00002909 // undef / X -> 0 for integer.
2910 // undef / X -> undef for FP (the undef could be a snan).
2911 if (isa<UndefValue>(Op0)) {
2912 if (Op0->getType()->isFPOrFPVector())
2913 return ReplaceInstUsesWith(I, Op0);
Owen Anderson24be4c12009-07-03 00:17:18 +00002914 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002915 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002916
2917 // X / undef -> undef
2918 if (isa<UndefValue>(Op1))
2919 return ReplaceInstUsesWith(I, Op1);
2920
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921 return 0;
2922}
2923
2924/// This function implements the transforms common to both integer division
2925/// instructions (udiv and sdiv). It is called by the visitors to those integer
2926/// division instructions.
2927/// @brief Common integer divide transforms
2928Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2929 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2930
Chris Lattnercefb36c2008-05-16 02:59:42 +00002931 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002932 if (Op0 == Op1) {
2933 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002934 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002935 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00002936 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002937 }
2938
Owen Anderson24be4c12009-07-03 00:17:18 +00002939 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002940 return ReplaceInstUsesWith(I, CI);
2941 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002942
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002943 if (Instruction *Common = commonDivTransforms(I))
2944 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002945
2946 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2947 // This does not apply for fdiv.
2948 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2949 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950
2951 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2952 // div X, 1 == X
2953 if (RHS->equalsInt(1))
2954 return ReplaceInstUsesWith(I, Op0);
2955
2956 // (X / C1) / C2 -> X / (C1*C2)
2957 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2958 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2959 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002960 if (MultiplyOverflows(RHS, LHSRHS,
2961 I.getOpcode()==Instruction::SDiv, Context))
2962 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002963 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002964 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002965 Context->getConstantExprMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 }
2967
2968 if (!RHS->isZero()) { // avoid X udiv 0
2969 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2971 return R;
2972 if (isa<PHINode>(Op0))
2973 if (Instruction *NV = FoldOpIntoPhi(I))
2974 return NV;
2975 }
2976 }
2977
2978 // 0 / X == 0, we don't need to preserve faults!
2979 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2980 if (LHS->equalsInt(0))
Owen Anderson24be4c12009-07-03 00:17:18 +00002981 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002982
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002983 // It can't be division by zero, hence it must be division by one.
2984 if (I.getType() == Type::Int1Ty)
2985 return ReplaceInstUsesWith(I, Op0);
2986
Nick Lewycky94418732008-11-27 20:21:08 +00002987 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2988 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2989 // div X, 1 == X
2990 if (X->isOne())
2991 return ReplaceInstUsesWith(I, Op0);
2992 }
2993
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002994 return 0;
2995}
2996
2997Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2998 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2999
3000 // Handle the integer div common cases
3001 if (Instruction *Common = commonIDivTransforms(I))
3002 return Common;
3003
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003004 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003005 // X udiv C^2 -> X >> C
3006 // Check to see if this is an unsigned division with an exact power of 2,
3007 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003008 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateLShr(Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00003010 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003011
3012 // X udiv C, where C >= signbit
3013 if (C->getValue().isNegative()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00003014 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3015 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky240182a2008-11-27 22:41:10 +00003016 I);
Owen Anderson24be4c12009-07-03 00:17:18 +00003017 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3018 Context->getConstantInt(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003019 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 }
3021
3022 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3023 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3024 if (RHSI->getOpcode() == Instruction::Shl &&
3025 isa<ConstantInt>(RHSI->getOperand(0))) {
3026 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3027 if (C1.isPowerOf2()) {
3028 Value *N = RHSI->getOperand(1);
3029 const Type *NTy = N->getType();
3030 if (uint32_t C2 = C1.logBase2()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003031 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003032 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 }
3036 }
3037 }
3038
3039 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040 // where C1&C2 are powers of two.
3041 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3042 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3043 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3044 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3045 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3046 // Compute the shift amounts
3047 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3048 // Construct the "on true" case of the select
Owen Anderson24be4c12009-07-03 00:17:18 +00003049 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003050 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003051 Op0, TC, SI->getName()+".t");
3052 TSI = InsertNewInstBefore(TSI, I);
3053
3054 // Construct the "on false" case of the select
Owen Anderson24be4c12009-07-03 00:17:18 +00003055 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003056 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003057 Op0, FC, SI->getName()+".f");
3058 FSI = InsertNewInstBefore(FSI, I);
3059
3060 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003061 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003062 }
3063 }
3064 return 0;
3065}
3066
3067Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3068 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069
3070 // Handle the integer div common cases
3071 if (Instruction *Common = commonIDivTransforms(I))
3072 return Common;
3073
3074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075 // sdiv X, -1 == -X
3076 if (RHS->isAllOnesValue())
Owen Anderson15b39322009-07-13 04:09:18 +00003077 return BinaryOperator::CreateNeg(*Context, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003078 }
3079
3080 // If the sign bits of both operands are zero (i.e. we can prove they are
3081 // unsigned inputs), turn this into a udiv.
3082 if (I.getType()->isInteger()) {
3083 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedmana17b85f2009-07-18 09:53:21 +00003084 if (MaskedValueIsZero(Op0, Mask)) {
3085 if (MaskedValueIsZero(Op1, Mask)) {
3086 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3087 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3088 }
3089 ConstantInt *ShiftedInt;
3090 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3091 ShiftedInt->getValue().isPowerOf2()) {
3092 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3093 // Safe because the only negative value (1 << Y) can take on is
3094 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3095 // the sign bit set.
3096 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3097 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003098 }
Eli Friedmana17b85f2009-07-18 09:53:21 +00003099 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003100
3101 return 0;
3102}
3103
3104Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3105 return commonDivTransforms(I);
3106}
3107
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108/// This function implements the transforms on rem instructions that work
3109/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3110/// is used by the visitors to those instructions.
3111/// @brief Transforms common to all three rem instructions
3112Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3113 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3114
Chris Lattner653ef3c2008-02-19 06:12:18 +00003115 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3116 if (I.getType()->isFPOrFPVector())
3117 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Anderson24be4c12009-07-03 00:17:18 +00003118 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003119 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120 if (isa<UndefValue>(Op1))
3121 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3122
3123 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003124 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3125 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003126
3127 return 0;
3128}
3129
3130/// This function implements the transforms common to both integer remainder
3131/// instructions (urem and srem). It is called by the visitors to those integer
3132/// remainder instructions.
3133/// @brief Common integer remainder transforms
3134Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3136
3137 if (Instruction *common = commonRemTransforms(I))
3138 return common;
3139
Dale Johannesena51f7372009-01-21 00:35:19 +00003140 // 0 % X == 0 for integer, we don't need to preserve faults!
3141 if (Constant *LHS = dyn_cast<Constant>(Op0))
3142 if (LHS->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00003143 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003144
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3146 // X % 0 == undef, we don't need to preserve faults!
3147 if (RHS->equalsInt(0))
Owen Anderson24be4c12009-07-03 00:17:18 +00003148 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149
3150 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Anderson24be4c12009-07-03 00:17:18 +00003151 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003152
3153 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3154 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3155 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3156 return R;
3157 } else if (isa<PHINode>(Op0I)) {
3158 if (Instruction *NV = FoldOpIntoPhi(I))
3159 return NV;
3160 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003161
3162 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003163 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003164 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003165 }
3166 }
3167
3168 return 0;
3169}
3170
3171Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3173
3174 if (Instruction *common = commonIRemTransforms(I))
3175 return common;
3176
3177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3178 // X urem C^2 -> X and C
3179 // Check to see if this is an unsigned remainder with an exact power of 2,
3180 // if so, convert to a bitwise and.
3181 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3182 if (C->getValue().isPowerOf2())
Owen Anderson24be4c12009-07-03 00:17:18 +00003183 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 }
3185
3186 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3187 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3188 if (RHSI->getOpcode() == Instruction::Shl &&
3189 isa<ConstantInt>(RHSI->getOperand(0))) {
3190 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson035d41d2009-07-13 20:58:05 +00003191 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003192 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003193 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003194 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195 }
3196 }
3197 }
3198
3199 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3200 // where C1&C2 are powers of two.
3201 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3202 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3203 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3204 // STO == 0 and SFO == 0 handled above.
3205 if ((STO->getValue().isPowerOf2()) &&
3206 (SFO->getValue().isPowerOf2())) {
3207 Value *TrueAnd = InsertNewInstBefore(
Owen Anderson24be4c12009-07-03 00:17:18 +00003208 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3209 SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003210 Value *FalseAnd = InsertNewInstBefore(
Owen Anderson24be4c12009-07-03 00:17:18 +00003211 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3212 SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003213 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 }
3215 }
3216 }
3217
3218 return 0;
3219}
3220
3221Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3223
Dan Gohmandb3dd962007-11-05 23:16:33 +00003224 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003225 if (Instruction *common = commonIRemTransforms(I))
3226 return common;
3227
Owen Anderson24be4c12009-07-03 00:17:18 +00003228 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003229 if (!isa<Constant>(RHSNeg) ||
3230 (isa<ConstantInt>(RHSNeg) &&
3231 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003232 // X % -Y -> X % Y
3233 AddUsesToWorkList(I);
3234 I.setOperand(1, RHSNeg);
3235 return &I;
3236 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003237
Dan Gohmandb3dd962007-11-05 23:16:33 +00003238 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003239 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003240 if (I.getType()->isInteger()) {
3241 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3242 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3243 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003244 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003245 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003246 }
3247
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003248 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003249 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3250 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003251
Nick Lewyckyfd746832008-12-20 16:48:00 +00003252 bool hasNegative = false;
3253 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3254 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3255 if (RHS->getValue().isNegative())
3256 hasNegative = true;
3257
3258 if (hasNegative) {
3259 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003260 for (unsigned i = 0; i != VWidth; ++i) {
3261 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3262 if (RHS->getValue().isNegative())
Owen Anderson24be4c12009-07-03 00:17:18 +00003263 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003264 else
3265 Elts[i] = RHS;
3266 }
3267 }
3268
Owen Anderson24be4c12009-07-03 00:17:18 +00003269 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003270 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003271 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003272 I.setOperand(1, NewRHSV);
3273 return &I;
3274 }
3275 }
3276 }
3277
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 return 0;
3279}
3280
3281Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3282 return commonRemTransforms(I);
3283}
3284
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003285// isOneBitSet - Return true if there is exactly one bit set in the specified
3286// constant.
3287static bool isOneBitSet(const ConstantInt *CI) {
3288 return CI->getValue().isPowerOf2();
3289}
3290
3291// isHighOnes - Return true if the constant is of the form 1+0+.
3292// This is the same as lowones(~X).
3293static bool isHighOnes(const ConstantInt *CI) {
3294 return (~CI->getValue() + 1).isPowerOf2();
3295}
3296
3297/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3298/// are carefully arranged to allow folding of expressions such as:
3299///
3300/// (A < B) | (A > B) --> (A != B)
3301///
3302/// Note that this is only valid if the first and second predicates have the
3303/// same sign. Is illegal to do: (A u< B) | (A s> B)
3304///
3305/// Three bits are used to represent the condition, as follows:
3306/// 0 A > B
3307/// 1 A == B
3308/// 2 A < B
3309///
3310/// <=> Value Definition
3311/// 000 0 Always false
3312/// 001 1 A > B
3313/// 010 2 A == B
3314/// 011 3 A >= B
3315/// 100 4 A < B
3316/// 101 5 A != B
3317/// 110 6 A <= B
3318/// 111 7 Always true
3319///
3320static unsigned getICmpCode(const ICmpInst *ICI) {
3321 switch (ICI->getPredicate()) {
3322 // False -> 0
3323 case ICmpInst::ICMP_UGT: return 1; // 001
3324 case ICmpInst::ICMP_SGT: return 1; // 001
3325 case ICmpInst::ICMP_EQ: return 2; // 010
3326 case ICmpInst::ICMP_UGE: return 3; // 011
3327 case ICmpInst::ICMP_SGE: return 3; // 011
3328 case ICmpInst::ICMP_ULT: return 4; // 100
3329 case ICmpInst::ICMP_SLT: return 4; // 100
3330 case ICmpInst::ICMP_NE: return 5; // 101
3331 case ICmpInst::ICMP_ULE: return 6; // 110
3332 case ICmpInst::ICMP_SLE: return 6; // 110
3333 // True -> 7
3334 default:
Edwin Törökbd448e32009-07-14 16:55:14 +00003335 llvm_unreachable("Invalid ICmp predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003336 return 0;
3337 }
3338}
3339
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003340/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3341/// predicate into a three bit mask. It also returns whether it is an ordered
3342/// predicate by reference.
3343static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3344 isOrdered = false;
3345 switch (CC) {
3346 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3347 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003348 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3349 case FCmpInst::FCMP_UGT: return 1; // 001
3350 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3351 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003352 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3353 case FCmpInst::FCMP_UGE: return 3; // 011
3354 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3355 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003356 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3357 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003358 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3359 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003360 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003361 default:
3362 // Not expecting FCMP_FALSE and FCMP_TRUE;
Edwin Törökbd448e32009-07-14 16:55:14 +00003363 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003364 return 0;
3365 }
3366}
3367
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003368/// getICmpValue - This is the complement of getICmpCode, which turns an
3369/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003370/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003371/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003372static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003373 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003375 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson71f286c62009-07-21 18:03:38 +00003376 case 0: return Context->getFalse();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 case 1:
3378 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003379 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, 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_UGT, LHS, RHS);
3382 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003383 case 3:
3384 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, 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_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003388 case 4:
3389 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003390 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003392 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3393 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003394 case 6:
3395 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003396 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003397 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003398 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson71f286c62009-07-21 18:03:38 +00003399 case 7: return Context->getTrue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003400 }
3401}
3402
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003403/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3404/// opcode and two operands into either a FCmp instruction. isordered is passed
3405/// in to determine which kind of predicate to use in the new fcmp instruction.
3406static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003407 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003408 switch (code) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003409 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003410 case 0:
3411 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003412 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003413 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003414 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003415 case 1:
3416 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003417 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003418 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003419 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003420 case 2:
3421 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003423 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003424 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003425 case 3:
3426 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003428 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003429 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003430 case 4:
3431 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003433 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003434 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003435 case 5:
3436 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003438 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003439 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003440 case 6:
3441 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003443 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson71f286c62009-07-21 18:03:38 +00003445 case 7: return Context->getTrue();
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003446 }
3447}
3448
Chris Lattner2972b822008-11-16 04:55:20 +00003449/// PredicatesFoldable - Return true if both predicates match sign or if at
3450/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003451static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3452 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003453 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3454 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455}
3456
3457namespace {
3458// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3459struct FoldICmpLogical {
3460 InstCombiner &IC;
3461 Value *LHS, *RHS;
3462 ICmpInst::Predicate pred;
3463 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3464 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3465 pred(ICI->getPredicate()) {}
3466 bool shouldApply(Value *V) const {
3467 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3468 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003469 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3470 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003471 return false;
3472 }
3473 Instruction *apply(Instruction &Log) const {
3474 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3475 if (ICI->getOperand(0) != LHS) {
3476 assert(ICI->getOperand(1) == LHS);
3477 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3478 }
3479
3480 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3481 unsigned LHSCode = getICmpCode(ICI);
3482 unsigned RHSCode = getICmpCode(RHSICI);
3483 unsigned Code;
3484 switch (Log.getOpcode()) {
3485 case Instruction::And: Code = LHSCode & RHSCode; break;
3486 case Instruction::Or: Code = LHSCode | RHSCode; break;
3487 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Edwin Törökbd448e32009-07-14 16:55:14 +00003488 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489 }
3490
3491 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3492 ICmpInst::isSignedPredicate(ICI->getPredicate());
3493
Owen Anderson24be4c12009-07-03 00:17:18 +00003494 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 if (Instruction *I = dyn_cast<Instruction>(RV))
3496 return I;
3497 // Otherwise, it's a constant boolean value...
3498 return IC.ReplaceInstUsesWith(Log, RV);
3499 }
3500};
3501} // end anonymous namespace
3502
3503// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3504// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3505// guaranteed to be a binary operator.
3506Instruction *InstCombiner::OptAndOp(Instruction *Op,
3507 ConstantInt *OpRHS,
3508 ConstantInt *AndRHS,
3509 BinaryOperator &TheAnd) {
3510 Value *X = Op->getOperand(0);
3511 Constant *Together = 0;
3512 if (!Op->isShift())
Owen Anderson24be4c12009-07-03 00:17:18 +00003513 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514
3515 switch (Op->getOpcode()) {
3516 case Instruction::Xor:
3517 if (Op->hasOneUse()) {
3518 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003519 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520 InsertNewInstBefore(And, TheAnd);
3521 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003522 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003523 }
3524 break;
3525 case Instruction::Or:
3526 if (Together == AndRHS) // (X | C) & C --> C
3527 return ReplaceInstUsesWith(TheAnd, AndRHS);
3528
3529 if (Op->hasOneUse() && Together != OpRHS) {
3530 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003531 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003532 InsertNewInstBefore(Or, TheAnd);
3533 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003534 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003535 }
3536 break;
3537 case Instruction::Add:
3538 if (Op->hasOneUse()) {
3539 // Adding a one to a single bit bit-field should be turned into an XOR
3540 // of the bit. First thing to check is to see if this AND is with a
3541 // single bit constant.
3542 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3543
3544 // If there is only one bit set...
3545 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3546 // Ok, at this point, we know that we are masking the result of the
3547 // ADD down to exactly one bit. If the constant we are adding has
3548 // no bits set below this bit, then we can eliminate the ADD.
3549 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3550
3551 // Check to see if any bits below the one bit set in AndRHSV are set.
3552 if ((AddRHS & (AndRHSV-1)) == 0) {
3553 // If not, the only thing that can effect the output of the AND is
3554 // the bit specified by AndRHSV. If that bit is set, the effect of
3555 // the XOR is to toggle the bit. If it is clear, then the ADD has
3556 // no effect.
3557 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3558 TheAnd.setOperand(0, X);
3559 return &TheAnd;
3560 } else {
3561 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003562 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003563 InsertNewInstBefore(NewAnd, TheAnd);
3564 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003565 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003566 }
3567 }
3568 }
3569 }
3570 break;
3571
3572 case Instruction::Shl: {
3573 // We know that the AND will not produce any of the bits shifted in, so if
3574 // the anded constant includes them, clear them now!
3575 //
3576 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3577 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3578 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00003579 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003580
3581 if (CI->getValue() == ShlMask) {
3582 // Masking out bits that the shift already masks
3583 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3584 } else if (CI != AndRHS) { // Reducing bits set in and.
3585 TheAnd.setOperand(1, CI);
3586 return &TheAnd;
3587 }
3588 break;
3589 }
3590 case Instruction::LShr:
3591 {
3592 // We know that the AND will not produce any of the bits shifted in, so if
3593 // the anded constant includes them, clear them now! This only applies to
3594 // unsigned shifts, because a signed shr may bring in set bits!
3595 //
3596 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3597 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3598 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00003599 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003600
3601 if (CI->getValue() == ShrMask) {
3602 // Masking out bits that the shift already masks.
3603 return ReplaceInstUsesWith(TheAnd, Op);
3604 } else if (CI != AndRHS) {
3605 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3606 return &TheAnd;
3607 }
3608 break;
3609 }
3610 case Instruction::AShr:
3611 // Signed shr.
3612 // See if this is shifting in some sign extension, then masking it out
3613 // with an and.
3614 if (Op->hasOneUse()) {
3615 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3616 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3617 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00003618 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003619 if (C == AndRHS) { // Masking out bits shifted in.
3620 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3621 // Make the argument unsigned.
3622 Value *ShVal = Op->getOperand(0);
3623 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003624 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003625 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003626 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003627 }
3628 }
3629 break;
3630 }
3631 return 0;
3632}
3633
3634
3635/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3636/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3637/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3638/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3639/// insert new instructions.
3640Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3641 bool isSigned, bool Inside,
3642 Instruction &IB) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003643 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003644 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3645 "Lo is not <= Hi in range emission code!");
3646
3647 if (Inside) {
3648 if (Lo == Hi) // Trivially false.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003649 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650
3651 // V >= Min && V < Hi --> V < Hi
3652 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3653 ICmpInst::Predicate pred = (isSigned ?
3654 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003655 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003656 }
3657
3658 // Emit V-Lo <u Hi-Lo
Owen Anderson24be4c12009-07-03 00:17:18 +00003659 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003660 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003661 InsertNewInstBefore(Add, IB);
Owen Anderson24be4c12009-07-03 00:17:18 +00003662 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003663 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003664 }
3665
3666 if (Lo == Hi) // Trivially true.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003667 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668
3669 // V < Min || V >= Hi -> V > Hi-1
Owen Anderson24be4c12009-07-03 00:17:18 +00003670 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003671 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3672 ICmpInst::Predicate pred = (isSigned ?
3673 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003674 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003675 }
3676
3677 // Emit V-Lo >u Hi-1-Lo
3678 // Note that Hi has already had one subtracted from it, above.
Owen Anderson24be4c12009-07-03 00:17:18 +00003679 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003680 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003681 InsertNewInstBefore(Add, IB);
Owen Anderson24be4c12009-07-03 00:17:18 +00003682 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003683 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003684}
3685
3686// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3687// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3688// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3689// not, since all 1s are not contiguous.
3690static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3691 const APInt& V = Val->getValue();
3692 uint32_t BitWidth = Val->getType()->getBitWidth();
3693 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3694
3695 // look for the first zero bit after the run of ones
3696 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3697 // look for the first non-zero bit
3698 ME = V.getActiveBits();
3699 return true;
3700}
3701
3702/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3703/// where isSub determines whether the operator is a sub. If we can fold one of
3704/// the following xforms:
3705///
3706/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3707/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3709///
3710/// return (A +/- B).
3711///
3712Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3713 ConstantInt *Mask, bool isSub,
3714 Instruction &I) {
3715 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3716 if (!LHSI || LHSI->getNumOperands() != 2 ||
3717 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3718
3719 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3720
3721 switch (LHSI->getOpcode()) {
3722 default: return 0;
3723 case Instruction::And:
Owen Anderson24be4c12009-07-03 00:17:18 +00003724 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003725 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3726 if ((Mask->getValue().countLeadingZeros() +
3727 Mask->getValue().countPopulation()) ==
3728 Mask->getValue().getBitWidth())
3729 break;
3730
3731 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3732 // part, we don't need any explicit masks to take them out of A. If that
3733 // is all N is, ignore it.
3734 uint32_t MB = 0, ME = 0;
3735 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3736 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3737 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3738 if (MaskedValueIsZero(RHS, Mask))
3739 break;
3740 }
3741 }
3742 return 0;
3743 case Instruction::Or:
3744 case Instruction::Xor:
3745 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson24be4c12009-07-03 00:17:18 +00003748 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003749 break;
3750 return 0;
3751 }
3752
3753 Instruction *New;
3754 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003755 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003756 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003757 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003758 return InsertNewInstBefore(New, I);
3759}
3760
Chris Lattner0631ea72008-11-16 05:06:21 +00003761/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3762Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3763 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003764 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003765 ConstantInt *LHSCst, *RHSCst;
3766 ICmpInst::Predicate LHSCC, RHSCC;
3767
Chris Lattnerf3803482008-11-16 05:10:52 +00003768 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003769 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3770 m_ConstantInt(LHSCst)), *Context) ||
3771 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3772 m_ConstantInt(RHSCst)), *Context))
Chris Lattner0631ea72008-11-16 05:06:21 +00003773 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003774
3775 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3776 // where C is a power of 2
3777 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3778 LHSCst->getValue().isPowerOf2()) {
3779 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3780 InsertNewInstBefore(NewOr, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003781 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003782 }
3783
3784 // From here on, we only handle:
3785 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3786 if (Val != Val2) return 0;
3787
Chris Lattner0631ea72008-11-16 05:06:21 +00003788 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3789 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3790 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3791 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3792 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3793 return 0;
3794
3795 // We can't fold (ugt x, C) & (sgt x, C2).
3796 if (!PredicatesFoldable(LHSCC, RHSCC))
3797 return 0;
3798
3799 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003800 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003801 if (ICmpInst::isSignedPredicate(LHSCC) ||
3802 (ICmpInst::isEquality(LHSCC) &&
3803 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003804 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003805 else
Chris Lattner665298f2008-11-16 05:14:43 +00003806 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3807
3808 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003809 std::swap(LHS, RHS);
3810 std::swap(LHSCst, RHSCst);
3811 std::swap(LHSCC, RHSCC);
3812 }
3813
3814 // At this point, we know we have have two icmp instructions
3815 // comparing a value against two constants and and'ing the result
3816 // together. Because of the above check, we know that we only have
3817 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3818 // (from the FoldICmpLogical check above), that the two constants
3819 // are not equal and that the larger constant is on the RHS
3820 assert(LHSCst != RHSCst && "Compares not folded above?");
3821
3822 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003823 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003824 case ICmpInst::ICMP_EQ:
3825 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003826 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003827 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3828 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3829 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson71f286c62009-07-21 18:03:38 +00003830 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner0631ea72008-11-16 05:06:21 +00003831 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3832 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3833 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3834 return ReplaceInstUsesWith(I, LHS);
3835 }
3836 case ICmpInst::ICMP_NE:
3837 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003838 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003839 case ICmpInst::ICMP_ULT:
Owen Anderson24be4c12009-07-03 00:17:18 +00003840 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003841 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003842 break; // (X != 13 & X u< 15) -> no change
3843 case ICmpInst::ICMP_SLT:
Owen Anderson24be4c12009-07-03 00:17:18 +00003844 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003845 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003846 break; // (X != 13 & X s< 15) -> no change
3847 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3848 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3849 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3850 return ReplaceInstUsesWith(I, RHS);
3851 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003852 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3853 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003854 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3855 Val->getName()+".off");
3856 InsertNewInstBefore(Add, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003857 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Anderson24be4c12009-07-03 00:17:18 +00003858 Context->getConstantInt(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003859 }
3860 break; // (X != 13 & X != 15) -> no change
3861 }
3862 break;
3863 case ICmpInst::ICMP_ULT:
3864 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003865 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003866 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3867 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson71f286c62009-07-21 18:03:38 +00003868 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner0631ea72008-11-16 05:06:21 +00003869 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3870 break;
3871 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3872 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3873 return ReplaceInstUsesWith(I, LHS);
3874 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3875 break;
3876 }
3877 break;
3878 case ICmpInst::ICMP_SLT:
3879 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003880 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3882 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson71f286c62009-07-21 18:03:38 +00003883 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner0631ea72008-11-16 05:06:21 +00003884 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3885 break;
3886 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3887 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3888 return ReplaceInstUsesWith(I, LHS);
3889 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3890 break;
3891 }
3892 break;
3893 case ICmpInst::ICMP_UGT:
3894 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003895 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003896 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3897 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3898 return ReplaceInstUsesWith(I, RHS);
3899 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3900 break;
3901 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003902 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003903 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003904 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003905 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Anderson24be4c12009-07-03 00:17:18 +00003906 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3907 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003908 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3909 break;
3910 }
3911 break;
3912 case ICmpInst::ICMP_SGT:
3913 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00003914 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0631ea72008-11-16 05:06:21 +00003915 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3916 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3917 return ReplaceInstUsesWith(I, RHS);
3918 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3919 break;
3920 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003921 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003922 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003923 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003924 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Anderson24be4c12009-07-03 00:17:18 +00003925 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3926 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003927 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3928 break;
3929 }
3930 break;
3931 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003932
3933 return 0;
3934}
3935
Chris Lattner93a359a2009-07-23 05:14:02 +00003936Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3937 FCmpInst *RHS) {
3938
3939 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3940 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3941 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3942 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3943 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3944 // If either of the constants are nans, then the whole thing returns
3945 // false.
3946 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3947 return ReplaceInstUsesWith(I, Context->getFalse());
3948 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3949 LHS->getOperand(0), RHS->getOperand(0));
3950 }
Chris Lattnercf373552009-07-23 05:32:17 +00003951
3952 // Handle vector zeros. This occurs because the canonical form of
3953 // "fcmp ord x,x" is "fcmp ord x, 0".
3954 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3955 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3956 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3957 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner93a359a2009-07-23 05:14:02 +00003958 return 0;
3959 }
3960
3961 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3962 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3963 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3964
3965
3966 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3967 // Swap RHS operands to match LHS.
3968 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3969 std::swap(Op1LHS, Op1RHS);
3970 }
3971
3972 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3973 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3974 if (Op0CC == Op1CC)
3975 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3976
3977 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3978 return ReplaceInstUsesWith(I, Context->getFalse());
3979 if (Op0CC == FCmpInst::FCMP_TRUE)
3980 return ReplaceInstUsesWith(I, RHS);
3981 if (Op1CC == FCmpInst::FCMP_TRUE)
3982 return ReplaceInstUsesWith(I, LHS);
3983
3984 bool Op0Ordered;
3985 bool Op1Ordered;
3986 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3987 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3988 if (Op1Pred == 0) {
3989 std::swap(LHS, RHS);
3990 std::swap(Op0Pred, Op1Pred);
3991 std::swap(Op0Ordered, Op1Ordered);
3992 }
3993 if (Op0Pred == 0) {
3994 // uno && ueq -> uno && (uno || eq) -> ueq
3995 // ord && olt -> ord && (ord && lt) -> olt
3996 if (Op0Ordered == Op1Ordered)
3997 return ReplaceInstUsesWith(I, RHS);
3998
3999 // uno && oeq -> uno && (ord && eq) -> false
4000 // uno && ord -> false
4001 if (!Op0Ordered)
4002 return ReplaceInstUsesWith(I, Context->getFalse());
4003 // ord && ueq -> ord && (uno || eq) -> oeq
4004 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4005 Op0LHS, Op0RHS, Context));
4006 }
4007 }
4008
4009 return 0;
4010}
4011
Chris Lattner0631ea72008-11-16 05:06:21 +00004012
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004013Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4014 bool Changed = SimplifyCommutative(I);
4015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4016
4017 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00004018 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004019
4020 // and X, X = X
4021 if (Op0 == Op1)
4022 return ReplaceInstUsesWith(I, Op1);
4023
4024 // See if we can simplify any instructions used by the instruction whose sole
4025 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004026 if (SimplifyDemandedInstructionBits(I))
4027 return &I;
4028 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004029 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4030 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4031 return ReplaceInstUsesWith(I, I.getOperand(0));
4032 } else if (isa<ConstantAggregateZero>(Op1)) {
4033 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4034 }
4035 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00004036
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004037 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4038 const APInt& AndRHSMask = AndRHS->getValue();
4039 APInt NotAndRHS(~AndRHSMask);
4040
4041 // Optimize a variety of ((val OP C1) & C2) combinations...
4042 if (isa<BinaryOperator>(Op0)) {
4043 Instruction *Op0I = cast<Instruction>(Op0);
4044 Value *Op0LHS = Op0I->getOperand(0);
4045 Value *Op0RHS = Op0I->getOperand(1);
4046 switch (Op0I->getOpcode()) {
4047 case Instruction::Xor:
4048 case Instruction::Or:
4049 // If the mask is only needed on one incoming arm, push it up.
4050 if (Op0I->hasOneUse()) {
4051 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4052 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004053 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004054 Op0RHS->getName()+".masked");
4055 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004056 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004057 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4058 }
4059 if (!isa<Constant>(Op0RHS) &&
4060 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4061 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004062 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004063 Op0LHS->getName()+".masked");
4064 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004065 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004066 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4067 }
4068 }
4069
4070 break;
4071 case Instruction::Add:
4072 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4073 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4074 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4075 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004076 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004077 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004078 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004079 break;
4080
4081 case Instruction::Sub:
4082 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4083 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4084 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4085 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004086 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004087
Nick Lewyckya349ba42008-07-10 05:51:40 +00004088 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4089 // has 1's for all bits that the subtraction with A might affect.
4090 if (Op0I->hasOneUse()) {
4091 uint32_t BitWidth = AndRHSMask.getBitWidth();
4092 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4093 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4094
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004095 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004096 if (!(A && A->isZero()) && // avoid infinite recursion.
4097 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson15b39322009-07-13 04:09:18 +00004098 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004099 InsertNewInstBefore(NewNeg, I);
4100 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4101 }
4102 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004103 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004104
4105 case Instruction::Shl:
4106 case Instruction::LShr:
4107 // (1 << x) & 1 --> zext(x == 0)
4108 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004109 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00004110 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4111 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004112 InsertNewInstBefore(NewICmp, I);
4113 return new ZExtInst(NewICmp, I.getType());
4114 }
4115 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004116 }
4117
4118 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4119 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4120 return Res;
4121 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4122 // If this is an integer truncation or change from signed-to-unsigned, and
4123 // if the source is an and/or with immediate, transform it. This
4124 // frequently occurs for bitfield accesses.
4125 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4126 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4127 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004128 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004129 if (CastOp->getOpcode() == Instruction::And) {
4130 // Change: and (cast (and X, C1) to T), C2
4131 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4132 // This will fold the two constants together, which may allow
4133 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004134 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135 CastOp->getOperand(0), I.getType(),
4136 CastOp->getName()+".shrunk");
4137 NewCast = InsertNewInstBefore(NewCast, I);
4138 // trunc_or_bitcast(C1)&C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004139 Constant *C3 =
4140 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4141 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004142 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143 } else if (CastOp->getOpcode() == Instruction::Or) {
4144 // Change: and (cast (or X, C1) to T), C2
4145 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004146 Constant *C3 =
4147 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4148 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4149 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004150 return ReplaceInstUsesWith(I, AndRHS);
4151 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004152 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004153 }
4154 }
4155
4156 // Try to fold constant and into select arguments.
4157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4159 return R;
4160 if (isa<PHINode>(Op0))
4161 if (Instruction *NV = FoldOpIntoPhi(I))
4162 return NV;
4163 }
4164
Owen Anderson24be4c12009-07-03 00:17:18 +00004165 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4166 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004167
4168 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Anderson24be4c12009-07-03 00:17:18 +00004169 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170
4171 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4172 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004173 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004174 I.getName()+".demorgan");
4175 InsertNewInstBefore(Or, I);
Owen Anderson035d41d2009-07-13 20:58:05 +00004176 return BinaryOperator::CreateNot(*Context, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004177 }
4178
4179 {
4180 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004181 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004182 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4183 return ReplaceInstUsesWith(I, Op1);
4184
4185 // (A|B) & ~(A&B) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004186 if (match(Op1, 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
Owen Andersona21eb582009-07-10 17:35:01 +00004192 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4194 return ReplaceInstUsesWith(I, Op0);
4195
4196 // ~(A&B) & (A|B) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004197 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004198 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004199 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004200 }
4201 }
4202
4203 if (Op0->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004204 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004205 if (A == Op1) { // (A^B)&A -> A&(A^B)
4206 I.swapOperands(); // Simplify below
4207 std::swap(Op0, Op1);
4208 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4209 cast<BinaryOperator>(Op0)->swapOperands();
4210 I.swapOperands(); // Simplify below
4211 std::swap(Op0, Op1);
4212 }
4213 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004214
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004215 if (Op1->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004216 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004217 if (B == Op0) { // B&(A^B) -> B&(B^A)
4218 cast<BinaryOperator>(Op1)->swapOperands();
4219 std::swap(A, B);
4220 }
4221 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson035d41d2009-07-13 20:58:05 +00004222 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004223 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004224 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225 }
4226 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004227
4228 // (A&((~A)|B)) -> A&B
Owen Andersona21eb582009-07-10 17:35:01 +00004229 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4230 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattner9db479f2008-12-01 05:16:26 +00004231 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersona21eb582009-07-10 17:35:01 +00004232 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4233 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattner9db479f2008-12-01 05:16:26 +00004234 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235 }
4236
4237 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4238 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Anderson24be4c12009-07-03 00:17:18 +00004239 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004240 return R;
4241
Chris Lattner0631ea72008-11-16 05:06:21 +00004242 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4243 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4244 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 }
4246
4247 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4248 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4249 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4250 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4251 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004252 if (SrcTy == Op1C->getOperand(0)->getType() &&
4253 SrcTy->isIntOrIntVector() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004254 // Only do this if the casts both really cause code to be generated.
4255 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4256 I.getType(), TD) &&
4257 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4258 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004259 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004260 Op1C->getOperand(0),
4261 I.getName());
4262 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004263 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004264 }
4265 }
4266
4267 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4268 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4269 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4270 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4271 SI0->getOperand(1) == SI1->getOperand(1) &&
4272 (SI0->hasOneUse() || SI1->hasOneUse())) {
4273 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004274 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004275 SI1->getOperand(0),
4276 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004277 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004278 SI1->getOperand(1));
4279 }
4280 }
4281
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004282 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004283 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner93a359a2009-07-23 05:14:02 +00004284 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4285 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4286 return Res;
Chris Lattner91882432007-10-24 05:38:08 +00004287 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004288
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004289 return Changed ? &I : 0;
4290}
4291
Chris Lattner567f5112008-10-05 02:13:19 +00004292/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4293/// capable of providing pieces of a bswap. The subexpression provides pieces
4294/// of a bswap if it is proven that each of the non-zero bytes in the output of
4295/// the expression came from the corresponding "byte swapped" byte in some other
4296/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4297/// we know that the expression deposits the low byte of %X into the high byte
4298/// of the bswap result and that all other bytes are zero. This expression is
4299/// accepted, the high byte of ByteValues is set to X to indicate a correct
4300/// match.
4301///
4302/// This function returns true if the match was unsuccessful and false if so.
4303/// On entry to the function the "OverallLeftShift" is a signed integer value
4304/// indicating the number of bytes that the subexpression is later shifted. For
4305/// example, if the expression is later right shifted by 16 bits, the
4306/// OverallLeftShift value would be -2 on entry. This is used to specify which
4307/// byte of ByteValues is actually being set.
4308///
4309/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4310/// byte is masked to zero by a user. For example, in (X & 255), X will be
4311/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4312/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4313/// always in the local (OverallLeftShift) coordinate space.
4314///
4315static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4316 SmallVector<Value*, 8> &ByteValues) {
4317 if (Instruction *I = dyn_cast<Instruction>(V)) {
4318 // If this is an or instruction, it may be an inner node of the bswap.
4319 if (I->getOpcode() == Instruction::Or) {
4320 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4321 ByteValues) ||
4322 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4323 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004324 }
Chris Lattner567f5112008-10-05 02:13:19 +00004325
4326 // If this is a logical shift by a constant multiple of 8, recurse with
4327 // OverallLeftShift and ByteMask adjusted.
4328 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4329 unsigned ShAmt =
4330 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4331 // Ensure the shift amount is defined and of a byte value.
4332 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4333 return true;
4334
4335 unsigned ByteShift = ShAmt >> 3;
4336 if (I->getOpcode() == Instruction::Shl) {
4337 // X << 2 -> collect(X, +2)
4338 OverallLeftShift += ByteShift;
4339 ByteMask >>= ByteShift;
4340 } else {
4341 // X >>u 2 -> collect(X, -2)
4342 OverallLeftShift -= ByteShift;
4343 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004344 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004345 }
4346
4347 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4348 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4349
4350 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4351 ByteValues);
4352 }
4353
4354 // If this is a logical 'and' with a mask that clears bytes, clear the
4355 // corresponding bytes in ByteMask.
4356 if (I->getOpcode() == Instruction::And &&
4357 isa<ConstantInt>(I->getOperand(1))) {
4358 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4359 unsigned NumBytes = ByteValues.size();
4360 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4361 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4362
4363 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4364 // If this byte is masked out by a later operation, we don't care what
4365 // the and mask is.
4366 if ((ByteMask & (1 << i)) == 0)
4367 continue;
4368
4369 // If the AndMask is all zeros for this byte, clear the bit.
4370 APInt MaskB = AndMask & Byte;
4371 if (MaskB == 0) {
4372 ByteMask &= ~(1U << i);
4373 continue;
4374 }
4375
4376 // If the AndMask is not all ones for this byte, it's not a bytezap.
4377 if (MaskB != Byte)
4378 return true;
4379
4380 // Otherwise, this byte is kept.
4381 }
4382
4383 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4384 ByteValues);
4385 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004386 }
4387
Chris Lattner567f5112008-10-05 02:13:19 +00004388 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4389 // the input value to the bswap. Some observations: 1) if more than one byte
4390 // is demanded from this input, then it could not be successfully assembled
4391 // into a byteswap. At least one of the two bytes would not be aligned with
4392 // their ultimate destination.
4393 if (!isPowerOf2_32(ByteMask)) return true;
4394 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395
Chris Lattner567f5112008-10-05 02:13:19 +00004396 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4397 // is demanded, it needs to go into byte 0 of the result. This means that the
4398 // byte needs to be shifted until it lands in the right byte bucket. The
4399 // shift amount depends on the position: if the byte is coming from the high
4400 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4401 // low part, it must be shifted left.
4402 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4403 if (InputByteNo < ByteValues.size()/2) {
4404 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4405 return true;
4406 } else {
4407 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4408 return true;
4409 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004410
4411 // If the destination byte value is already defined, the values are or'd
4412 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004413 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004414 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004415 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 return false;
4417}
4418
4419/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4420/// If so, insert the new bswap intrinsic and return it.
4421Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4422 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004423 if (!ITy || ITy->getBitWidth() % 16 ||
4424 // ByteMask only allows up to 32-byte values.
4425 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4427
4428 /// ByteValues - For each byte of the result, we keep track of which value
4429 /// defines each byte.
4430 SmallVector<Value*, 8> ByteValues;
4431 ByteValues.resize(ITy->getBitWidth()/8);
4432
4433 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004434 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4435 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004436 return 0;
4437
4438 // Check to see if all of the bytes come from the same value.
4439 Value *V = ByteValues[0];
4440 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4441
4442 // Check to make sure that all of the bytes come from the same value.
4443 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4444 if (ByteValues[i] != V)
4445 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004446 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004448 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004449 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004450}
4451
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004452/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4453/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4454/// we can simplify this expression to "cond ? C : D or B".
4455static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004456 Value *C, Value *D,
4457 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004458 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004459 Value *Cond = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004460 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004461 return 0;
4462
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004463 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersona21eb582009-07-10 17:35:01 +00004464 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004465 return SelectInst::Create(Cond, C, B);
Owen Andersona21eb582009-07-10 17:35:01 +00004466 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004467 return SelectInst::Create(Cond, C, B);
4468 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersona21eb582009-07-10 17:35:01 +00004469 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004470 return SelectInst::Create(Cond, C, D);
Owen Andersona21eb582009-07-10 17:35:01 +00004471 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004472 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004473 return 0;
4474}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004475
Chris Lattner0c678e52008-11-16 05:20:07 +00004476/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4477Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4478 ICmpInst *LHS, ICmpInst *RHS) {
4479 Value *Val, *Val2;
4480 ConstantInt *LHSCst, *RHSCst;
4481 ICmpInst::Predicate LHSCC, RHSCC;
4482
4483 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004484 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4485 m_ConstantInt(LHSCst)), *Context) ||
4486 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4487 m_ConstantInt(RHSCst)), *Context))
Chris Lattner0c678e52008-11-16 05:20:07 +00004488 return 0;
4489
4490 // From here on, we only handle:
4491 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4492 if (Val != Val2) return 0;
4493
4494 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4495 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4496 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4497 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4498 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4499 return 0;
4500
4501 // We can't fold (ugt x, C) | (sgt x, C2).
4502 if (!PredicatesFoldable(LHSCC, RHSCC))
4503 return 0;
4504
4505 // Ensure that the larger constant is on the RHS.
4506 bool ShouldSwap;
4507 if (ICmpInst::isSignedPredicate(LHSCC) ||
4508 (ICmpInst::isEquality(LHSCC) &&
4509 ICmpInst::isSignedPredicate(RHSCC)))
4510 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4511 else
4512 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4513
4514 if (ShouldSwap) {
4515 std::swap(LHS, RHS);
4516 std::swap(LHSCst, RHSCst);
4517 std::swap(LHSCC, RHSCC);
4518 }
4519
4520 // At this point, we know we have have two icmp instructions
4521 // comparing a value against two constants and or'ing the result
4522 // together. Because of the above check, we know that we only have
4523 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4524 // FoldICmpLogical check above), that the two constants are not
4525 // equal.
4526 assert(LHSCst != RHSCst && "Compares not folded above?");
4527
4528 switch (LHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004529 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004530 case ICmpInst::ICMP_EQ:
4531 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004532 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004533 case ICmpInst::ICMP_EQ:
Owen Anderson24be4c12009-07-03 00:17:18 +00004534 if (LHSCst == SubOne(RHSCst, Context)) {
4535 // (X == 13 | X == 14) -> X-13 <u 2
4536 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004537 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4538 Val->getName()+".off");
4539 InsertNewInstBefore(Add, I);
Owen Anderson24be4c12009-07-03 00:17:18 +00004540 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson6601fcd2009-07-09 23:48:35 +00004541 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004542 }
4543 break; // (X == 13 | X == 15) -> no change
4544 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4545 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4546 break;
4547 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4548 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4549 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4550 return ReplaceInstUsesWith(I, RHS);
4551 }
4552 break;
4553 case ICmpInst::ICMP_NE:
4554 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004555 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004556 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4557 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4558 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4559 return ReplaceInstUsesWith(I, LHS);
4560 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4561 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4562 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson71f286c62009-07-21 18:03:38 +00004563 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner0c678e52008-11-16 05:20:07 +00004564 }
4565 break;
4566 case ICmpInst::ICMP_ULT:
4567 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004568 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004569 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4570 break;
4571 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4572 // If RHSCst is [us]MAXINT, it is always false. Not handling
4573 // this can cause overflow.
4574 if (RHSCst->isMaxValue(false))
4575 return ReplaceInstUsesWith(I, LHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00004576 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4577 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004578 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4579 break;
4580 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4581 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4582 return ReplaceInstUsesWith(I, RHS);
4583 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4584 break;
4585 }
4586 break;
4587 case ICmpInst::ICMP_SLT:
4588 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004589 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004590 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4591 break;
4592 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4593 // If RHSCst is [us]MAXINT, it is always false. Not handling
4594 // this can cause overflow.
4595 if (RHSCst->isMaxValue(true))
4596 return ReplaceInstUsesWith(I, LHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00004597 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4598 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004599 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4600 break;
4601 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4602 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4603 return ReplaceInstUsesWith(I, RHS);
4604 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4605 break;
4606 }
4607 break;
4608 case ICmpInst::ICMP_UGT:
4609 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004610 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004611 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4612 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4613 return ReplaceInstUsesWith(I, LHS);
4614 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4615 break;
4616 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4617 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson71f286c62009-07-21 18:03:38 +00004618 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner0c678e52008-11-16 05:20:07 +00004619 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4620 break;
4621 }
4622 break;
4623 case ICmpInst::ICMP_SGT:
4624 switch (RHSCC) {
Edwin Törökbd448e32009-07-14 16:55:14 +00004625 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner0c678e52008-11-16 05:20:07 +00004626 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4627 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4628 return ReplaceInstUsesWith(I, LHS);
4629 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4630 break;
4631 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4632 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson71f286c62009-07-21 18:03:38 +00004633 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner0c678e52008-11-16 05:20:07 +00004634 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4635 break;
4636 }
4637 break;
4638 }
4639 return 0;
4640}
4641
Bill Wendlingdae376a2008-12-01 08:23:25 +00004642/// FoldOrWithConstants - This helper function folds:
4643///
Bill Wendling236a1192008-12-02 05:09:00 +00004644/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004645///
4646/// into:
4647///
Bill Wendling236a1192008-12-02 05:09:00 +00004648/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004649///
Bill Wendling236a1192008-12-02 05:09:00 +00004650/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004651Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004652 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004653 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4654 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004655
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004656 Value *V1 = 0;
4657 ConstantInt *CI2 = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004658 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004659
Bill Wendling86ee3162008-12-02 06:18:11 +00004660 APInt Xor = CI1->getValue() ^ CI2->getValue();
4661 if (!Xor.isAllOnesValue()) return 0;
4662
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004663 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004664 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004665 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4666 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004667 }
4668
4669 return 0;
4670}
4671
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4673 bool Changed = SimplifyCommutative(I);
4674 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4675
4676 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Anderson24be4c12009-07-03 00:17:18 +00004677 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004678
4679 // or X, X = X
4680 if (Op0 == Op1)
4681 return ReplaceInstUsesWith(I, Op0);
4682
4683 // See if we can simplify any instructions used by the instruction whose sole
4684 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004685 if (SimplifyDemandedInstructionBits(I))
4686 return &I;
4687 if (isa<VectorType>(I.getType())) {
4688 if (isa<ConstantAggregateZero>(Op1)) {
4689 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4690 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4691 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4692 return ReplaceInstUsesWith(I, I.getOperand(1));
4693 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004694 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004695
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004696 // or X, -1 == -1
4697 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4698 ConstantInt *C1 = 0; Value *X = 0;
4699 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersona21eb582009-07-10 17:35:01 +00004700 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4701 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004702 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004703 InsertNewInstBefore(Or, I);
4704 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004705 return BinaryOperator::CreateAnd(Or,
Owen Anderson24be4c12009-07-03 00:17:18 +00004706 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004707 }
4708
4709 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersona21eb582009-07-10 17:35:01 +00004710 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4711 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004712 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004713 InsertNewInstBefore(Or, I);
4714 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004715 return BinaryOperator::CreateXor(Or,
Owen Anderson24be4c12009-07-03 00:17:18 +00004716 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004717 }
4718
4719 // Try to fold constant and into select arguments.
4720 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4721 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4722 return R;
4723 if (isa<PHINode>(Op0))
4724 if (Instruction *NV = FoldOpIntoPhi(I))
4725 return NV;
4726 }
4727
4728 Value *A = 0, *B = 0;
4729 ConstantInt *C1 = 0, *C2 = 0;
4730
Owen Andersona21eb582009-07-10 17:35:01 +00004731 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004732 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4733 return ReplaceInstUsesWith(I, Op1);
Owen Andersona21eb582009-07-10 17:35:01 +00004734 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004735 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4736 return ReplaceInstUsesWith(I, Op0);
4737
4738 // (A | B) | C and A | (B | C) -> bswap if possible.
4739 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersona21eb582009-07-10 17:35:01 +00004740 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4741 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4742 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4743 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004744 if (Instruction *BSwap = MatchBSwap(I))
4745 return BSwap;
4746 }
4747
4748 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004749 if (Op0->hasOneUse() &&
4750 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004752 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004753 InsertNewInstBefore(NOr, I);
4754 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004755 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004756 }
4757
4758 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004759 if (Op1->hasOneUse() &&
4760 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004761 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004762 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004763 InsertNewInstBefore(NOr, I);
4764 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004765 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004766 }
4767
4768 // (A & C)|(B & D)
4769 Value *C = 0, *D = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004770 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4771 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772 Value *V1 = 0, *V2 = 0, *V3 = 0;
4773 C1 = dyn_cast<ConstantInt>(C);
4774 C2 = dyn_cast<ConstantInt>(D);
4775 if (C1 && C2) { // (A & C1)|(B & C2)
4776 // If we have: ((V + N) & C1) | (V & C2)
4777 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4778 // replace with V+N.
4779 if (C1->getValue() == ~C2->getValue()) {
4780 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersona21eb582009-07-10 17:35:01 +00004781 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004782 // Add commutes, try both ways.
4783 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4784 return ReplaceInstUsesWith(I, A);
4785 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4786 return ReplaceInstUsesWith(I, A);
4787 }
4788 // Or commutes, try both ways.
4789 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersona21eb582009-07-10 17:35:01 +00004790 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004791 // Add commutes, try both ways.
4792 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4793 return ReplaceInstUsesWith(I, B);
4794 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4795 return ReplaceInstUsesWith(I, B);
4796 }
4797 }
4798 V1 = 0; V2 = 0; V3 = 0;
4799 }
4800
4801 // Check to see if we have any common things being and'ed. If so, find the
4802 // terms for V1 & (V2|V3).
4803 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4804 if (A == B) // (A & C)|(A & D) == A & (C|D)
4805 V1 = A, V2 = C, V3 = D;
4806 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4807 V1 = A, V2 = B, V3 = C;
4808 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4809 V1 = C, V2 = A, V3 = D;
4810 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4811 V1 = C, V2 = A, V3 = B;
4812
4813 if (V1) {
4814 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004815 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4816 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004817 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004818 }
Dan Gohman279952c2008-10-28 22:38:57 +00004819
Dan Gohman35b76162008-10-30 20:40:10 +00004820 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004821 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004822 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004823 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004824 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004825 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004826 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004827 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004828 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004829
Bill Wendling22ca8352008-11-30 13:52:49 +00004830 // ((A&~B)|(~A&B)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004831 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4832 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004833 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004834 // ((~B&A)|(~A&B)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004835 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4836 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004837 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004838 // ((A&~B)|(B&~A)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004839 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4840 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004841 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004842 // ((~B&A)|(B&~A)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004843 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4844 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004845 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004846 }
4847
4848 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4849 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4850 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4851 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4852 SI0->getOperand(1) == SI1->getOperand(1) &&
4853 (SI0->hasOneUse() || SI1->hasOneUse())) {
4854 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004855 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004856 SI1->getOperand(0),
4857 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004858 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004859 SI1->getOperand(1));
4860 }
4861 }
4862
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004863 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersona21eb582009-07-10 17:35:01 +00004864 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4865 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling9912f712008-12-01 08:32:40 +00004866 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004867 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004868 }
4869 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersona21eb582009-07-10 17:35:01 +00004870 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4871 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling9912f712008-12-01 08:32:40 +00004872 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004873 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004874 }
4875
Owen Andersona21eb582009-07-10 17:35:01 +00004876 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004877 if (A == Op1) // ~A | A == -1
Owen Anderson24be4c12009-07-03 00:17:18 +00004878 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004879 } else {
4880 A = 0;
4881 }
4882 // Note, A is still live here!
Owen Andersona21eb582009-07-10 17:35:01 +00004883 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004884 if (Op0 == B)
Owen Anderson24be4c12009-07-03 00:17:18 +00004885 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004886
4887 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4888 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004889 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004890 I.getName()+".demorgan"), I);
Owen Anderson035d41d2009-07-13 20:58:05 +00004891 return BinaryOperator::CreateNot(*Context, And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004892 }
4893 }
4894
4895 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4896 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004897 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004898 return R;
4899
Chris Lattner0c678e52008-11-16 05:20:07 +00004900 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4901 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4902 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004903 }
4904
4905 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004906 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004907 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4908 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004909 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4910 !isa<ICmpInst>(Op1C->getOperand(0))) {
4911 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnercf373552009-07-23 05:32:17 +00004912 if (SrcTy == Op1C->getOperand(0)->getType() &&
4913 SrcTy->isIntOrIntVector() &&
Evan Chenge3779cf2008-03-24 00:21:34 +00004914 // Only do this if the casts both really cause code to be
4915 // generated.
4916 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4917 I.getType(), TD) &&
4918 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4919 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004920 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004921 Op1C->getOperand(0),
4922 I.getName());
4923 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004924 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004925 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004926 }
4927 }
Chris Lattner91882432007-10-24 05:38:08 +00004928 }
4929
4930
4931 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4932 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4933 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4934 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004935 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng72988052008-10-14 18:44:08 +00004936 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner91882432007-10-24 05:38:08 +00004937 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4938 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4939 // If either of the constants are nans, then the whole thing returns
4940 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004941 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson71f286c62009-07-21 18:03:38 +00004942 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner91882432007-10-24 05:38:08 +00004943
4944 // Otherwise, no need to compare the two constants, compare the
4945 // rest.
Owen Anderson6601fcd2009-07-09 23:48:35 +00004946 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4947 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner91882432007-10-24 05:38:08 +00004948 }
Chris Lattnercf373552009-07-23 05:32:17 +00004949
4950 // Handle vector zeros. This occurs because the canonical form of
4951 // "fcmp uno x,x" is "fcmp uno x, 0".
4952 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4953 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4954 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4955 LHS->getOperand(0), RHS->getOperand(0));
4956
4957
Evan Cheng72988052008-10-14 18:44:08 +00004958 } else {
4959 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4960 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersona21eb582009-07-10 17:35:01 +00004961 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4962 m_Value(Op0RHS)), *Context) &&
4963 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4964 m_Value(Op1RHS)), *Context)) {
Evan Cheng72988052008-10-14 18:44:08 +00004965 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4966 // Swap RHS operands to match LHS.
4967 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4968 std::swap(Op1LHS, Op1RHS);
4969 }
4970 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4971 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4972 if (Op0CC == Op1CC)
Owen Anderson6601fcd2009-07-09 23:48:35 +00004973 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4974 Op0LHS, Op0RHS);
Evan Cheng72988052008-10-14 18:44:08 +00004975 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4976 Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson71f286c62009-07-21 18:03:38 +00004977 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng72988052008-10-14 18:44:08 +00004978 else if (Op0CC == FCmpInst::FCMP_FALSE)
4979 return ReplaceInstUsesWith(I, Op1);
4980 else if (Op1CC == FCmpInst::FCMP_FALSE)
4981 return ReplaceInstUsesWith(I, Op0);
4982 bool Op0Ordered;
4983 bool Op1Ordered;
4984 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4985 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4986 if (Op0Ordered == Op1Ordered) {
4987 // If both are ordered or unordered, return a new fcmp with
4988 // or'ed predicates.
4989 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Anderson24be4c12009-07-03 00:17:18 +00004990 Op0LHS, Op0RHS, Context);
Evan Cheng72988052008-10-14 18:44:08 +00004991 if (Instruction *I = dyn_cast<Instruction>(RV))
4992 return I;
4993 // Otherwise, it's a constant boolean value...
4994 return ReplaceInstUsesWith(I, RV);
4995 }
4996 }
4997 }
4998 }
Chris Lattner91882432007-10-24 05:38:08 +00004999 }
5000 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005001
5002 return Changed ? &I : 0;
5003}
5004
Dan Gohman089efff2008-05-13 00:00:25 +00005005namespace {
5006
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005007// XorSelf - Implements: X ^ X --> 0
5008struct XorSelf {
5009 Value *RHS;
5010 XorSelf(Value *rhs) : RHS(rhs) {}
5011 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5012 Instruction *apply(BinaryOperator &Xor) const {
5013 return &Xor;
5014 }
5015};
5016
Dan Gohman089efff2008-05-13 00:00:25 +00005017}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005018
5019Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5020 bool Changed = SimplifyCommutative(I);
5021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5022
Evan Chenge5cd8032008-03-25 20:07:13 +00005023 if (isa<UndefValue>(Op1)) {
5024 if (isa<UndefValue>(Op0))
5025 // Handle undef ^ undef -> 0 special case. This is a common
5026 // idiom (misuse).
Owen Anderson24be4c12009-07-03 00:17:18 +00005027 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005028 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005029 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005030
5031 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Anderson24be4c12009-07-03 00:17:18 +00005032 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005033 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Anderson24be4c12009-07-03 00:17:18 +00005034 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005035 }
5036
5037 // See if we can simplify any instructions used by the instruction whose sole
5038 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005039 if (SimplifyDemandedInstructionBits(I))
5040 return &I;
5041 if (isa<VectorType>(I.getType()))
5042 if (isa<ConstantAggregateZero>(Op1))
5043 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005044
5045 // Is this a ~ operation?
Owen Anderson24be4c12009-07-03 00:17:18 +00005046 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005047 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5048 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5049 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5050 if (Op0I->getOpcode() == Instruction::And ||
5051 Op0I->getOpcode() == Instruction::Or) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005052 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5053 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005054 Instruction *NotY =
Owen Anderson035d41d2009-07-13 20:58:05 +00005055 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005056 Op0I->getOperand(1)->getName()+".not");
5057 InsertNewInstBefore(NotY, I);
5058 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005059 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005061 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005062 }
5063 }
5064 }
5065 }
5066
5067
5068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson71f286c62009-07-21 18:03:38 +00005069 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005070 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005071 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005072 return new ICmpInst(*Context, ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005073 ICI->getOperand(0), ICI->getOperand(1));
5074
Nick Lewycky1405e922007-08-06 20:04:16 +00005075 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005076 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005077 FCI->getOperand(0), FCI->getOperand(1));
5078 }
5079
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005080 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5081 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5082 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5083 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5084 Instruction::CastOps Opcode = Op0C->getOpcode();
5085 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005086 if (RHS == Context->getConstantExprCast(Opcode,
Owen Anderson71f286c62009-07-21 18:03:38 +00005087 Context->getTrue(),
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005088 Op0C->getDestTy())) {
5089 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson6601fcd2009-07-09 23:48:35 +00005090 *Context,
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005091 CI->getOpcode(), CI->getInversePredicate(),
5092 CI->getOperand(0), CI->getOperand(1)), I);
5093 NewCI->takeName(CI);
5094 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5095 }
5096 }
5097 }
5098 }
5099 }
5100
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005101 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5102 // ~(c-X) == X-c-1 == X+(-c-1)
5103 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5104 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005105 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5106 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5107 Context->getConstantInt(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005108 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005109 }
5110
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005111 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005112 if (Op0I->getOpcode() == Instruction::Add) {
5113 // ~(X-c) --> (-c-1)-X
5114 if (RHS->isAllOnesValue()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005115 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005116 return BinaryOperator::CreateSub(
Owen Anderson24be4c12009-07-03 00:17:18 +00005117 Context->getConstantExprSub(NegOp0CI,
5118 Context->getConstantInt(I.getType(), 1)),
5119 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005120 } else if (RHS->getValue().isSignBit()) {
5121 // (X + C) ^ signbit -> (X + C + signbit)
Owen Anderson24be4c12009-07-03 00:17:18 +00005122 Constant *C =
5123 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005124 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005125
5126 }
5127 } else if (Op0I->getOpcode() == Instruction::Or) {
5128 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5129 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005130 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005131 // Anything in both C1 and C2 is known to be zero, remove it from
5132 // NewRHS.
Owen Anderson24be4c12009-07-03 00:17:18 +00005133 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5134 NewRHS = Context->getConstantExprAnd(NewRHS,
5135 Context->getConstantExprNot(CommonBits));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005136 AddToWorkList(Op0I);
5137 I.setOperand(0, Op0I->getOperand(0));
5138 I.setOperand(1, NewRHS);
5139 return &I;
5140 }
5141 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005143 }
5144
5145 // Try to fold constant and into select arguments.
5146 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5147 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5148 return R;
5149 if (isa<PHINode>(Op0))
5150 if (Instruction *NV = FoldOpIntoPhi(I))
5151 return NV;
5152 }
5153
Owen Anderson24be4c12009-07-03 00:17:18 +00005154 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005155 if (X == Op1)
Owen Anderson24be4c12009-07-03 00:17:18 +00005156 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005157
Owen Anderson24be4c12009-07-03 00:17:18 +00005158 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005159 if (X == Op0)
Owen Anderson24be4c12009-07-03 00:17:18 +00005160 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005161
5162
5163 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5164 if (Op1I) {
5165 Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00005166 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005167 if (A == Op0) { // B^(B|A) == (A|B)^B
5168 Op1I->swapOperands();
5169 I.swapOperands();
5170 std::swap(Op0, Op1);
5171 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5172 I.swapOperands(); // Simplified below.
5173 std::swap(Op0, Op1);
5174 }
Owen Andersona21eb582009-07-10 17:35:01 +00005175 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005176 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersona21eb582009-07-10 17:35:01 +00005177 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005178 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersona21eb582009-07-10 17:35:01 +00005179 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5180 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 if (A == Op0) { // A^(A&B) -> A^(B&A)
5182 Op1I->swapOperands();
5183 std::swap(A, B);
5184 }
5185 if (B == Op0) { // A^(B&A) -> (B&A)^A
5186 I.swapOperands(); // Simplified below.
5187 std::swap(Op0, Op1);
5188 }
5189 }
5190 }
5191
5192 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5193 if (Op0I) {
5194 Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00005195 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5196 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005197 if (A == Op1) // (B|A)^B == (A|B)^B
5198 std::swap(A, B);
5199 if (B == Op1) { // (A|B)^B == A & ~B
5200 Instruction *NotB =
Owen Anderson035d41d2009-07-13 20:58:05 +00005201 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5202 Op1, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005203 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005204 }
Owen Andersona21eb582009-07-10 17:35:01 +00005205 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005206 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersona21eb582009-07-10 17:35:01 +00005207 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005208 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersona21eb582009-07-10 17:35:01 +00005209 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5210 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005211 if (A == Op1) // (A&B)^A -> (B&A)^A
5212 std::swap(A, B);
5213 if (B == Op1 && // (B&A)^A == ~B & A
5214 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5215 Instruction *N =
Owen Anderson035d41d2009-07-13 20:58:05 +00005216 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005217 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005218 }
5219 }
5220 }
5221
5222 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5223 if (Op0I && Op1I && Op0I->isShift() &&
5224 Op0I->getOpcode() == Op1I->getOpcode() &&
5225 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5226 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5227 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005228 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005229 Op1I->getOperand(0),
5230 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005231 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005232 Op1I->getOperand(1));
5233 }
5234
5235 if (Op0I && Op1I) {
5236 Value *A, *B, *C, *D;
5237 // (A & B)^(A | B) -> A ^ B
Owen Andersona21eb582009-07-10 17:35:01 +00005238 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5239 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005240 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005241 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005242 }
5243 // (A | B)^(A & B) -> A ^ B
Owen Andersona21eb582009-07-10 17:35:01 +00005244 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5245 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005246 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005247 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005248 }
5249
5250 // (A & B)^(C & D)
5251 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005252 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5253 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005254 // (X & Y)^(X & Y) -> (Y^Z) & X
5255 Value *X = 0, *Y = 0, *Z = 0;
5256 if (A == C)
5257 X = A, Y = B, Z = D;
5258 else if (A == D)
5259 X = A, Y = B, Z = C;
5260 else if (B == C)
5261 X = B, Y = A, Z = D;
5262 else if (B == D)
5263 X = B, Y = A, Z = C;
5264
5265 if (X) {
5266 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005267 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5268 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005269 }
5270 }
5271 }
5272
5273 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5274 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Anderson24be4c12009-07-03 00:17:18 +00005275 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005276 return R;
5277
5278 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005279 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005280 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5281 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5282 const Type *SrcTy = Op0C->getOperand(0)->getType();
5283 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5284 // Only do this if the casts both really cause code to be generated.
5285 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5286 I.getType(), TD) &&
5287 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5288 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005289 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005290 Op1C->getOperand(0),
5291 I.getName());
5292 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005293 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005294 }
5295 }
Chris Lattner91882432007-10-24 05:38:08 +00005296 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005297
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005298 return Changed ? &I : 0;
5299}
5300
Owen Anderson24be4c12009-07-03 00:17:18 +00005301static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005302 LLVMContext *Context) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005303 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005304}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005305
Dan Gohman8fd520a2009-06-15 22:12:54 +00005306static bool HasAddOverflow(ConstantInt *Result,
5307 ConstantInt *In1, ConstantInt *In2,
5308 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005309 if (IsSigned)
5310 if (In2->getValue().isNegative())
5311 return Result->getValue().sgt(In1->getValue());
5312 else
5313 return Result->getValue().slt(In1->getValue());
5314 else
5315 return Result->getValue().ult(In1->getValue());
5316}
5317
Dan Gohman8fd520a2009-06-15 22:12:54 +00005318/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005319/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005320static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005321 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005322 bool IsSigned = false) {
5323 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005324
Dan Gohman8fd520a2009-06-15 22:12:54 +00005325 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5326 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005327 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5328 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5329 ExtractElement(In1, Idx, Context),
5330 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005331 IsSigned))
5332 return true;
5333 }
5334 return false;
5335 }
5336
5337 return HasAddOverflow(cast<ConstantInt>(Result),
5338 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5339 IsSigned);
5340}
5341
5342static bool HasSubOverflow(ConstantInt *Result,
5343 ConstantInt *In1, ConstantInt *In2,
5344 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005345 if (IsSigned)
5346 if (In2->getValue().isNegative())
5347 return Result->getValue().slt(In1->getValue());
5348 else
5349 return Result->getValue().sgt(In1->getValue());
5350 else
5351 return Result->getValue().ugt(In1->getValue());
5352}
5353
Dan Gohman8fd520a2009-06-15 22:12:54 +00005354/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5355/// overflowed for this type.
5356static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005357 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005358 bool IsSigned = false) {
5359 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005360
5361 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5362 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005363 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5364 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5365 ExtractElement(In1, Idx, Context),
5366 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005367 IsSigned))
5368 return true;
5369 }
5370 return false;
5371 }
5372
5373 return HasSubOverflow(cast<ConstantInt>(Result),
5374 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5375 IsSigned);
5376}
5377
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005378/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5379/// code necessary to compute the offset from the base pointer (without adding
5380/// in the base pointer). Return the result as a signed integer of intptr size.
5381static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005382 TargetData &TD = *IC.getTargetData();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005383 gep_type_iterator GTI = gep_type_begin(GEP);
5384 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson5349f052009-07-06 23:00:19 +00005385 LLVMContext *Context = IC.getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00005386 Value *Result = Context->getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005387
5388 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005389 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005390 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5391
Gabor Greif17396002008-06-12 21:37:33 +00005392 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5393 ++i, ++GTI) {
5394 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005395 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005396 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5397 if (OpC->isZero()) continue;
5398
5399 // Handle a struct index, which adds its field offset to the pointer.
5400 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5401 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5402
5403 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005404 Result =
5405 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005406 else
5407 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005408 BinaryOperator::CreateAdd(Result,
Owen Anderson24be4c12009-07-03 00:17:18 +00005409 Context->getConstantInt(IntPtrTy, Size),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005410 GEP->getName()+".offs"), I);
5411 continue;
5412 }
5413
Owen Anderson24be4c12009-07-03 00:17:18 +00005414 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5415 Constant *OC =
5416 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5417 Scale = Context->getConstantExprMul(OC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005418 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005419 Result = Context->getConstantExprAdd(RC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005420 else {
5421 // Emit an add instruction.
5422 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005423 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005424 GEP->getName()+".offs"), I);
5425 }
5426 continue;
5427 }
5428 // Convert to correct type.
5429 if (Op->getType() != IntPtrTy) {
5430 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson24be4c12009-07-03 00:17:18 +00005431 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005432 else
Chris Lattner2941a652009-04-07 05:03:34 +00005433 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5434 true,
5435 Op->getName()+".c"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005436 }
5437 if (Size != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005438 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005439 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson24be4c12009-07-03 00:17:18 +00005440 Op = Context->getConstantExprMul(OpC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005441 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005442 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005443 GEP->getName()+".idx"), I);
5444 }
5445
5446 // Emit an add instruction.
5447 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005448 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005449 cast<Constant>(Result));
5450 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005451 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005452 GEP->getName()+".offs"), I);
5453 }
5454 return Result;
5455}
5456
Chris Lattnereba75862008-04-22 02:53:33 +00005457
Dan Gohmanff9b4732009-07-17 22:16:21 +00005458/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5459/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5460/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5461/// be complex, and scales are involved. The above expression would also be
5462/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5463/// This later form is less amenable to optimization though, and we are allowed
5464/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattnereba75862008-04-22 02:53:33 +00005465///
5466/// If we can't emit an optimized form for this expression, this returns null.
5467///
5468static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5469 InstCombiner &IC) {
Dan Gohmana80e2712009-07-21 23:21:54 +00005470 TargetData &TD = *IC.getTargetData();
Chris Lattnereba75862008-04-22 02:53:33 +00005471 gep_type_iterator GTI = gep_type_begin(GEP);
5472
5473 // Check to see if this gep only has a single variable index. If so, and if
5474 // any constant indices are a multiple of its scale, then we can compute this
5475 // in terms of the scale of the variable index. For example, if the GEP
5476 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5477 // because the expression will cross zero at the same point.
5478 unsigned i, e = GEP->getNumOperands();
5479 int64_t Offset = 0;
5480 for (i = 1; i != e; ++i, ++GTI) {
5481 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5482 // Compute the aggregate offset of constant indices.
5483 if (CI->isZero()) continue;
5484
5485 // Handle a struct index, which adds its field offset to the pointer.
5486 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5487 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5488 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005489 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005490 Offset += Size*CI->getSExtValue();
5491 }
5492 } else {
5493 // Found our variable index.
5494 break;
5495 }
5496 }
5497
5498 // If there are no variable indices, we must have a constant offset, just
5499 // evaluate it the general way.
5500 if (i == e) return 0;
5501
5502 Value *VariableIdx = GEP->getOperand(i);
5503 // Determine the scale factor of the variable element. For example, this is
5504 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005505 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005506
5507 // Verify that there are no other variable indices. If so, emit the hard way.
5508 for (++i, ++GTI; i != e; ++i, ++GTI) {
5509 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5510 if (!CI) return 0;
5511
5512 // Compute the aggregate offset of constant indices.
5513 if (CI->isZero()) continue;
5514
5515 // Handle a struct index, which adds its field offset to the pointer.
5516 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5517 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5518 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005519 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005520 Offset += Size*CI->getSExtValue();
5521 }
5522 }
5523
5524 // Okay, we know we have a single variable index, which must be a
5525 // pointer/array/vector index. If there is no offset, life is simple, return
5526 // the index.
5527 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5528 if (Offset == 0) {
5529 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5530 // we don't need to bother extending: the extension won't affect where the
5531 // computation crosses zero.
5532 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5533 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5534 VariableIdx->getNameStart(), &I);
5535 return VariableIdx;
5536 }
5537
5538 // Otherwise, there is an index. The computation we will do will be modulo
5539 // the pointer size, so get it.
5540 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5541
5542 Offset &= PtrSizeMask;
5543 VariableScale &= PtrSizeMask;
5544
5545 // To do this transformation, any constant index must be a multiple of the
5546 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5547 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5548 // multiple of the variable scale.
5549 int64_t NewOffs = Offset / (int64_t)VariableScale;
5550 if (Offset != NewOffs*(int64_t)VariableScale)
5551 return 0;
5552
5553 // Okay, we can do this evaluation. Start by converting the index to intptr.
5554 const Type *IntPtrTy = TD.getIntPtrType();
5555 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005556 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005557 true /*SExt*/,
5558 VariableIdx->getNameStart(), &I);
Owen Anderson24be4c12009-07-03 00:17:18 +00005559 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005560 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005561}
5562
5563
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005564/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5565/// else. At this point we know that the GEP is on the LHS of the comparison.
5566Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5567 ICmpInst::Predicate Cond,
5568 Instruction &I) {
5569 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5570
Chris Lattnereba75862008-04-22 02:53:33 +00005571 // Look through bitcasts.
5572 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5573 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005574
5575 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmana80e2712009-07-21 23:21:54 +00005576 if (TD && PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005577 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005578 // This transformation (ignoring the base and scales) is valid because we
5579 // know pointers can't overflow. See if we can output an optimized form.
5580 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5581
5582 // If not, synthesize the offset the hard way.
5583 if (Offset == 0)
5584 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005585 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Anderson24be4c12009-07-03 00:17:18 +00005586 Context->getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005587 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5588 // If the base pointers are different, but the indices are the same, just
5589 // compare the base pointer.
5590 if (PtrBase != GEPRHS->getOperand(0)) {
5591 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5592 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5593 GEPRHS->getOperand(0)->getType();
5594 if (IndicesTheSame)
5595 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5596 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5597 IndicesTheSame = false;
5598 break;
5599 }
5600
5601 // If all indices are the same, just compare the base pointers.
5602 if (IndicesTheSame)
Owen Anderson6601fcd2009-07-09 23:48:35 +00005603 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005604 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5605
5606 // Otherwise, the base pointers are different and the indices are
5607 // different, bail out.
5608 return 0;
5609 }
5610
5611 // If one of the GEPs has all zero indices, recurse.
5612 bool AllZeros = true;
5613 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5614 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5615 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5616 AllZeros = false;
5617 break;
5618 }
5619 if (AllZeros)
5620 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5621 ICmpInst::getSwappedPredicate(Cond), I);
5622
5623 // If the other GEP has all zero indices, recurse.
5624 AllZeros = true;
5625 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5626 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5627 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5628 AllZeros = false;
5629 break;
5630 }
5631 if (AllZeros)
5632 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5633
5634 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5635 // If the GEPs only differ by one index, compare it.
5636 unsigned NumDifferences = 0; // Keep track of # differences.
5637 unsigned DiffOperand = 0; // The operand that differs.
5638 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5639 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5640 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5641 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5642 // Irreconcilable differences.
5643 NumDifferences = 2;
5644 break;
5645 } else {
5646 if (NumDifferences++) break;
5647 DiffOperand = i;
5648 }
5649 }
5650
5651 if (NumDifferences == 0) // SAME GEP?
5652 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson24be4c12009-07-03 00:17:18 +00005653 Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005654 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005655
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005656 else if (NumDifferences == 1) {
5657 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5658 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5659 // Make sure we do a signed comparison here.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005660 return new ICmpInst(*Context,
5661 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005662 }
5663 }
5664
5665 // Only lower this if the icmp is the only user of the GEP or if we expect
5666 // the result to fold to a constant!
Dan Gohmana80e2712009-07-21 23:21:54 +00005667 if (TD &&
5668 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005669 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5670 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5671 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5672 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005673 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005674 }
5675 }
5676 return 0;
5677}
5678
Chris Lattnere6b62d92008-05-19 20:18:56 +00005679/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5680///
5681Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5682 Instruction *LHSI,
5683 Constant *RHSC) {
5684 if (!isa<ConstantFP>(RHSC)) return 0;
5685 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5686
5687 // Get the width of the mantissa. We don't want to hack on conversions that
5688 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005689 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005690 if (MantissaWidth == -1) return 0; // Unknown.
5691
5692 // Check to see that the input is converted from an integer type that is small
5693 // enough that preserves all bits. TODO: check here for "known" sign bits.
5694 // 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 +00005695 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005696
5697 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005698 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5699 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005700 ++InputSize;
5701
5702 // If the conversion would lose info, don't hack on this.
5703 if ((int)InputSize > MantissaWidth)
5704 return 0;
5705
5706 // Otherwise, we can potentially simplify the comparison. We know that it
5707 // will always come through as an integer value and we know the constant is
5708 // not a NAN (it would have been previously simplified).
5709 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5710
5711 ICmpInst::Predicate Pred;
5712 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005713 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnere6b62d92008-05-19 20:18:56 +00005714 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005715 case FCmpInst::FCMP_OEQ:
5716 Pred = ICmpInst::ICMP_EQ;
5717 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005718 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005719 case FCmpInst::FCMP_OGT:
5720 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5721 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005722 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005723 case FCmpInst::FCMP_OGE:
5724 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5725 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005726 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005727 case FCmpInst::FCMP_OLT:
5728 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5729 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005730 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005731 case FCmpInst::FCMP_OLE:
5732 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5733 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005735 case FCmpInst::FCMP_ONE:
5736 Pred = ICmpInst::ICMP_NE;
5737 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005738 case FCmpInst::FCMP_ORD:
Owen Anderson71f286c62009-07-21 18:03:38 +00005739 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005740 case FCmpInst::FCMP_UNO:
Owen Anderson71f286c62009-07-21 18:03:38 +00005741 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005742 }
5743
5744 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5745
5746 // Now we know that the APFloat is a normal number, zero or inf.
5747
Chris Lattnerf13ff492008-05-20 03:50:52 +00005748 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005749 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005750 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005751
Bill Wendling20636df2008-11-09 04:26:50 +00005752 if (!LHSUnsigned) {
5753 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5754 // and large values.
5755 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5756 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5757 APFloat::rmNearestTiesToEven);
5758 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5759 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5760 Pred == ICmpInst::ICMP_SLE)
Owen Anderson71f286c62009-07-21 18:03:38 +00005761 return ReplaceInstUsesWith(I, Context->getTrue());
5762 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005763 }
5764 } else {
5765 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5766 // +INF and large values.
5767 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5768 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5769 APFloat::rmNearestTiesToEven);
5770 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5771 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5772 Pred == ICmpInst::ICMP_ULE)
Owen Anderson71f286c62009-07-21 18:03:38 +00005773 return ReplaceInstUsesWith(I, Context->getTrue());
5774 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005775 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005776 }
5777
Bill Wendling20636df2008-11-09 04:26:50 +00005778 if (!LHSUnsigned) {
5779 // See if the RHS value is < SignedMin.
5780 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5781 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5782 APFloat::rmNearestTiesToEven);
5783 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5784 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5785 Pred == ICmpInst::ICMP_SGE)
Owen Anderson71f286c62009-07-21 18:03:38 +00005786 return ReplaceInstUsesWith(I, Context->getTrue());
5787 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005788 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005789 }
5790
Bill Wendling20636df2008-11-09 04:26:50 +00005791 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5792 // [0, UMAX], but it may still be fractional. See if it is fractional by
5793 // casting the FP value to the integer value and back, checking for equality.
5794 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005795 Constant *RHSInt = LHSUnsigned
Owen Anderson24be4c12009-07-03 00:17:18 +00005796 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5797 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005798 if (!RHS.isZero()) {
5799 bool Equal = LHSUnsigned
Owen Anderson24be4c12009-07-03 00:17:18 +00005800 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5801 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005802 if (!Equal) {
5803 // If we had a comparison against a fractional value, we have to adjust
5804 // the compare predicate and sometimes the value. RHSC is rounded towards
5805 // zero at this point.
5806 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005807 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng14118132009-05-22 23:10:53 +00005808 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson71f286c62009-07-21 18:03:38 +00005809 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005810 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson71f286c62009-07-21 18:03:38 +00005811 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng14118132009-05-22 23:10:53 +00005812 case ICmpInst::ICMP_ULE:
5813 // (float)int <= 4.4 --> int <= 4
5814 // (float)int <= -4.4 --> false
5815 if (RHS.isNegative())
Owen Anderson71f286c62009-07-21 18:03:38 +00005816 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng14118132009-05-22 23:10:53 +00005817 break;
5818 case ICmpInst::ICMP_SLE:
5819 // (float)int <= 4.4 --> int <= 4
5820 // (float)int <= -4.4 --> int < -4
5821 if (RHS.isNegative())
5822 Pred = ICmpInst::ICMP_SLT;
5823 break;
5824 case ICmpInst::ICMP_ULT:
5825 // (float)int < -4.4 --> false
5826 // (float)int < 4.4 --> int <= 4
5827 if (RHS.isNegative())
Owen Anderson71f286c62009-07-21 18:03:38 +00005828 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng14118132009-05-22 23:10:53 +00005829 Pred = ICmpInst::ICMP_ULE;
5830 break;
5831 case ICmpInst::ICMP_SLT:
5832 // (float)int < -4.4 --> int < -4
5833 // (float)int < 4.4 --> int <= 4
5834 if (!RHS.isNegative())
5835 Pred = ICmpInst::ICMP_SLE;
5836 break;
5837 case ICmpInst::ICMP_UGT:
5838 // (float)int > 4.4 --> int > 4
5839 // (float)int > -4.4 --> true
5840 if (RHS.isNegative())
Owen Anderson71f286c62009-07-21 18:03:38 +00005841 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005842 break;
5843 case ICmpInst::ICMP_SGT:
5844 // (float)int > 4.4 --> int > 4
5845 // (float)int > -4.4 --> int >= -4
5846 if (RHS.isNegative())
5847 Pred = ICmpInst::ICMP_SGE;
5848 break;
5849 case ICmpInst::ICMP_UGE:
5850 // (float)int >= -4.4 --> true
5851 // (float)int >= 4.4 --> int > 4
5852 if (!RHS.isNegative())
Owen Anderson71f286c62009-07-21 18:03:38 +00005853 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005854 Pred = ICmpInst::ICMP_UGT;
5855 break;
5856 case ICmpInst::ICMP_SGE:
5857 // (float)int >= -4.4 --> int >= -4
5858 // (float)int >= 4.4 --> int > 4
5859 if (!RHS.isNegative())
5860 Pred = ICmpInst::ICMP_SGT;
5861 break;
5862 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005863 }
5864 }
5865
5866 // Lower this FP comparison into an appropriate integer version of the
5867 // comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005868 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005869}
5870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005871Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5872 bool Changed = SimplifyCompare(I);
5873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5874
5875 // Fold trivial predicates.
5876 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson71f286c62009-07-21 18:03:38 +00005877 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005878 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson71f286c62009-07-21 18:03:38 +00005879 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005880
5881 // Simplify 'fcmp pred X, X'
5882 if (Op0 == Op1) {
5883 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00005884 default: llvm_unreachable("Unknown predicate!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005885 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5886 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5887 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson71f286c62009-07-21 18:03:38 +00005888 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005889 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5890 case FCmpInst::FCMP_OLT: // True if ordered and less than
5891 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson71f286c62009-07-21 18:03:38 +00005892 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005893
5894 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5895 case FCmpInst::FCMP_ULT: // True if unordered or less than
5896 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5897 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5898 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5899 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Anderson24be4c12009-07-03 00:17:18 +00005900 I.setOperand(1, Context->getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005901 return &I;
5902
5903 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5904 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5905 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5906 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5907 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5908 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Anderson24be4c12009-07-03 00:17:18 +00005909 I.setOperand(1, Context->getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005910 return &I;
5911 }
5912 }
5913
5914 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson24be4c12009-07-03 00:17:18 +00005915 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005916
5917 // Handle fcmp with constant RHS
5918 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005919 // If the constant is a nan, see if we can fold the comparison based on it.
5920 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5921 if (CFP->getValueAPF().isNaN()) {
5922 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson71f286c62009-07-21 18:03:38 +00005923 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnerf13ff492008-05-20 03:50:52 +00005924 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5925 "Comparison must be either ordered or unordered!");
5926 // True if unordered.
Owen Anderson71f286c62009-07-21 18:03:38 +00005927 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005928 }
5929 }
5930
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005931 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5932 switch (LHSI->getOpcode()) {
5933 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005934 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5935 // block. If in the same block, we're encouraging jump threading. If
5936 // not, we are just pessimizing the code by making an i1 phi.
5937 if (LHSI->getParent() == I.getParent())
5938 if (Instruction *NV = FoldOpIntoPhi(I))
5939 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005940 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005941 case Instruction::SIToFP:
5942 case Instruction::UIToFP:
5943 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5944 return NV;
5945 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005946 case Instruction::Select:
5947 // If either operand of the select is a constant, we can fold the
5948 // comparison into the select arms, which will cause one to be
5949 // constant folded and the select turned into a bitwise or.
5950 Value *Op1 = 0, *Op2 = 0;
5951 if (LHSI->hasOneUse()) {
5952 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5953 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00005954 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005955 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005956 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005957 LHSI->getOperand(2), RHSC,
5958 I.getName()), I);
5959 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5960 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00005961 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005962 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005963 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005964 LHSI->getOperand(1), RHSC,
5965 I.getName()), I);
5966 }
5967 }
5968
5969 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005970 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005971 break;
5972 }
5973 }
5974
5975 return Changed ? &I : 0;
5976}
5977
5978Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5979 bool Changed = SimplifyCompare(I);
5980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5981 const Type *Ty = Op0->getType();
5982
5983 // icmp X, X
5984 if (Op0 == Op1)
Owen Anderson24be4c12009-07-03 00:17:18 +00005985 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005986 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005987
5988 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson24be4c12009-07-03 00:17:18 +00005989 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005990
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005991 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5992 // addresses never equal each other! We already know that Op0 != Op1.
5993 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5994 isa<ConstantPointerNull>(Op0)) &&
5995 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5996 isa<ConstantPointerNull>(Op1)))
Owen Anderson24be4c12009-07-03 00:17:18 +00005997 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005998 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005999
6000 // icmp's with boolean values can always be turned into bitwise operations
6001 if (Ty == Type::Int1Ty) {
6002 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006003 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00006004 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00006005 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006006 InsertNewInstBefore(Xor, I);
Owen Anderson035d41d2009-07-13 20:58:05 +00006007 return BinaryOperator::CreateNot(*Context, Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006008 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006010 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011
6012 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006013 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006014 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006015 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson035d41d2009-07-13 20:58:05 +00006016 Instruction *Not = BinaryOperator::CreateNot(*Context,
6017 Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006018 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006019 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006020 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_SGT:
6022 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006023 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006024 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson035d41d2009-07-13 20:58:05 +00006025 Instruction *Not = BinaryOperator::CreateNot(*Context,
6026 Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006027 InsertNewInstBefore(Not, I);
6028 return BinaryOperator::CreateAnd(Not, Op0);
6029 }
6030 case ICmpInst::ICMP_UGE:
6031 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson035d41d2009-07-13 20:58:05 +00006034 Instruction *Not = BinaryOperator::CreateNot(*Context,
6035 Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006036 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006037 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006038 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006039 case ICmpInst::ICMP_SGE:
6040 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6041 // FALL THROUGH
6042 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson035d41d2009-07-13 20:58:05 +00006043 Instruction *Not = BinaryOperator::CreateNot(*Context,
6044 Op1, I.getName()+"tmp");
Chris Lattnera02893d2008-07-11 04:20:58 +00006045 InsertNewInstBefore(Not, I);
6046 return BinaryOperator::CreateOr(Not, Op0);
6047 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006048 }
6049 }
6050
Dan Gohman7934d592009-04-25 17:12:48 +00006051 unsigned BitWidth = 0;
6052 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006053 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6054 else if (Ty->isIntOrIntVector())
6055 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006056
6057 bool isSignBit = false;
6058
Dan Gohman58c09632008-09-16 18:46:06 +00006059 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006060 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006061 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006062
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006063 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6064 if (I.isEquality() && CI->isNullValue() &&
Owen Andersona21eb582009-07-10 17:35:01 +00006065 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006066 // (icmp cond A B) if cond is equality
Owen Anderson6601fcd2009-07-09 23:48:35 +00006067 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006068 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006069
Dan Gohman58c09632008-09-16 18:46:06 +00006070 // If we have an icmp le or icmp ge instruction, turn it into the
6071 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6072 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006073 switch (I.getPredicate()) {
6074 default: break;
6075 case ICmpInst::ICMP_ULE:
6076 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson71f286c62009-07-21 18:03:38 +00006077 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006078 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6079 AddOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006080 case ICmpInst::ICMP_SLE:
6081 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson71f286c62009-07-21 18:03:38 +00006082 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6084 AddOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006085 case ICmpInst::ICMP_UGE:
6086 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson71f286c62009-07-21 18:03:38 +00006087 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006088 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6089 SubOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006090 case ICmpInst::ICMP_SGE:
6091 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson71f286c62009-07-21 18:03:38 +00006092 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006093 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6094 SubOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006095 }
6096
Chris Lattnera1308652008-07-11 05:40:05 +00006097 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006098 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006099 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006100 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6101 }
6102
6103 // See if we can fold the comparison based on range information we can get
6104 // by checking whether bits are known to be zero or one in the input.
6105 if (BitWidth != 0) {
6106 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6107 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6108
6109 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006110 isSignBit ? APInt::getSignBit(BitWidth)
6111 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006112 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006113 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006114 if (SimplifyDemandedBits(I.getOperandUse(1),
6115 APInt::getAllOnesValue(BitWidth),
6116 Op1KnownZero, Op1KnownOne, 0))
6117 return &I;
6118
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006119 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006120 // in. Compute the Min, Max and RHS values based on the known bits. For the
6121 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006122 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6123 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6124 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6125 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6126 Op0Min, Op0Max);
6127 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6128 Op1Min, Op1Max);
6129 } else {
6130 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6131 Op0Min, Op0Max);
6132 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6133 Op1Min, Op1Max);
6134 }
6135
Chris Lattnera1308652008-07-11 05:40:05 +00006136 // If Min and Max are known to be the same, then SimplifyDemandedBits
6137 // figured out that the LHS is a constant. Just constant fold this now so
6138 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006139 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006140 return new ICmpInst(*Context, I.getPredicate(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006141 Context->getConstantInt(Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006142 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006143 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00006144 Context->getConstantInt(Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006145
Chris Lattnera1308652008-07-11 05:40:05 +00006146 // Based on the range information we know about the LHS, see if we can
6147 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006148 switch (I.getPredicate()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006149 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner62d0f232008-07-11 05:08:55 +00006150 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006151 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson71f286c62009-07-21 18:03:38 +00006152 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner62d0f232008-07-11 05:08:55 +00006153 break;
6154 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006155 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson71f286c62009-07-21 18:03:38 +00006156 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner62d0f232008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006160 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006161 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006162 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006163 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006164 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6166 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006167 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6168 SubOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006169
6170 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6171 if (CI->isMinValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006172 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson035d41d2009-07-13 20:58:05 +00006173 Context->getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006174 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006175 break;
6176 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006177 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006178 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006179 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006180 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006181
6182 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006183 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6185 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006186 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6187 AddOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006188
6189 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6190 if (CI->isMaxValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00006192 Context->getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006193 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006194 break;
6195 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006196 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson71f286c62009-07-21 18:03:38 +00006197 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006198 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson71f286c62009-07-21 18:03:38 +00006199 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006200 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006201 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006202 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6203 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006204 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6205 SubOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006206 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006207 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006208 case ICmpInst::ICMP_SGT:
6209 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006210 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006211 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006212 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006213
6214 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006215 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006216 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6217 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006218 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6219 AddOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006220 }
6221 break;
6222 case ICmpInst::ICMP_SGE:
6223 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6224 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006225 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006226 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006227 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006228 break;
6229 case ICmpInst::ICMP_SLE:
6230 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6231 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006232 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006233 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006234 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006235 break;
6236 case ICmpInst::ICMP_UGE:
6237 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6238 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006239 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006240 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006241 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006242 break;
6243 case ICmpInst::ICMP_ULE:
6244 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6245 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006246 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006247 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson71f286c62009-07-21 18:03:38 +00006248 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner62d0f232008-07-11 05:08:55 +00006249 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006250 }
Dan Gohman7934d592009-04-25 17:12:48 +00006251
6252 // Turn a signed comparison into an unsigned one if both operands
6253 // are known to have the same sign.
6254 if (I.isSignedPredicate() &&
6255 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6256 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006257 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006258 }
6259
6260 // Test if the ICmpInst instruction is used exclusively by a select as
6261 // part of a minimum or maximum operation. If so, refrain from doing
6262 // any other folding. This helps out other analyses which understand
6263 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6264 // and CodeGen. And in this case, at least one of the comparison
6265 // operands has at least one user besides the compare (the select),
6266 // which would often largely negate the benefit of folding anyway.
6267 if (I.hasOneUse())
6268 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6269 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6270 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6271 return 0;
6272
6273 // See if we are doing a comparison between a constant and an instruction that
6274 // can be folded into the comparison.
6275 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006276 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6277 // instruction, see if that instruction also has constants so that the
6278 // instruction can be folded into the icmp
6279 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6280 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6281 return Res;
6282 }
6283
6284 // Handle icmp with constant (but not simple integer constant) RHS
6285 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6286 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6287 switch (LHSI->getOpcode()) {
6288 case Instruction::GetElementPtr:
6289 if (RHSC->isNullValue()) {
6290 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6291 bool isAllZeros = true;
6292 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6293 if (!isa<Constant>(LHSI->getOperand(i)) ||
6294 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6295 isAllZeros = false;
6296 break;
6297 }
6298 if (isAllZeros)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006299 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006300 Context->getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006301 }
6302 break;
6303
6304 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006305 // Only fold icmp into the PHI if the phi and fcmp are in the same
6306 // block. If in the same block, we're encouraging jump threading. If
6307 // not, we are just pessimizing the code by making an i1 phi.
6308 if (LHSI->getParent() == I.getParent())
6309 if (Instruction *NV = FoldOpIntoPhi(I))
6310 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006311 break;
6312 case Instruction::Select: {
6313 // If either operand of the select is a constant, we can fold the
6314 // comparison into the select arms, which will cause one to be
6315 // constant folded and the select turned into a bitwise or.
6316 Value *Op1 = 0, *Op2 = 0;
6317 if (LHSI->hasOneUse()) {
6318 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6319 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00006320 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006321 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006322 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006323 LHSI->getOperand(2), RHSC,
6324 I.getName()), I);
6325 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6326 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00006327 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006328 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006329 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006330 LHSI->getOperand(1), RHSC,
6331 I.getName()), I);
6332 }
6333 }
6334
6335 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006336 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006337 break;
6338 }
6339 case Instruction::Malloc:
6340 // If we have (malloc != null), and if the malloc has a single use, we
6341 // can assume it is successful and remove the malloc.
6342 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6343 AddToWorkList(LHSI);
Owen Anderson24be4c12009-07-03 00:17:18 +00006344 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006345 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006346 }
6347 break;
6348 }
6349 }
6350
6351 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6352 if (User *GEP = dyn_castGetElementPtr(Op0))
6353 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6354 return NI;
6355 if (User *GEP = dyn_castGetElementPtr(Op1))
6356 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6357 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6358 return NI;
6359
6360 // Test to see if the operands of the icmp are casted versions of other
6361 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6362 // now.
6363 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6364 if (isa<PointerType>(Op0->getType()) &&
6365 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6366 // We keep moving the cast from the left operand over to the right
6367 // operand, where it can often be eliminated completely.
6368 Op0 = CI->getOperand(0);
6369
6370 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6371 // so eliminate it as well.
6372 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6373 Op1 = CI2->getOperand(0);
6374
6375 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006376 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006377 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006378 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006379 } else {
6380 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006381 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006382 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006383 }
Owen Anderson6601fcd2009-07-09 23:48:35 +00006384 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006385 }
6386 }
6387
6388 if (isa<CastInst>(Op0)) {
6389 // Handle the special case of: icmp (cast bool to X), <cst>
6390 // This comes up when you have code like
6391 // int X = A < B;
6392 // if (X) ...
6393 // For generality, we handle any zero-extension of any operand comparison
6394 // with a constant or another cast from the same type.
6395 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6396 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6397 return R;
6398 }
6399
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006400 // See if it's the same type of instruction on the left and right.
6401 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6402 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006403 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006404 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006405 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006406 default: break;
6407 case Instruction::Add:
6408 case Instruction::Sub:
6409 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006410 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson6601fcd2009-07-09 23:48:35 +00006411 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006412 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006413 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6414 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6415 if (CI->getValue().isSignBit()) {
6416 ICmpInst::Predicate Pred = I.isSignedPredicate()
6417 ? I.getUnsignedPredicate()
6418 : I.getSignedPredicate();
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));
6421 }
6422
6423 if (CI->getValue().isMaxSignedValue()) {
6424 ICmpInst::Predicate Pred = I.isSignedPredicate()
6425 ? I.getUnsignedPredicate()
6426 : I.getSignedPredicate();
6427 Pred = I.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006428 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006429 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006430 }
6431 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006432 break;
6433 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006434 if (!I.isEquality())
6435 break;
6436
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006437 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6438 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6439 // Mask = -1 >> count-trailing-zeros(Cst).
6440 if (!CI->isZero() && !CI->isOne()) {
6441 const APInt &AP = CI->getValue();
Owen Anderson24be4c12009-07-03 00:17:18 +00006442 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006443 APInt::getLowBitsSet(AP.getBitWidth(),
6444 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006445 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006446 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6447 Mask);
6448 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6449 Mask);
6450 InsertNewInstBefore(And1, I);
6451 InsertNewInstBefore(And2, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006452 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006453 }
6454 }
6455 break;
6456 }
6457 }
6458 }
6459 }
6460
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006461 // ~x < ~y --> y < x
6462 { Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00006463 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6464 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006465 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006466 }
6467
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006468 if (I.isEquality()) {
6469 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006470
6471 // -x == -y --> x == y
Owen Andersona21eb582009-07-10 17:35:01 +00006472 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6473 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006474 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006475
Owen Andersona21eb582009-07-10 17:35:01 +00006476 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006477 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6478 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006479 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006480 Context->getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006481 }
6482
Owen Andersona21eb582009-07-10 17:35:01 +00006483 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006484 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006485 ConstantInt *C1, *C2;
Owen Andersona21eb582009-07-10 17:35:01 +00006486 if (match(B, m_ConstantInt(C1), *Context) &&
6487 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006488 Constant *NC =
6489 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattner3b874082008-11-16 05:38:51 +00006490 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson6601fcd2009-07-09 23:48:35 +00006491 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattner3b874082008-11-16 05:38:51 +00006492 InsertNewInstBefore(Xor, I));
6493 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006494
6495 // A^B == A^D -> B == D
Owen Anderson6601fcd2009-07-09 23:48:35 +00006496 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6497 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6498 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6499 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006500 }
6501 }
6502
Owen Andersona21eb582009-07-10 17:35:01 +00006503 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006504 (A == Op0 || B == Op0)) {
6505 // A == (A^B) -> B == 0
6506 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006507 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006508 Context->getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006509 }
Chris Lattner3b874082008-11-16 05:38:51 +00006510
6511 // (A-B) == A -> B == 0
Owen Andersona21eb582009-07-10 17:35:01 +00006512 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006513 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Anderson24be4c12009-07-03 00:17:18 +00006514 Context->getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006515
6516 // A == (A-B) -> B == 0
Owen Andersona21eb582009-07-10 17:35:01 +00006517 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006518 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Anderson24be4c12009-07-03 00:17:18 +00006519 Context->getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006520
6521 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6522 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00006523 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6524 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006525 Value *X = 0, *Y = 0, *Z = 0;
6526
6527 if (A == C) {
6528 X = B; Y = D; Z = A;
6529 } else if (A == D) {
6530 X = B; Y = C; Z = A;
6531 } else if (B == C) {
6532 X = A; Y = D; Z = B;
6533 } else if (B == D) {
6534 X = A; Y = C; Z = B;
6535 }
6536
6537 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006538 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6539 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006540 I.setOperand(0, Op1);
Owen Anderson24be4c12009-07-03 00:17:18 +00006541 I.setOperand(1, Context->getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006542 return &I;
6543 }
6544 }
6545 }
6546 return Changed ? &I : 0;
6547}
6548
6549
6550/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6551/// and CmpRHS are both known to be integer constants.
6552Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6553 ConstantInt *DivRHS) {
6554 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6555 const APInt &CmpRHSV = CmpRHS->getValue();
6556
6557 // FIXME: If the operand types don't match the type of the divide
6558 // then don't attempt this transform. The code below doesn't have the
6559 // logic to deal with a signed divide and an unsigned compare (and
6560 // vice versa). This is because (x /s C1) <s C2 produces different
6561 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6562 // (x /u C1) <u C2. Simply casting the operands and result won't
6563 // work. :( The if statement below tests that condition and bails
6564 // if it finds it.
6565 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6566 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6567 return 0;
6568 if (DivRHS->isZero())
6569 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006570 if (DivIsSigned && DivRHS->isAllOnesValue())
6571 return 0; // The overflow computation also screws up here
6572 if (DivRHS->isOne())
6573 return 0; // Not worth bothering, and eliminates some funny cases
6574 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006575
6576 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6577 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6578 // C2 (CI). By solving for X we can turn this into a range check
6579 // instead of computing a divide.
Owen Anderson24be4c12009-07-03 00:17:18 +00006580 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006581
6582 // Determine if the product overflows by seeing if the product is
6583 // not equal to the divide. Make sure we do the same kind of divide
6584 // as in the LHS instruction that we're folding.
Owen Anderson24be4c12009-07-03 00:17:18 +00006585 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6586 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006587
6588 // Get the ICmp opcode
6589 ICmpInst::Predicate Pred = ICI.getPredicate();
6590
6591 // Figure out the interval that is being checked. For example, a comparison
6592 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6593 // Compute this interval based on the constants involved and the signedness of
6594 // the compare/divide. This computes a half-open interval, keeping track of
6595 // whether either value in the interval overflows. After analysis each
6596 // overflow variable is set to 0 if it's corresponding bound variable is valid
6597 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6598 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006599 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006600
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006601 if (!DivIsSigned) { // udiv
6602 // e.g. X/5 op 3 --> [15, 20)
6603 LoBound = Prod;
6604 HiOverflow = LoOverflow = ProdOV;
6605 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006606 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006607 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006608 if (CmpRHSV == 0) { // (X / pos) op 0
6609 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Anderson24be4c12009-07-03 00:17:18 +00006610 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6611 Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006612 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006613 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006614 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6615 HiOverflow = LoOverflow = ProdOV;
6616 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006617 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618 } else { // (X / pos) op neg
6619 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Anderson24be4c12009-07-03 00:17:18 +00006620 HiBound = AddOne(Prod, Context);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006621 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6622 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006623 ConstantInt* DivNeg =
6624 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6625 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006626 true) ? -1 : 0;
6627 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006628 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006629 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006630 if (CmpRHSV == 0) { // (X / neg) op 0
6631 // e.g. X/-5 op 0 --> [-4, 5)
Owen Anderson24be4c12009-07-03 00:17:18 +00006632 LoBound = AddOne(DivRHS, Context);
6633 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006634 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6635 HiOverflow = 1; // [INTMIN+1, overflow)
6636 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6637 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006638 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006639 // e.g. X/-5 op 3 --> [-19, -14)
Owen Anderson24be4c12009-07-03 00:17:18 +00006640 HiBound = AddOne(Prod, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006641 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6642 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006643 LoOverflow = AddWithOverflow(LoBound, HiBound,
6644 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006645 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006646 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6647 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006648 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006649 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006650 }
6651
6652 // Dividing by a negative swaps the condition. LT <-> GT
6653 Pred = ICmpInst::getSwappedPredicate(Pred);
6654 }
6655
6656 Value *X = DivI->getOperand(0);
6657 switch (Pred) {
Edwin Törökbd448e32009-07-14 16:55:14 +00006658 default: llvm_unreachable("Unhandled icmp opcode!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006659 case ICmpInst::ICMP_EQ:
6660 if (LoOverflow && HiOverflow)
Owen Anderson71f286c62009-07-21 18:03:38 +00006661 return ReplaceInstUsesWith(ICI, Context->getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006662 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006663 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006664 ICmpInst::ICMP_UGE, X, LoBound);
6665 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006667 ICmpInst::ICMP_ULT, X, HiBound);
6668 else
6669 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6670 case ICmpInst::ICMP_NE:
6671 if (LoOverflow && HiOverflow)
Owen Anderson71f286c62009-07-21 18:03:38 +00006672 return ReplaceInstUsesWith(ICI, Context->getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006673 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006674 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006675 ICmpInst::ICMP_ULT, X, LoBound);
6676 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006677 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006678 ICmpInst::ICMP_UGE, X, HiBound);
6679 else
6680 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6681 case ICmpInst::ICMP_ULT:
6682 case ICmpInst::ICMP_SLT:
6683 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson71f286c62009-07-21 18:03:38 +00006684 return ReplaceInstUsesWith(ICI, Context->getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006685 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson71f286c62009-07-21 18:03:38 +00006686 return ReplaceInstUsesWith(ICI, Context->getFalse());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006687 return new ICmpInst(*Context, Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006688 case ICmpInst::ICMP_UGT:
6689 case ICmpInst::ICMP_SGT:
6690 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson71f286c62009-07-21 18:03:38 +00006691 return ReplaceInstUsesWith(ICI, Context->getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006692 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson71f286c62009-07-21 18:03:38 +00006693 return ReplaceInstUsesWith(ICI, Context->getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006694 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006695 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006696 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006697 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006698 }
6699}
6700
6701
6702/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6703///
6704Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6705 Instruction *LHSI,
6706 ConstantInt *RHS) {
6707 const APInt &RHSV = RHS->getValue();
6708
6709 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006710 case Instruction::Trunc:
6711 if (ICI.isEquality() && LHSI->hasOneUse()) {
6712 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6713 // of the high bits truncated out of x are known.
6714 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6715 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6716 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6717 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6718 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6719
6720 // If all the high bits are known, we can do this xform.
6721 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6722 // Pull in the high bits from known-ones set.
6723 APInt NewRHS(RHS->getValue());
6724 NewRHS.zext(SrcBits);
6725 NewRHS |= KnownOne;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006726 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006727 Context->getConstantInt(NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006728 }
6729 }
6730 break;
6731
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006732 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6733 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6734 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6735 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006736 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6737 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006738 Value *CompareVal = LHSI->getOperand(0);
6739
6740 // If the sign bit of the XorCST is not set, there is no change to
6741 // the operation, just stop using the Xor.
6742 if (!XorCST->getValue().isNegative()) {
6743 ICI.setOperand(0, CompareVal);
6744 AddToWorkList(LHSI);
6745 return &ICI;
6746 }
6747
6748 // Was the old condition true if the operand is positive?
6749 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6750
6751 // If so, the new one isn't.
6752 isTrueIfPositive ^= true;
6753
6754 if (isTrueIfPositive)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006755 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006756 SubOne(RHS, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006757 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006758 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006759 AddOne(RHS, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006760 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006761
6762 if (LHSI->hasOneUse()) {
6763 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6764 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6765 const APInt &SignBit = XorCST->getValue();
6766 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767 ? ICI.getUnsignedPredicate()
6768 : ICI.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006769 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006770 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006771 }
6772
6773 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006774 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006775 const APInt &NotSignBit = XorCST->getValue();
6776 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6777 ? ICI.getUnsignedPredicate()
6778 : ICI.getSignedPredicate();
6779 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006780 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006781 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006782 }
6783 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006784 }
6785 break;
6786 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6787 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6788 LHSI->getOperand(0)->hasOneUse()) {
6789 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6790
6791 // If the LHS is an AND of a truncating cast, we can widen the
6792 // and/compare to be the input width without changing the value
6793 // produced, eliminating a cast.
6794 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6795 // We can do this transformation if either the AND constant does not
6796 // have its sign bit set or if it is an equality comparison.
6797 // Extending a relational comparison when we're checking the sign
6798 // bit would not work.
6799 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006800 (ICI.isEquality() ||
6801 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006802 uint32_t BitWidth =
6803 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6804 APInt NewCST = AndCST->getValue();
6805 NewCST.zext(BitWidth);
6806 APInt NewCI = RHSV;
6807 NewCI.zext(BitWidth);
6808 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006809 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006810 Context->getConstantInt(NewCST),LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006811 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006812 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Anderson24be4c12009-07-03 00:17:18 +00006813 Context->getConstantInt(NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006814 }
6815 }
6816
6817 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6818 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6819 // happens a LOT in code produced by the C front-end, for bitfield
6820 // access.
6821 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6822 if (Shift && !Shift->isShift())
6823 Shift = 0;
6824
6825 ConstantInt *ShAmt;
6826 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6827 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6828 const Type *AndTy = AndCST->getType(); // Type of the and.
6829
6830 // We can fold this as long as we can't shift unknown bits
6831 // into the mask. This can only happen with signed shift
6832 // rights, as they sign-extend.
6833 if (ShAmt) {
6834 bool CanFold = Shift->isLogicalShift();
6835 if (!CanFold) {
6836 // To test for the bad case of the signed shr, see if any
6837 // of the bits shifted in could be tested after the mask.
6838 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6839 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6840
6841 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6842 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6843 AndCST->getValue()) == 0)
6844 CanFold = true;
6845 }
6846
6847 if (CanFold) {
6848 Constant *NewCst;
6849 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson24be4c12009-07-03 00:17:18 +00006850 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006851 else
Owen Anderson24be4c12009-07-03 00:17:18 +00006852 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006853
6854 // Check to see if we are shifting out any of the bits being
6855 // compared.
Owen Anderson24be4c12009-07-03 00:17:18 +00006856 if (Context->getConstantExpr(Shift->getOpcode(),
6857 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006858 // If we shifted bits out, the fold is not going to work out.
6859 // As a special case, check to see if this means that the
6860 // result is always true or false now.
6861 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson71f286c62009-07-21 18:03:38 +00006862 return ReplaceInstUsesWith(ICI, Context->getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006863 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson71f286c62009-07-21 18:03:38 +00006864 return ReplaceInstUsesWith(ICI, Context->getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006865 } else {
6866 ICI.setOperand(1, NewCst);
6867 Constant *NewAndCST;
6868 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson24be4c12009-07-03 00:17:18 +00006869 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006870 else
Owen Anderson24be4c12009-07-03 00:17:18 +00006871 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006872 LHSI->setOperand(1, NewAndCST);
6873 LHSI->setOperand(0, Shift->getOperand(0));
6874 AddToWorkList(Shift); // Shift is dead.
6875 AddUsesToWorkList(ICI);
6876 return &ICI;
6877 }
6878 }
6879 }
6880
6881 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6882 // preferable because it allows the C<<Y expression to be hoisted out
6883 // of a loop if Y is invariant and X is not.
6884 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006885 ICI.isEquality() && !Shift->isArithmeticShift() &&
6886 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006887 // Compute C << Y.
6888 Value *NS;
6889 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006890 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006891 Shift->getOperand(1), "tmp");
6892 } else {
6893 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006894 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006895 Shift->getOperand(1), "tmp");
6896 }
6897 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6898
6899 // Compute X & (C << Y).
6900 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006901 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006902 InsertNewInstBefore(NewAnd, ICI);
6903
6904 ICI.setOperand(0, NewAnd);
6905 return &ICI;
6906 }
6907 }
6908 break;
6909
6910 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6911 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6912 if (!ShAmt) break;
6913
6914 uint32_t TypeBits = RHSV.getBitWidth();
6915
6916 // Check that the shift amount is in range. If not, don't perform
6917 // undefined shifts. When the shift is visited it will be
6918 // simplified.
6919 if (ShAmt->uge(TypeBits))
6920 break;
6921
6922 if (ICI.isEquality()) {
6923 // If we are comparing against bits always shifted out, the
6924 // comparison cannot succeed.
6925 Constant *Comp =
Owen Anderson24be4c12009-07-03 00:17:18 +00006926 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6927 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006928 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6929 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson24be4c12009-07-03 00:17:18 +00006930 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006931 return ReplaceInstUsesWith(ICI, Cst);
6932 }
6933
6934 if (LHSI->hasOneUse()) {
6935 // Otherwise strength reduce the shift into an and.
6936 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6937 Constant *Mask =
Owen Anderson24be4c12009-07-03 00:17:18 +00006938 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6939 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006940
6941 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006942 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006943 Mask, LHSI->getName()+".mask");
6944 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006945 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Anderson24be4c12009-07-03 00:17:18 +00006946 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006947 }
6948 }
6949
6950 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6951 bool TrueIfSigned = false;
6952 if (LHSI->hasOneUse() &&
6953 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6954 // (X << 31) <s 0 --> (X&1) != 0
Owen Anderson24be4c12009-07-03 00:17:18 +00006955 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006956 (TypeBits-ShAmt->getZExtValue()-1));
6957 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006958 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006959 Mask, LHSI->getName()+".mask");
6960 Value *And = InsertNewInstBefore(AndI, ICI);
6961
Owen Anderson6601fcd2009-07-09 23:48:35 +00006962 return new ICmpInst(*Context,
6963 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Anderson24be4c12009-07-03 00:17:18 +00006964 And, Context->getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006965 }
6966 break;
6967 }
6968
6969 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6970 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006971 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006972 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006973 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006974
Chris Lattner5ee84f82008-03-21 05:19:58 +00006975 // Check that the shift amount is in range. If not, don't perform
6976 // undefined shifts. When the shift is visited it will be
6977 // simplified.
6978 uint32_t TypeBits = RHSV.getBitWidth();
6979 if (ShAmt->uge(TypeBits))
6980 break;
6981
6982 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006983
Chris Lattner5ee84f82008-03-21 05:19:58 +00006984 // If we are comparing against bits always shifted out, the
6985 // comparison cannot succeed.
6986 APInt Comp = RHSV << ShAmtVal;
6987 if (LHSI->getOpcode() == Instruction::LShr)
6988 Comp = Comp.lshr(ShAmtVal);
6989 else
6990 Comp = Comp.ashr(ShAmtVal);
6991
6992 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6993 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson24be4c12009-07-03 00:17:18 +00006994 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006995 return ReplaceInstUsesWith(ICI, Cst);
6996 }
6997
6998 // Otherwise, check to see if the bits shifted out are known to be zero.
6999 // If so, we can compare against the unshifted value:
7000 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00007001 if (LHSI->hasOneUse() &&
7002 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007003 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007004 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007005 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00007006 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007007
Evan Chengfb9292a2008-04-23 00:38:06 +00007008 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00007009 // Otherwise strength reduce the shift into an and.
7010 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00007011 Constant *Mask = Context->getConstantInt(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007012
Chris Lattner5ee84f82008-03-21 05:19:58 +00007013 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00007014 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007015 Mask, LHSI->getName()+".mask");
7016 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007017 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Anderson24be4c12009-07-03 00:17:18 +00007018 Context->getConstantExprShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007019 }
7020 break;
7021 }
7022
7023 case Instruction::SDiv:
7024 case Instruction::UDiv:
7025 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7026 // Fold this div into the comparison, producing a range check.
7027 // Determine, based on the divide type, what the range is being
7028 // checked. If there is an overflow on the low or high side, remember
7029 // it, otherwise compute the range [low, hi) bounding the new value.
7030 // See: InsertRangeTest above for the kinds of replacements possible.
7031 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7032 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7033 DivRHS))
7034 return R;
7035 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007036
7037 case Instruction::Add:
7038 // Fold: icmp pred (add, X, C1), C2
7039
7040 if (!ICI.isEquality()) {
7041 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7042 if (!LHSC) break;
7043 const APInt &LHSV = LHSC->getValue();
7044
7045 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7046 .subtract(LHSV);
7047
7048 if (ICI.isSignedPredicate()) {
7049 if (CR.getLower().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007050 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007051 Context->getConstantInt(CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007052 } else if (CR.getUpper().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007053 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007054 Context->getConstantInt(CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007055 }
7056 } else {
7057 if (CR.getLower().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007058 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007059 Context->getConstantInt(CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007060 } else if (CR.getUpper().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007061 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007062 Context->getConstantInt(CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007063 }
7064 }
7065 }
7066 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007067 }
7068
7069 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7070 if (ICI.isEquality()) {
7071 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7072
7073 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7074 // the second operand is a constant, simplify a bit.
7075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7076 switch (BO->getOpcode()) {
7077 case Instruction::SRem:
7078 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7079 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7080 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7081 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7082 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00007083 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007084 BO->getName());
7085 InsertNewInstBefore(NewRem, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007086 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Anderson24be4c12009-07-03 00:17:18 +00007087 Context->getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007088 }
7089 }
7090 break;
7091 case Instruction::Add:
7092 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7093 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7094 if (BO->hasOneUse())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007095 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007096 Context->getConstantExprSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007097 } else if (RHSV == 0) {
7098 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7099 // efficiently invertible, or if the add has just this one use.
7100 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7101
Owen Anderson24be4c12009-07-03 00:17:18 +00007102 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007103 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Anderson24be4c12009-07-03 00:17:18 +00007104 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007105 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007106 else if (BO->hasOneUse()) {
Owen Anderson15b39322009-07-13 04:09:18 +00007107 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007108 InsertNewInstBefore(Neg, ICI);
7109 Neg->takeName(BO);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007110 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007111 }
7112 }
7113 break;
7114 case Instruction::Xor:
7115 // For the xor case, we can xor two constants together, eliminating
7116 // the explicit xor.
7117 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007118 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007119 Context->getConstantExprXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007120
7121 // FALLTHROUGH
7122 case Instruction::Sub:
7123 // Replace (([sub|xor] A, B) != 0) with (A != B)
7124 if (RHSV == 0)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007125 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007126 BO->getOperand(1));
7127 break;
7128
7129 case Instruction::Or:
7130 // If bits are being or'd in that are not present in the constant we
7131 // are comparing against, then the comparison could never succeed!
7132 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007133 Constant *NotCI = Context->getConstantExprNot(RHS);
7134 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7135 return ReplaceInstUsesWith(ICI,
7136 Context->getConstantInt(Type::Int1Ty,
7137 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007138 }
7139 break;
7140
7141 case Instruction::And:
7142 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143 // If bits are being compared against that are and'd out, then the
7144 // comparison can never succeed!
7145 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007146 return ReplaceInstUsesWith(ICI,
7147 Context->getConstantInt(Type::Int1Ty,
7148 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149
7150 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007152 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007153 ICmpInst::ICMP_NE, LHSI,
Owen Anderson24be4c12009-07-03 00:17:18 +00007154 Context->getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007155
7156 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007157 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 Value *X = BO->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +00007159 Constant *Zero = Context->getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007160 ICmpInst::Predicate pred = isICMP_NE ?
7161 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007162 return new ICmpInst(*Context, pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007163 }
7164
7165 // ((X & ~7) == 0) --> X < 8
7166 if (RHSV == 0 && isHighOnes(BOC)) {
7167 Value *X = BO->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +00007168 Constant *NegX = Context->getConstantExprNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007171 return new ICmpInst(*Context, pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007172 }
7173 }
7174 default: break;
7175 }
7176 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177 // Handle icmp {eq|ne} <intrinsic>, intcst.
7178 if (II->getIntrinsicID() == Intrinsic::bswap) {
7179 AddToWorkList(II);
7180 ICI.setOperand(0, II->getOperand(1));
Owen Anderson24be4c12009-07-03 00:17:18 +00007181 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007182 return &ICI;
7183 }
7184 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007185 }
7186 return 0;
7187}
7188
7189/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190/// We only handle extending casts so far.
7191///
7192Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7194 Value *LHSCIOp = LHSCI->getOperand(0);
7195 const Type *SrcTy = LHSCIOp->getType();
7196 const Type *DestTy = LHSCI->getType();
7197 Value *RHSCIOp;
7198
7199 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7200 // integer type is the same size as the pointer type.
Dan Gohmana80e2712009-07-21 23:21:54 +00007201 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7202 TD->getPointerSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007203 cast<IntegerType>(DestTy)->getBitWidth()) {
7204 Value *RHSOp = 0;
7205 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007206 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007207 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208 RHSOp = RHSC->getOperand(0);
7209 // If the pointer types don't match, insert a bitcast.
7210 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007211 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007212 }
7213
7214 if (RHSOp)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007215 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007216 }
7217
7218 // The code below only handles extension cast instructions, so far.
7219 // Enforce this.
7220 if (LHSCI->getOpcode() != Instruction::ZExt &&
7221 LHSCI->getOpcode() != Instruction::SExt)
7222 return 0;
7223
7224 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7225 bool isSignedCmp = ICI.isSignedPredicate();
7226
7227 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7228 // Not an extension from the same type?
7229 RHSCIOp = CI->getOperand(0);
7230 if (RHSCIOp->getType() != LHSCIOp->getType())
7231 return 0;
7232
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007233 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007234 // and the other is a zext), then we can't handle this.
7235 if (CI->getOpcode() != LHSCI->getOpcode())
7236 return 0;
7237
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007238 // Deal with equality cases early.
7239 if (ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007240 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007241
7242 // A signed comparison of sign extended values simplifies into a
7243 // signed comparison.
7244 if (isSignedCmp && isSignedExt)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007245 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007246
7247 // The other three cases all fold into an unsigned comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00007248 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007249 }
7250
7251 // If we aren't dealing with a constant on the RHS, exit early
7252 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7253 if (!CI)
7254 return 0;
7255
7256 // Compute the constant that would happen if we truncated to SrcTy then
7257 // reextended to DestTy.
Owen Anderson24be4c12009-07-03 00:17:18 +00007258 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7259 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7260 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007261
7262 // If the re-extended constant didn't change...
7263 if (Res2 == CI) {
7264 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007266 // %A = sext i16 %X to i32
7267 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007268 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007269 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007270 // because %A may have negative value.
7271 //
Chris Lattner3d816532008-07-11 04:09:09 +00007272 // However, we allow this when the compare is EQ/NE, because they are
7273 // signless.
7274 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007275 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007276 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007277 }
7278
7279 // The re-extended constant changed so the constant cannot be represented
7280 // in the shorter type. Consequently, we cannot emit a simple comparison.
7281
7282 // First, handle some easy cases. We know the result cannot be equal at this
7283 // point so handle the ICI.isEquality() cases
7284 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson71f286c62009-07-21 18:03:38 +00007285 return ReplaceInstUsesWith(ICI, Context->getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007286 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson71f286c62009-07-21 18:03:38 +00007287 return ReplaceInstUsesWith(ICI, Context->getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007288
7289 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290 // should have been folded away previously and not enter in here.
7291 Value *Result;
7292 if (isSignedCmp) {
7293 // We're performing a signed comparison.
7294 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson71f286c62009-07-21 18:03:38 +00007295 Result = Context->getFalse(); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007296 else
Owen Anderson71f286c62009-07-21 18:03:38 +00007297 Result = Context->getTrue(); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 } else {
7299 // We're performing an unsigned comparison.
7300 if (isSignedExt) {
7301 // We're performing an unsigned comp with a sign extended value.
7302 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson035d41d2009-07-13 20:58:05 +00007303 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007304 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7305 LHSCIOp, NegOne, ICI.getName()), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007306 } else {
7307 // Unsigned extend & unsigned compare -> always true.
Owen Anderson71f286c62009-07-21 18:03:38 +00007308 Result = Context->getTrue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007309 }
7310 }
7311
7312 // Finally, return the value computed.
7313 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007314 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007315 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007316
7317 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7318 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7319 "ICmp should be folded!");
7320 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00007321 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson035d41d2009-07-13 20:58:05 +00007322 return BinaryOperator::CreateNot(*Context, Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007323}
7324
7325Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7326 return commonShiftTransforms(I);
7327}
7328
7329Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7330 return commonShiftTransforms(I);
7331}
7332
7333Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007334 if (Instruction *R = commonShiftTransforms(I))
7335 return R;
7336
7337 Value *Op0 = I.getOperand(0);
7338
7339 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7340 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7341 if (CSI->isAllOnesValue())
7342 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007343
Dan Gohman2526aea2009-06-16 19:55:29 +00007344 // See if we can turn a signed shr into an unsigned shr.
7345 if (MaskedValueIsZero(Op0,
7346 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7347 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7348
7349 // Arithmetic shifting an all-sign-bit value is a no-op.
7350 unsigned NumSignBits = ComputeNumSignBits(Op0);
7351 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7352 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007353
Chris Lattnere3c504f2007-12-06 01:59:46 +00007354 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007355}
7356
7357Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7358 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7360
7361 // shl X, 0 == X and shr X, 0 == X
7362 // shl 0, X == 0 and shr 0, X == 0
Owen Anderson24be4c12009-07-03 00:17:18 +00007363 if (Op1 == Context->getNullValue(Op1->getType()) ||
7364 Op0 == Context->getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007365 return ReplaceInstUsesWith(I, Op0);
7366
7367 if (isa<UndefValue>(Op0)) {
7368 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7369 return ReplaceInstUsesWith(I, Op0);
7370 else // undef << X -> 0, undef >>u X -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00007371 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007372 }
7373 if (isa<UndefValue>(Op1)) {
7374 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7375 return ReplaceInstUsesWith(I, Op0);
7376 else // X << undef, X >>u undef -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00007377 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007378 }
7379
Dan Gohman2bc21562009-05-21 02:28:33 +00007380 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007381 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007382 return &I;
7383
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007384 // Try to fold constant and into select arguments.
7385 if (isa<Constant>(Op0))
7386 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7387 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7388 return R;
7389
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7391 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7392 return Res;
7393 return 0;
7394}
7395
7396Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7397 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007398 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007399
7400 // See if we can simplify any instructions used by the instruction whose sole
7401 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007402 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007403
Dan Gohman9e1657f2009-06-14 23:30:43 +00007404 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7405 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007406 //
7407 if (Op1->uge(TypeBits)) {
7408 if (I.getOpcode() != Instruction::AShr)
Owen Anderson24be4c12009-07-03 00:17:18 +00007409 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007410 else {
Owen Anderson24be4c12009-07-03 00:17:18 +00007411 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007412 return &I;
7413 }
7414 }
7415
7416 // ((X*C1) << C2) == (X * (C1 << C2))
7417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7418 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7419 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007420 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007421 Context->getConstantExprShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007422
7423 // Try to fold constant and into select arguments.
7424 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7425 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7426 return R;
7427 if (isa<PHINode>(Op0))
7428 if (Instruction *NV = FoldOpIntoPhi(I))
7429 return NV;
7430
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007431 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7432 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7433 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7434 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7435 // place. Don't try to do this transformation in this case. Also, we
7436 // require that the input operand is a shift-by-constant so that we have
7437 // confidence that the shifts will get folded together. We could do this
7438 // xform in more cases, but it is unlikely to be profitable.
7439 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7440 isa<ConstantInt>(TrOp->getOperand(1))) {
7441 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson24be4c12009-07-03 00:17:18 +00007442 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007443 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007444 I.getName());
7445 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7446
7447 // For logical shifts, the truncation has the effect of making the high
7448 // part of the register be zeros. Emulate this by inserting an AND to
7449 // clear the top bits as needed. This 'and' will usually be zapped by
7450 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007451 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7452 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007453 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7454
7455 // The mask we constructed says what the trunc would do if occurring
7456 // between the shifts. We want to know the effect *after* the second
7457 // shift. We know that it is a logical shift by a constant, so adjust the
7458 // mask as appropriate.
7459 if (I.getOpcode() == Instruction::Shl)
7460 MaskV <<= Op1->getZExtValue();
7461 else {
7462 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7463 MaskV = MaskV.lshr(Op1->getZExtValue());
7464 }
7465
Owen Anderson24be4c12009-07-03 00:17:18 +00007466 Instruction *And =
7467 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7468 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007469 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7470
7471 // Return the value truncated to the interesting size.
7472 return new TruncInst(And, I.getType());
7473 }
7474 }
7475
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007476 if (Op0->hasOneUse()) {
7477 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7478 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7479 Value *V1, *V2;
7480 ConstantInt *CC;
7481 switch (Op0BO->getOpcode()) {
7482 default: break;
7483 case Instruction::Add:
7484 case Instruction::And:
7485 case Instruction::Or:
7486 case Instruction::Xor: {
7487 // These operators commute.
7488 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7489 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007490 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7491 m_Specific(Op1)), *Context)){
Gabor Greifa645dd32008-05-16 19:29:10 +00007492 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007493 Op0BO->getOperand(0), Op1,
7494 Op0BO->getName());
7495 InsertNewInstBefore(YS, I); // (Y << C)
7496 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007497 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007498 Op0BO->getOperand(1)->getName());
7499 InsertNewInstBefore(X, I); // (X + (Y << C))
7500 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Anderson24be4c12009-07-03 00:17:18 +00007501 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7503 }
7504
7505 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7506 Value *Op0BOOp1 = Op0BO->getOperand(1);
7507 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7508 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007509 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersona21eb582009-07-10 17:35:01 +00007510 m_ConstantInt(CC)), *Context) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007511 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007512 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007513 Op0BO->getOperand(0), Op1,
7514 Op0BO->getName());
7515 InsertNewInstBefore(YS, I); // (Y << C)
7516 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007517 BinaryOperator::CreateAnd(V1,
7518 Context->getConstantExprShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007519 V1->getName()+".mask");
7520 InsertNewInstBefore(XM, I); // X & (CC << C)
7521
Gabor Greifa645dd32008-05-16 19:29:10 +00007522 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007523 }
7524 }
7525
7526 // FALL THROUGH.
7527 case Instruction::Sub: {
7528 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7529 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007530 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7531 m_Specific(Op1)), *Context)){
Gabor Greifa645dd32008-05-16 19:29:10 +00007532 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007533 Op0BO->getOperand(1), Op1,
7534 Op0BO->getName());
7535 InsertNewInstBefore(YS, I); // (Y << C)
7536 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007537 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007538 Op0BO->getOperand(0)->getName());
7539 InsertNewInstBefore(X, I); // (X + (Y << C))
7540 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Anderson24be4c12009-07-03 00:17:18 +00007541 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007542 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7543 }
7544
7545 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7546 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7547 match(Op0BO->getOperand(0),
7548 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersona21eb582009-07-10 17:35:01 +00007549 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007550 cast<BinaryOperator>(Op0BO->getOperand(0))
7551 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007552 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007553 Op0BO->getOperand(1), Op1,
7554 Op0BO->getName());
7555 InsertNewInstBefore(YS, I); // (Y << C)
7556 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007557 BinaryOperator::CreateAnd(V1,
7558 Context->getConstantExprShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007559 V1->getName()+".mask");
7560 InsertNewInstBefore(XM, I); // X & (CC << C)
7561
Gabor Greifa645dd32008-05-16 19:29:10 +00007562 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007563 }
7564
7565 break;
7566 }
7567 }
7568
7569
7570 // If the operand is an bitwise operator with a constant RHS, and the
7571 // shift is the only use, we can pull it out of the shift.
7572 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7573 bool isValid = true; // Valid only for And, Or, Xor
7574 bool highBitSet = false; // Transform if high bit of constant set?
7575
7576 switch (Op0BO->getOpcode()) {
7577 default: isValid = false; break; // Do not perform transform!
7578 case Instruction::Add:
7579 isValid = isLeftShift;
7580 break;
7581 case Instruction::Or:
7582 case Instruction::Xor:
7583 highBitSet = false;
7584 break;
7585 case Instruction::And:
7586 highBitSet = true;
7587 break;
7588 }
7589
7590 // If this is a signed shift right, and the high bit is modified
7591 // by the logical operation, do not perform the transformation.
7592 // The highBitSet boolean indicates the value of the high bit of
7593 // the constant which would cause it to be modified for this
7594 // operation.
7595 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007596 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007597 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007598
7599 if (isValid) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007600 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007601
7602 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007603 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007604 InsertNewInstBefore(NewShift, I);
7605 NewShift->takeName(Op0BO);
7606
Gabor Greifa645dd32008-05-16 19:29:10 +00007607 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007608 NewRHS);
7609 }
7610 }
7611 }
7612 }
7613
7614 // Find out if this is a shift of a shift by a constant.
7615 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7616 if (ShiftOp && !ShiftOp->isShift())
7617 ShiftOp = 0;
7618
7619 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7620 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7621 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7622 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7623 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7624 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7625 Value *X = ShiftOp->getOperand(0);
7626
7627 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007628
7629 const IntegerType *Ty = cast<IntegerType>(I.getType());
7630
7631 // Check for (X << c1) << c2 and (X >> c1) >> c2
7632 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007633 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7634 // saturates.
7635 if (AmtSum >= TypeBits) {
7636 if (I.getOpcode() != Instruction::AShr)
Owen Anderson24be4c12009-07-03 00:17:18 +00007637 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007638 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7639 }
7640
Gabor Greifa645dd32008-05-16 19:29:10 +00007641 return BinaryOperator::Create(I.getOpcode(), X,
Owen Anderson24be4c12009-07-03 00:17:18 +00007642 Context->getConstantInt(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007643 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7644 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007645 if (AmtSum >= TypeBits)
Owen Anderson24be4c12009-07-03 00:17:18 +00007646 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007647
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007648 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Anderson24be4c12009-07-03 00:17:18 +00007649 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007650 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7651 I.getOpcode() == Instruction::LShr) {
7652 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007653 if (AmtSum >= TypeBits)
7654 AmtSum = TypeBits-1;
7655
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007656 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007657 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007658 InsertNewInstBefore(Shift, I);
7659
7660 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007661 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007662 }
7663
7664 // Okay, if we get here, one shift must be left, and the other shift must be
7665 // right. See if the amounts are equal.
7666 if (ShiftAmt1 == ShiftAmt2) {
7667 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7668 if (I.getOpcode() == Instruction::Shl) {
7669 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Anderson24be4c12009-07-03 00:17:18 +00007670 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007671 }
7672 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7673 if (I.getOpcode() == Instruction::LShr) {
7674 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Anderson24be4c12009-07-03 00:17:18 +00007675 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007676 }
7677 // We can simplify ((X << C) >>s C) into a trunc + sext.
7678 // NOTE: we could do this for any C, but that would make 'unusual' integer
7679 // types. For now, just stick to ones well-supported by the code
7680 // generators.
7681 const Type *SExtType = 0;
7682 switch (Ty->getBitWidth() - ShiftAmt1) {
7683 case 1 :
7684 case 8 :
7685 case 16 :
7686 case 32 :
7687 case 64 :
7688 case 128:
Owen Anderson24be4c12009-07-03 00:17:18 +00007689 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007690 break;
7691 default: break;
7692 }
7693 if (SExtType) {
7694 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7695 InsertNewInstBefore(NewTrunc, I);
7696 return new SExtInst(NewTrunc, Ty);
7697 }
7698 // Otherwise, we can't handle it yet.
7699 } else if (ShiftAmt1 < ShiftAmt2) {
7700 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7701
7702 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7703 if (I.getOpcode() == Instruction::Shl) {
7704 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7705 ShiftOp->getOpcode() == Instruction::AShr);
7706 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007707 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007708 InsertNewInstBefore(Shift, I);
7709
7710 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007711 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007712 }
7713
7714 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7715 if (I.getOpcode() == Instruction::LShr) {
7716 assert(ShiftOp->getOpcode() == Instruction::Shl);
7717 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007718 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007719 InsertNewInstBefore(Shift, I);
7720
7721 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007722 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007723 }
7724
7725 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7726 } else {
7727 assert(ShiftAmt2 < ShiftAmt1);
7728 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7729
7730 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7731 if (I.getOpcode() == Instruction::Shl) {
7732 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7733 ShiftOp->getOpcode() == Instruction::AShr);
7734 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007735 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Anderson24be4c12009-07-03 00:17:18 +00007736 Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007737 InsertNewInstBefore(Shift, I);
7738
7739 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007740 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007741 }
7742
7743 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7744 if (I.getOpcode() == Instruction::LShr) {
7745 assert(ShiftOp->getOpcode() == Instruction::Shl);
7746 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007747 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007748 InsertNewInstBefore(Shift, I);
7749
7750 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007751 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007752 }
7753
7754 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7755 }
7756 }
7757 return 0;
7758}
7759
7760
7761/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7762/// expression. If so, decompose it, returning some value X, such that Val is
7763/// X*Scale+Offset.
7764///
7765static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007766 int &Offset, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007767 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7768 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7769 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007770 Scale = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +00007771 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007772 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7773 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7774 if (I->getOpcode() == Instruction::Shl) {
7775 // This is a value scaled by '1 << the shift amt'.
7776 Scale = 1U << RHS->getZExtValue();
7777 Offset = 0;
7778 return I->getOperand(0);
7779 } else if (I->getOpcode() == Instruction::Mul) {
7780 // This value is scaled by 'RHS'.
7781 Scale = RHS->getZExtValue();
7782 Offset = 0;
7783 return I->getOperand(0);
7784 } else if (I->getOpcode() == Instruction::Add) {
7785 // We have X+C. Check to see if we really have (X*C2)+C1,
7786 // where C1 is divisible by C2.
7787 unsigned SubScale;
7788 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007789 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7790 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007791 Offset += RHS->getZExtValue();
7792 Scale = SubScale;
7793 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007794 }
7795 }
7796 }
7797
7798 // Otherwise, we can't look past this.
7799 Scale = 1;
7800 Offset = 0;
7801 return Val;
7802}
7803
7804
7805/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7806/// try to eliminate the cast by moving the type information into the alloc.
7807Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7808 AllocationInst &AI) {
7809 const PointerType *PTy = cast<PointerType>(CI.getType());
7810
7811 // Remove any uses of AI that are dead.
7812 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7813
7814 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7815 Instruction *User = cast<Instruction>(*UI++);
7816 if (isInstructionTriviallyDead(User)) {
7817 while (UI != E && *UI == User)
7818 ++UI; // If this instruction uses AI more than once, don't break UI.
7819
7820 ++NumDeadInst;
7821 DOUT << "IC: DCE: " << *User;
7822 EraseInstFromFunction(*User);
7823 }
7824 }
Dan Gohmana80e2712009-07-21 23:21:54 +00007825
7826 // This requires TargetData to get the alloca alignment and size information.
7827 if (!TD) return 0;
7828
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007829 // Get the type really allocated and the type casted to.
7830 const Type *AllocElTy = AI.getAllocatedType();
7831 const Type *CastElTy = PTy->getElementType();
7832 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7833
7834 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7835 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7836 if (CastElTyAlign < AllocElTyAlign) return 0;
7837
7838 // If the allocation has multiple uses, only promote it if we are strictly
7839 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007840 // same, we open the door to infinite loops of various kinds. (A reference
7841 // from a dbg.declare doesn't count as a use for this purpose.)
7842 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7843 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007844
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007845 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7846 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007847 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7848
7849 // See if we can satisfy the modulus by pulling a scale out of the array
7850 // size argument.
7851 unsigned ArraySizeScale;
7852 int ArrayOffset;
7853 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007854 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7855 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007856
7857 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7858 // do the xform.
7859 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7860 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7861
7862 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7863 Value *Amt = 0;
7864 if (Scale == 1) {
7865 Amt = NumElements;
7866 } else {
7867 // If the allocation size is constant, form a constant mul expression
Owen Anderson24be4c12009-07-03 00:17:18 +00007868 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007869 if (isa<ConstantInt>(NumElements))
Owen Anderson24be4c12009-07-03 00:17:18 +00007870 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman8fd520a2009-06-15 22:12:54 +00007871 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007872 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007873 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007874 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007875 Amt = InsertNewInstBefore(Tmp, AI);
7876 }
7877 }
7878
7879 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007880 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007881 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007882 Amt = InsertNewInstBefore(Tmp, AI);
7883 }
7884
7885 AllocationInst *New;
7886 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +00007887 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007888 else
Owen Anderson140166d2009-07-15 23:53:25 +00007889 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007890 InsertNewInstBefore(New, AI);
7891 New->takeName(&AI);
7892
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007893 // If the allocation has one real use plus a dbg.declare, just remove the
7894 // declare.
7895 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7896 EraseInstFromFunction(*DI);
7897 }
7898 // If the allocation has multiple real uses, insert a cast and change all
7899 // things that used it to use the new cast. This will also hack on CI, but it
7900 // will die soon.
7901 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007902 AddUsesToWorkList(AI);
7903 // New is the allocation instruction, pointer typed. AI is the original
7904 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7905 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7906 InsertNewInstBefore(NewCast, AI);
7907 AI.replaceAllUsesWith(NewCast);
7908 }
7909 return ReplaceInstUsesWith(CI, New);
7910}
7911
7912/// CanEvaluateInDifferentType - Return true if we can take the specified value
7913/// and return it as type Ty without inserting any new casts and without
7914/// changing the computed value. This is used by code that tries to decide
7915/// whether promoting or shrinking integer operations to wider or smaller types
7916/// will allow us to eliminate a truncate or extend.
7917///
7918/// This is a truncation operation if Ty is smaller than V->getType(), or an
7919/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007920///
7921/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7922/// should return true if trunc(V) can be computed by computing V in the smaller
7923/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7924/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7925/// efficiently truncated.
7926///
7927/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7928/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7929/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007930bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007931 unsigned CastOpc,
7932 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007933 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007934 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 return true;
7936
7937 Instruction *I = dyn_cast<Instruction>(V);
7938 if (!I) return false;
7939
Dan Gohman8fd520a2009-06-15 22:12:54 +00007940 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007941
Chris Lattneref70bb82007-08-02 06:11:14 +00007942 // If this is an extension or truncate, we can often eliminate it.
7943 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7944 // If this is a cast from the destination type, we can trivially eliminate
7945 // it, and this will remove a cast overall.
7946 if (I->getOperand(0)->getType() == Ty) {
7947 // If the first operand is itself a cast, and is eliminable, do not count
7948 // this as an eliminable cast. We would prefer to eliminate those two
7949 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007950 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007951 ++NumCastsRemoved;
7952 return true;
7953 }
7954 }
7955
7956 // We can't extend or shrink something that has multiple uses: doing so would
7957 // require duplicating the instruction in general, which isn't profitable.
7958 if (!I->hasOneUse()) return false;
7959
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007960 unsigned Opc = I->getOpcode();
7961 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007962 case Instruction::Add:
7963 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007964 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007965 case Instruction::And:
7966 case Instruction::Or:
7967 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007968 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007969 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007970 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007971 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007972 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007973
Eli Friedman08c45bc2009-07-13 22:46:01 +00007974 case Instruction::UDiv:
7975 case Instruction::URem: {
7976 // UDiv and URem can be truncated if all the truncated bits are zero.
7977 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7978 uint32_t BitWidth = Ty->getScalarSizeInBits();
7979 if (BitWidth < OrigBitWidth) {
7980 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7981 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7982 MaskedValueIsZero(I->getOperand(1), Mask)) {
7983 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7984 NumCastsRemoved) &&
7985 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7986 NumCastsRemoved);
7987 }
7988 }
7989 break;
7990 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007991 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992 // If we are truncating the result of this SHL, and if it's a shift of a
7993 // constant amount, we can always perform a SHL in a smaller type.
7994 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007995 uint32_t BitWidth = Ty->getScalarSizeInBits();
7996 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007997 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007998 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007999 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008000 }
8001 break;
8002 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008003 // If this is a truncate of a logical shr, we can truncate it to a smaller
8004 // lshr iff we know that the bits we would otherwise be shifting in are
8005 // already zeros.
8006 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008007 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8008 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008009 if (BitWidth < OrigBitWidth &&
8010 MaskedValueIsZero(I->getOperand(0),
8011 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8012 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00008013 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008014 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008015 }
8016 }
8017 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008018 case Instruction::ZExt:
8019 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00008020 case Instruction::Trunc:
8021 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00008022 // can safely replace it. Note that replacing it does not reduce the number
8023 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008024 if (Opc == CastOpc)
8025 return true;
8026
8027 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00008028 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008029 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008030 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008031 case Instruction::Select: {
8032 SelectInst *SI = cast<SelectInst>(I);
8033 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008034 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008035 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008036 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008037 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008038 case Instruction::PHI: {
8039 // We can change a phi if we can change all operands.
8040 PHINode *PN = cast<PHINode>(I);
8041 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8042 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008043 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008044 return false;
8045 return true;
8046 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008047 default:
8048 // TODO: Can handle more cases here.
8049 break;
8050 }
8051
8052 return false;
8053}
8054
8055/// EvaluateInDifferentType - Given an expression that
8056/// CanEvaluateInDifferentType returns true for, actually insert the code to
8057/// evaluate the expression.
8058Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8059 bool isSigned) {
8060 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +00008061 return Context->getConstantExprIntegerCast(C, Ty,
8062 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008063
8064 // Otherwise, it must be an instruction.
8065 Instruction *I = cast<Instruction>(V);
8066 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008067 unsigned Opc = I->getOpcode();
8068 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008069 case Instruction::Add:
8070 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008071 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008072 case Instruction::And:
8073 case Instruction::Or:
8074 case Instruction::Xor:
8075 case Instruction::AShr:
8076 case Instruction::LShr:
Eli Friedman08c45bc2009-07-13 22:46:01 +00008077 case Instruction::Shl:
8078 case Instruction::UDiv:
8079 case Instruction::URem: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008080 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8081 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008082 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008083 break;
8084 }
8085 case Instruction::Trunc:
8086 case Instruction::ZExt:
8087 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008088 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008089 // just return the source. There's no need to insert it because it is not
8090 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008091 if (I->getOperand(0)->getType() == Ty)
8092 return I->getOperand(0);
8093
Chris Lattner4200c2062008-06-18 04:00:49 +00008094 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008095 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008096 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008097 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008098 case Instruction::Select: {
8099 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8100 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8101 Res = SelectInst::Create(I->getOperand(0), True, False);
8102 break;
8103 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008104 case Instruction::PHI: {
8105 PHINode *OPN = cast<PHINode>(I);
8106 PHINode *NPN = PHINode::Create(Ty);
8107 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8108 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8109 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8110 }
8111 Res = NPN;
8112 break;
8113 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008114 default:
8115 // TODO: Can handle more cases here.
Edwin Törökbd448e32009-07-14 16:55:14 +00008116 llvm_unreachable("Unreachable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008117 break;
8118 }
8119
Chris Lattner4200c2062008-06-18 04:00:49 +00008120 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008121 return InsertNewInstBefore(Res, *I);
8122}
8123
8124/// @brief Implement the transforms common to all CastInst visitors.
8125Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8126 Value *Src = CI.getOperand(0);
8127
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008128 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8129 // eliminate it now.
8130 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8131 if (Instruction::CastOps opc =
8132 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8133 // The first cast (CSrc) is eliminable so we need to fix up or replace
8134 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008135 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008136 }
8137 }
8138
8139 // If we are casting a select then fold the cast into the select
8140 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8141 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8142 return NV;
8143
8144 // If we are casting a PHI then fold the cast into the PHI
8145 if (isa<PHINode>(Src))
8146 if (Instruction *NV = FoldOpIntoPhi(CI))
8147 return NV;
8148
8149 return 0;
8150}
8151
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008152/// FindElementAtOffset - Given a type and a constant offset, determine whether
8153/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008154/// the specified offset. If so, fill them into NewIndices and return the
8155/// resultant element type, otherwise return null.
8156static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8157 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008158 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008159 LLVMContext *Context) {
Dan Gohmana80e2712009-07-21 23:21:54 +00008160 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +00008161 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008162
8163 // Start with the index over the outer type. Note that the type size
8164 // might be zero (even if the offset isn't zero) if the indexed type
8165 // is something like [0 x {int, int}]
8166 const Type *IntPtrTy = TD->getIntPtrType();
8167 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008168 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008169 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008170 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008171
Chris Lattnerce48c462009-01-11 20:15:20 +00008172 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008173 if (Offset < 0) {
8174 --FirstIdx;
8175 Offset += TySize;
8176 assert(Offset >= 0);
8177 }
8178 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8179 }
8180
Owen Anderson24be4c12009-07-03 00:17:18 +00008181 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008182
8183 // Index into the types. If we fail, set OrigBase to null.
8184 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008185 // Indexing into tail padding between struct/array elements.
8186 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008187 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008188
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008189 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8190 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008191 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8192 "Offset must stay within the indexed type");
8193
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008194 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson24be4c12009-07-03 00:17:18 +00008195 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008196
8197 Offset -= SL->getElementOffset(Elt);
8198 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008199 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008200 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008201 assert(EltSize && "Cannot index into a zero-sized array");
Owen Anderson24be4c12009-07-03 00:17:18 +00008202 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008203 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008204 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008205 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008206 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008207 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008208 }
8209 }
8210
Chris Lattner54dddc72009-01-24 01:00:13 +00008211 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008212}
8213
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008214/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8215Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8216 Value *Src = CI.getOperand(0);
8217
8218 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8219 // If casting the result of a getelementptr instruction with no offset, turn
8220 // this into a cast of the original pointer!
8221 if (GEP->hasAllZeroIndices()) {
8222 // Changing the cast operand is usually not a good idea but it is safe
8223 // here because the pointer operand is being replaced with another
8224 // pointer operand so the opcode doesn't need to change.
8225 AddToWorkList(GEP);
8226 CI.setOperand(0, GEP->getOperand(0));
8227 return &CI;
8228 }
8229
8230 // If the GEP has a single use, and the base pointer is a bitcast, and the
8231 // GEP computes a constant offset, see if we can convert these three
8232 // instructions into fewer. This typically happens with unions and other
8233 // non-type-safe code.
Dan Gohmana80e2712009-07-21 23:21:54 +00008234 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008235 if (GEP->hasAllConstantIndices()) {
8236 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008237 ConstantInt *OffsetV =
8238 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008239 int64_t Offset = OffsetV->getSExtValue();
8240
8241 // Get the base pointer input of the bitcast, and the type it points to.
8242 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8243 const Type *GEPIdxTy =
8244 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008245 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008246 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008247 // If we were able to index down into an element, create the GEP
8248 // and bitcast the result. This eliminates one bitcast, potentially
8249 // two.
8250 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8251 NewIndices.begin(),
8252 NewIndices.end(), "");
8253 InsertNewInstBefore(NGEP, CI);
8254 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008255
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008256 if (isa<BitCastInst>(CI))
8257 return new BitCastInst(NGEP, CI.getType());
8258 assert(isa<PtrToIntInst>(CI));
8259 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008260 }
8261 }
8262 }
8263 }
8264
8265 return commonCastTransforms(CI);
8266}
8267
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008268/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8269/// type like i42. We don't want to introduce operations on random non-legal
8270/// integer types where they don't already exist in the code. In the future,
8271/// we should consider making this based off target-data, so that 32-bit targets
8272/// won't get i64 operations etc.
8273static bool isSafeIntegerType(const Type *Ty) {
8274 switch (Ty->getPrimitiveSizeInBits()) {
8275 case 8:
8276 case 16:
8277 case 32:
8278 case 64:
8279 return true;
8280 default:
8281 return false;
8282 }
8283}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008284
Eli Friedman827e37a2009-07-13 20:58:59 +00008285/// commonIntCastTransforms - This function implements the common transforms
8286/// for trunc, zext, and sext.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008287Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8288 if (Instruction *Result = commonCastTransforms(CI))
8289 return Result;
8290
8291 Value *Src = CI.getOperand(0);
8292 const Type *SrcTy = Src->getType();
8293 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008294 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8295 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008296
8297 // See if we can simplify any instructions used by the LHS whose sole
8298 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008299 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008300 return &CI;
8301
8302 // If the source isn't an instruction or has more than one use then we
8303 // can't do anything more.
8304 Instruction *SrcI = dyn_cast<Instruction>(Src);
8305 if (!SrcI || !Src->hasOneUse())
8306 return 0;
8307
8308 // Attempt to propagate the cast into the instruction for int->int casts.
8309 int NumCastsRemoved = 0;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008310 // Only do this if the dest type is a simple type, don't convert the
8311 // expression tree to something weird like i93 unless the source is also
8312 // strange.
8313 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman8fd520a2009-06-15 22:12:54 +00008314 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8315 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008316 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008317 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008318 // eliminates the cast, so it is always a win. If this is a zero-extension,
8319 // we need to do an AND to maintain the clear top-part of the computation,
8320 // so we require that the input have eliminated at least one cast. If this
8321 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008322 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008323 bool DoXForm = false;
8324 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 switch (CI.getOpcode()) {
8326 default:
8327 // All the others use floating point so we shouldn't actually
8328 // get here because of the check above.
Edwin Törökbd448e32009-07-14 16:55:14 +00008329 llvm_unreachable("Unknown cast type");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008330 case Instruction::Trunc:
8331 DoXForm = true;
8332 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008333 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008334 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008335 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008336 // If it's unnecessary to issue an AND to clear the high bits, it's
8337 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008338 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008339 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8340 if (MaskedValueIsZero(TryRes, Mask))
8341 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008342
8343 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008344 if (TryI->use_empty())
8345 EraseInstFromFunction(*TryI);
8346 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008347 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008348 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008349 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008350 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008351 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008352 // If we do not have to emit the truncate + sext pair, then it's always
8353 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008354 //
8355 // It's not safe to eliminate the trunc + sext pair if one of the
8356 // eliminated cast is a truncate. e.g.
8357 // t2 = trunc i32 t1 to i16
8358 // t3 = sext i16 t2 to i32
8359 // !=
8360 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008361 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008362 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8363 if (NumSignBits > (DestBitSize - SrcBitSize))
8364 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008365
8366 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008367 if (TryI->use_empty())
8368 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008369 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008370 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008371 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008372 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008373
8374 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008375 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8376 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008377 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8378 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008379 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008380 // Just replace this cast with the result.
8381 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008383 assert(Res->getType() == DestTy);
8384 switch (CI.getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +00008385 default: llvm_unreachable("Unknown cast type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008386 case Instruction::Trunc:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008387 // Just replace this cast with the result.
8388 return ReplaceInstUsesWith(CI, Res);
8389 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008390 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008391
8392 // If the high bits are already zero, just replace this cast with the
8393 // result.
8394 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8395 if (MaskedValueIsZero(Res, Mask))
8396 return ReplaceInstUsesWith(CI, Res);
8397
8398 // We need to emit an AND to clear the high bits.
Owen Anderson24be4c12009-07-03 00:17:18 +00008399 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008400 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008401 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008402 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008403 case Instruction::SExt: {
8404 // If the high bits are already filled with sign bit, just replace this
8405 // cast with the result.
8406 unsigned NumSignBits = ComputeNumSignBits(Res);
8407 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008408 return ReplaceInstUsesWith(CI, Res);
8409
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008410 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008411 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008412 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8413 CI), DestTy);
8414 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008415 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008416 }
8417 }
8418
8419 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8420 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8421
8422 switch (SrcI->getOpcode()) {
8423 case Instruction::Add:
8424 case Instruction::Mul:
8425 case Instruction::And:
8426 case Instruction::Or:
8427 case Instruction::Xor:
8428 // If we are discarding information, rewrite.
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008429 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8430 // Don't insert two casts unless at least one can be eliminated.
8431 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008432 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008433 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8434 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008435 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008436 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8437 }
8438 }
8439
8440 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8441 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8442 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson71f286c62009-07-21 18:03:38 +00008443 Op1 == Context->getTrue() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008444 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008445 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008446 return BinaryOperator::CreateXor(New,
8447 Context->getConstantInt(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008448 }
8449 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008450
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008451 case Instruction::Shl: {
8452 // Canonicalize trunc inside shl, if we can.
8453 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8454 if (CI && DestBitSize < SrcBitSize &&
8455 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8456 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8457 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008458 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008459 }
8460 break;
Eli Friedman1cfc6b42009-07-13 21:45:57 +00008461 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008462 }
8463 return 0;
8464}
8465
8466Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8467 if (Instruction *Result = commonIntCastTransforms(CI))
8468 return Result;
8469
8470 Value *Src = CI.getOperand(0);
8471 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008472 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8473 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008474
8475 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman37a5d412009-07-18 09:21:25 +00008476 if (DestBitWidth == 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +00008477 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner32177f82009-03-24 18:15:30 +00008478 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008479 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson6601fcd2009-07-09 23:48:35 +00008480 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008481 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008482
Chris Lattner32177f82009-03-24 18:15:30 +00008483 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8484 ConstantInt *ShAmtV = 0;
8485 Value *ShiftOp = 0;
8486 if (Src->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00008487 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner32177f82009-03-24 18:15:30 +00008488 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8489
8490 // Get a mask for the bits shifting in.
8491 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8492 if (MaskedValueIsZero(ShiftOp, Mask)) {
8493 if (ShAmt >= DestBitWidth) // All zeros.
Owen Anderson24be4c12009-07-03 00:17:18 +00008494 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008495
8496 // Okay, we can shrink this. Truncate the input, then return a new
8497 // shift.
8498 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008499 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008500 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008501 }
8502 }
8503
8504 return 0;
8505}
8506
Evan Chenge3779cf2008-03-24 00:21:34 +00008507/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8508/// in order to eliminate the icmp.
8509Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8510 bool DoXform) {
8511 // If we are just checking for a icmp eq of a single bit and zext'ing it
8512 // to an integer, then shift the bit to the appropriate place and then
8513 // cast to integer to avoid the comparison.
8514 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8515 const APInt &Op1CV = Op1C->getValue();
8516
8517 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8518 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8519 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8520 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8521 if (!DoXform) return ICI;
8522
8523 Value *In = ICI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +00008524 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008525 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008526 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008527 In->getName()+".lobit"),
8528 CI);
8529 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008530 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008531 false/*ZExt*/, "tmp", &CI);
8532
8533 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Anderson24be4c12009-07-03 00:17:18 +00008534 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008535 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008536 In->getName()+".not"),
8537 CI);
8538 }
8539
8540 return ReplaceInstUsesWith(CI, In);
8541 }
8542
8543
8544
8545 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8546 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8547 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8548 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8549 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8550 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8551 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8552 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8553 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8554 // This only works for EQ and NE
8555 ICI->isEquality()) {
8556 // If Op1C some other power of two, convert:
8557 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8558 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8559 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8560 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8561
8562 APInt KnownZeroMask(~KnownZero);
8563 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8564 if (!DoXform) return ICI;
8565
8566 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8567 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8568 // (X&4) == 2 --> false
8569 // (X&4) != 2 --> true
Owen Anderson24be4c12009-07-03 00:17:18 +00008570 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8571 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008572 return ReplaceInstUsesWith(CI, Res);
8573 }
8574
8575 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8576 Value *In = ICI->getOperand(0);
8577 if (ShiftAmt) {
8578 // Perform a logical shr by shiftamt.
8579 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008580 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Anderson24be4c12009-07-03 00:17:18 +00008581 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chenge3779cf2008-03-24 00:21:34 +00008582 In->getName()+".lobit"), CI);
8583 }
8584
8585 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Anderson24be4c12009-07-03 00:17:18 +00008586 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008587 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008588 InsertNewInstBefore(cast<Instruction>(In), CI);
8589 }
8590
8591 if (CI.getType() == In->getType())
8592 return ReplaceInstUsesWith(CI, In);
8593 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008594 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008595 }
8596 }
8597 }
8598
8599 return 0;
8600}
8601
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008602Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8603 // If one of the common conversion will work ..
8604 if (Instruction *Result = commonIntCastTransforms(CI))
8605 return Result;
8606
8607 Value *Src = CI.getOperand(0);
8608
Chris Lattner215d56e2009-02-17 20:47:23 +00008609 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8610 // types and if the sizes are just right we can convert this into a logical
8611 // 'and' which will be much cheaper than the pair of casts.
8612 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8613 // Get the sizes of the types involved. We know that the intermediate type
8614 // will be smaller than A or C, but don't know the relation between A and C.
8615 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008616 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8617 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8618 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008619 // If we're actually extending zero bits, then if
8620 // SrcSize < DstSize: zext(a & mask)
8621 // SrcSize == DstSize: a & mask
8622 // SrcSize > DstSize: trunc(a) & mask
8623 if (SrcSize < DstSize) {
8624 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008625 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008626 Instruction *And =
8627 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8628 InsertNewInstBefore(And, CI);
8629 return new ZExtInst(And, CI.getType());
8630 } else if (SrcSize == DstSize) {
8631 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008632 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008633 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008634 } else if (SrcSize > DstSize) {
8635 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8636 InsertNewInstBefore(Trunc, CI);
8637 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008638 return BinaryOperator::CreateAnd(Trunc,
8639 Context->getConstantInt(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008640 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008641 }
8642 }
8643
Evan Chenge3779cf2008-03-24 00:21:34 +00008644 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8645 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008646
Evan Chenge3779cf2008-03-24 00:21:34 +00008647 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8648 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8649 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8650 // of the (zext icmp) will be transformed.
8651 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8652 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8653 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8654 (transformZExtICmp(LHS, CI, false) ||
8655 transformZExtICmp(RHS, CI, false))) {
8656 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8657 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008658 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008659 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008660 }
8661
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008662 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008663 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8664 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8665 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8666 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008667 if (TI0->getType() == CI.getType())
8668 return
8669 BinaryOperator::CreateAnd(TI0,
Owen Anderson24be4c12009-07-03 00:17:18 +00008670 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008671 }
8672
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008673 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8674 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8675 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8676 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8677 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8678 And->getOperand(1) == C)
8679 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8680 Value *TI0 = TI->getOperand(0);
8681 if (TI0->getType() == CI.getType()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00008682 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008683 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8684 InsertNewInstBefore(NewAnd, *And);
8685 return BinaryOperator::CreateXor(NewAnd, ZC);
8686 }
8687 }
8688
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008689 return 0;
8690}
8691
8692Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8693 if (Instruction *I = commonIntCastTransforms(CI))
8694 return I;
8695
8696 Value *Src = CI.getOperand(0);
8697
Dan Gohman35b76162008-10-30 20:40:10 +00008698 // Canonicalize sign-extend from i1 to a select.
8699 if (Src->getType() == Type::Int1Ty)
8700 return SelectInst::Create(Src,
Owen Anderson035d41d2009-07-13 20:58:05 +00008701 Context->getAllOnesValue(CI.getType()),
Owen Anderson24be4c12009-07-03 00:17:18 +00008702 Context->getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008703
8704 // See if the value being truncated is already sign extended. If so, just
8705 // eliminate the trunc/sext pair.
Dan Gohman9545fb02009-07-17 20:47:02 +00008706 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf0f12022008-05-20 21:01:12 +00008707 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008708 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8709 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8710 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008711 unsigned NumSignBits = ComputeNumSignBits(Op);
8712
8713 if (OpBits == DestBits) {
8714 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8715 // bits, it is already ready.
8716 if (NumSignBits > DestBits-MidBits)
8717 return ReplaceInstUsesWith(CI, Op);
8718 } else if (OpBits < DestBits) {
8719 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8720 // bits, just sext from i32.
8721 if (NumSignBits > OpBits-MidBits)
8722 return new SExtInst(Op, CI.getType(), "tmp");
8723 } else {
8724 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8725 // bits, just truncate to i32.
8726 if (NumSignBits > OpBits-MidBits)
8727 return new TruncInst(Op, CI.getType(), "tmp");
8728 }
8729 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008730
8731 // If the input is a shl/ashr pair of a same constant, then this is a sign
8732 // extension from a smaller value. If we could trust arbitrary bitwidth
8733 // integers, we could turn this into a truncate to the smaller bit and then
8734 // use a sext for the whole extension. Since we don't, look deeper and check
8735 // for a truncate. If the source and dest are the same type, eliminate the
8736 // trunc and extend and just do shifts. For example, turn:
8737 // %a = trunc i32 %i to i8
8738 // %b = shl i8 %a, 6
8739 // %c = ashr i8 %b, 6
8740 // %d = sext i8 %c to i32
8741 // into:
8742 // %a = shl i32 %i, 30
8743 // %d = ashr i32 %a, 30
8744 Value *A = 0;
8745 ConstantInt *BA = 0, *CA = 0;
8746 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersona21eb582009-07-10 17:35:01 +00008747 m_ConstantInt(CA)), *Context) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008748 BA == CA && isa<TruncInst>(A)) {
8749 Value *I = cast<TruncInst>(A)->getOperand(0);
8750 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008751 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8752 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008753 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Anderson24be4c12009-07-03 00:17:18 +00008754 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner8a2d0592008-08-06 07:35:52 +00008755 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8756 CI.getName()), CI);
8757 return BinaryOperator::CreateAShr(I, ShAmtV);
8758 }
8759 }
8760
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008761 return 0;
8762}
8763
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008764/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8765/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008766static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008767 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008768 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008769 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008770 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8771 if (!losesInfo)
Owen Anderson24be4c12009-07-03 00:17:18 +00008772 return Context->getConstantFP(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008773 return 0;
8774}
8775
8776/// LookThroughFPExtensions - If this is an fp extension instruction, look
8777/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008778static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008779 if (Instruction *I = dyn_cast<Instruction>(V))
8780 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008781 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008782
8783 // If this value is a constant, return the constant in the smallest FP type
8784 // that can accurately represent it. This allows us to turn
8785 // (float)((double)X+2.0) into x+2.0f.
8786 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8787 if (CFP->getType() == Type::PPC_FP128Ty)
8788 return V; // No constant folding of this.
8789 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008790 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008791 return V;
8792 if (CFP->getType() == Type::DoubleTy)
8793 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008794 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008795 return V;
8796 // Don't try to shrink to various long double types.
8797 }
8798
8799 return V;
8800}
8801
8802Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8803 if (Instruction *I = commonCastTransforms(CI))
8804 return I;
8805
Dan Gohman7ce405e2009-06-04 22:49:04 +00008806 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008807 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008808 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008809 // many builtins (sqrt, etc).
8810 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8811 if (OpI && OpI->hasOneUse()) {
8812 switch (OpI->getOpcode()) {
8813 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008814 case Instruction::FAdd:
8815 case Instruction::FSub:
8816 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008817 case Instruction::FDiv:
8818 case Instruction::FRem:
8819 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008820 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8821 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008822 if (LHSTrunc->getType() != SrcTy &&
8823 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008824 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008825 // If the source types were both smaller than the destination type of
8826 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008827 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8828 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008829 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8830 CI.getType(), CI);
8831 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8832 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008833 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008834 }
8835 }
8836 break;
8837 }
8838 }
8839 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008840}
8841
8842Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8843 return commonCastTransforms(CI);
8844}
8845
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008846Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008847 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8848 if (OpI == 0)
8849 return commonCastTransforms(FI);
8850
8851 // fptoui(uitofp(X)) --> X
8852 // fptoui(sitofp(X)) --> X
8853 // This is safe if the intermediate type has enough bits in its mantissa to
8854 // accurately represent all values of X. For example, do not do this with
8855 // i64->float->i64. This is also safe for sitofp case, because any negative
8856 // 'X' value would cause an undefined result for the fptoui.
8857 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8858 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008859 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008860 OpI->getType()->getFPMantissaWidth())
8861 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008862
8863 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008864}
8865
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008866Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008867 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8868 if (OpI == 0)
8869 return commonCastTransforms(FI);
8870
8871 // fptosi(sitofp(X)) --> X
8872 // fptosi(uitofp(X)) --> X
8873 // This is safe if the intermediate type has enough bits in its mantissa to
8874 // accurately represent all values of X. For example, do not do this with
8875 // i64->float->i64. This is also safe for sitofp case, because any negative
8876 // 'X' value would cause an undefined result for the fptoui.
8877 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8878 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008879 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008880 OpI->getType()->getFPMantissaWidth())
8881 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008882
8883 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008884}
8885
8886Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8887 return commonCastTransforms(CI);
8888}
8889
8890Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8891 return commonCastTransforms(CI);
8892}
8893
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008894Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8895 // If the destination integer type is smaller than the intptr_t type for
8896 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8897 // trunc to be exposed to other transforms. Don't do this for extending
8898 // ptrtoint's, because we don't know if the target sign or zero extends its
8899 // pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008900 if (TD &&
8901 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008902 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8903 TD->getIntPtrType(),
8904 "tmp"), CI);
8905 return new TruncInst(P, CI.getType());
8906 }
8907
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008908 return commonPointerCastTransforms(CI);
8909}
8910
Chris Lattner7c1626482008-01-08 07:23:51 +00008911Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008912 // If the source integer type is larger than the intptr_t type for
8913 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8914 // allows the trunc to be exposed to other transforms. Don't do this for
8915 // extending inttoptr's, because we don't know if the target sign or zero
8916 // extends to pointers.
Dan Gohmana80e2712009-07-21 23:21:54 +00008917 if (TD &&
8918 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008919 TD->getPointerSizeInBits()) {
8920 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8921 TD->getIntPtrType(),
8922 "tmp"), CI);
8923 return new IntToPtrInst(P, CI.getType());
8924 }
8925
Chris Lattner7c1626482008-01-08 07:23:51 +00008926 if (Instruction *I = commonCastTransforms(CI))
8927 return I;
Chris Lattner7c1626482008-01-08 07:23:51 +00008928
Chris Lattner7c1626482008-01-08 07:23:51 +00008929 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008930}
8931
8932Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8933 // If the operands are integer typed then apply the integer transforms,
8934 // otherwise just apply the common ones.
8935 Value *Src = CI.getOperand(0);
8936 const Type *SrcTy = Src->getType();
8937 const Type *DestTy = CI.getType();
8938
Eli Friedman5013d3f2009-07-13 20:53:00 +00008939 if (isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008940 if (Instruction *I = commonPointerCastTransforms(CI))
8941 return I;
8942 } else {
8943 if (Instruction *Result = commonCastTransforms(CI))
8944 return Result;
8945 }
8946
8947
8948 // Get rid of casts from one type to the same type. These are useless and can
8949 // be replaced by the operand.
8950 if (DestTy == Src->getType())
8951 return ReplaceInstUsesWith(CI, Src);
8952
8953 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8954 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8955 const Type *DstElTy = DstPTy->getElementType();
8956 const Type *SrcElTy = SrcPTy->getElementType();
8957
Nate Begemandf5b3612008-03-31 00:22:16 +00008958 // If the address spaces don't match, don't eliminate the bitcast, which is
8959 // required for changing types.
8960 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8961 return 0;
8962
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008963 // If we are casting a malloc or alloca to a pointer to a type of the same
8964 // size, rewrite the allocation instruction to allocate the "right" type.
8965 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8966 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8967 return V;
8968
8969 // If the source and destination are pointers, and this cast is equivalent
8970 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8971 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson24be4c12009-07-03 00:17:18 +00008972 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008973 unsigned NumZeros = 0;
8974 while (SrcElTy != DstElTy &&
8975 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8976 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8977 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8978 ++NumZeros;
8979 }
8980
8981 // If we found a path from the src to dest, create the getelementptr now.
8982 if (SrcElTy == DstElTy) {
8983 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008984 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8985 ((Instruction*) NULL));
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);
8994 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8995 Context->getNullValue(Type::Int32Ty));
8996 }
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 =
9005 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
9006 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 Anderson24be4c12009-07-03 00:17:18 +00009085 return Context->getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009086 case Instruction::And:
Owen Anderson24be4c12009-07-03 00:17:18 +00009087 return Context->getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009088 case Instruction::Mul:
Owen Anderson24be4c12009-07-03 00:17:18 +00009089 return Context->getConstantInt(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),
9109 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 Anderson24be4c12009-07-03 00:17:18 +00009322 Value *Sh = Context->getConstantInt(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,
9325 In->getName()+".lobit"),
9326 *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 Anderson24be4c12009-07-03 00:17:18 +00009547 NegVal = Context->getConstantExprNeg(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 Andersonf9f99362009-07-09 18:36:20 +00009674 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9675 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 =
9696 Context->getPointerTypeUnqual(Context->getIntegerType(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 Anderson24be4c12009-07-03 00:17:18 +00009725 NewPtrTy = Context->getPointerTypeUnqual(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 Anderson24be4c12009-07-03 00:17:18 +00009742 MI->setOperand(3, Context->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 Andersonf9f99362009-07-09 18:36:20 +00009749 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9750 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 Anderson24be4c12009-07-03 00:17:18 +00009767 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009768
9769 Value *Dest = MI->getDest();
Owen Anderson24be4c12009-07-03 00:17:18 +00009770 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(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 Anderson24be4c12009-07-03 00:17:18 +00009777 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9778 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 Anderson24be4c12009-07-03 00:17:18 +00009781 MI->setLength(Context->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 Anderson24be4c12009-07-03 00:17:18 +00009874 Context->getPointerTypeUnqual(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 Anderson24be4c12009-07-03 00:17:18 +00009884 Context->getPointerTypeUnqual(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 Anderson24be4c12009-07-03 00:17:18 +00009895 Context->getPointerTypeUnqual(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 Anderson24be4c12009-07-03 00:17:18 +00009935 Value *Result = Context->getUndef(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 =
Owen Anderson9f5b2aa2009-07-14 23:09:55 +00009949 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9950 Context->getConstantInt(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 Anderson9f5b2aa2009-07-14 23:09:55 +00009957 Context->getConstantInt(Type::Int32Ty, i, false),
9958 "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 Anderson71f286c62009-07-21 18:03:38 +000010060 new StoreInst(Context->getTrue(),
Owen Anderson24be4c12009-07-03 00:17:18 +000010061 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10062 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010063 if (!OldCall->use_empty())
Owen Anderson24be4c12009-07-03 00:17:18 +000010064 OldCall->replaceAllUsesWith(Context->getUndef(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 Anderson71f286c62009-07-21 18:03:38 +000010074 new StoreInst(Context->getTrue(),
Owen Anderson24be4c12009-07-03 00:17:18 +000010075 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010076 CS.getInstruction());
10077
10078 if (!CS.getInstruction()->use_empty())
10079 CS.getInstruction()->
Owen Anderson24be4c12009-07-03 00:17:18 +000010080 replaceAllUsesWith(Context->getUndef(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 Anderson71f286c62009-07-21 18:03:38 +000010085 Context->getTrue(), 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 Anderson24be4c12009-07-03 00:17:18 +000010258 Args.push_back(Context->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()) {
10263 cerr << "WARNING: While resolving call to function '"
10264 << Callee->getName() << "' arguments were dropped!\n";
10265 } 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
Devang Pateld222f862008-09-25 21:00:45 +000010293 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010294
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010295 Instruction *NC;
10296 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010297 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010298 Args.begin(), Args.end(),
10299 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010300 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010301 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010302 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010303 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10304 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010305 CallInst *CI = cast<CallInst>(Caller);
10306 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010307 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010308 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010309 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010310 }
10311
10312 // Insert a cast of the return type as necessary.
10313 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010314 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010315 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010316 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010317 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010318 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010319
10320 // If this is an invoke instruction, we should insert it after the first
10321 // non-phi, instruction in the normal successor block.
10322 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010323 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010324 InsertNewInstBefore(NC, *I);
10325 } else {
10326 // Otherwise, it's a call, just insert cast right after the call instr
10327 InsertNewInstBefore(NC, *Caller);
10328 }
10329 AddUsersToWorkList(*Caller);
10330 } else {
Owen Anderson24be4c12009-07-03 00:17:18 +000010331 NV = Context->getUndef(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010332 }
10333 }
10334
10335 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10336 Caller->replaceAllUsesWith(NV);
10337 Caller->eraseFromParent();
10338 RemoveFromWorkList(Caller);
10339 return true;
10340}
10341
Duncan Sands74833f22007-09-17 10:26:40 +000010342// transformCallThroughTrampoline - Turn a call to a function created by the
10343// init_trampoline intrinsic into a direct call to the underlying function.
10344//
10345Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10346 Value *Callee = CS.getCalledValue();
10347 const PointerType *PTy = cast<PointerType>(Callee->getType());
10348 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010349 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010350
10351 // If the call already has the 'nest' attribute somewhere then give up -
10352 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010353 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010354 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010355
10356 IntrinsicInst *Tramp =
10357 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10358
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010359 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010360 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10361 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10362
Devang Pateld222f862008-09-25 21:00:45 +000010363 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010364 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010365 unsigned NestIdx = 1;
10366 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010367 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010368
10369 // Look for a parameter marked with the 'nest' attribute.
10370 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10371 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010372 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010373 // Record the parameter type and any other attributes.
10374 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010375 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010376 break;
10377 }
10378
10379 if (NestTy) {
10380 Instruction *Caller = CS.getInstruction();
10381 std::vector<Value*> NewArgs;
10382 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10383
Devang Pateld222f862008-09-25 21:00:45 +000010384 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010385 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010386
Duncan Sands74833f22007-09-17 10:26:40 +000010387 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010388 // mean appending it. Likewise for attributes.
10389
Devang Patelf2a4a922008-09-26 22:53:05 +000010390 // Add any result attributes.
10391 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010392 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010393
Duncan Sands74833f22007-09-17 10:26:40 +000010394 {
10395 unsigned Idx = 1;
10396 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10397 do {
10398 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010399 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010400 Value *NestVal = Tramp->getOperand(3);
10401 if (NestVal->getType() != NestTy)
10402 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10403 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010404 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010405 }
10406
10407 if (I == E)
10408 break;
10409
Duncan Sands48b81112008-01-14 19:52:09 +000010410 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010411 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010412 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010413 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010414 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010415
10416 ++Idx, ++I;
10417 } while (1);
10418 }
10419
Devang Patelf2a4a922008-09-26 22:53:05 +000010420 // Add any function attributes.
10421 if (Attributes Attr = Attrs.getFnAttributes())
10422 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10423
Duncan Sands74833f22007-09-17 10:26:40 +000010424 // The trampoline may have been bitcast to a bogus type (FTy).
10425 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010426 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010427
Duncan Sands74833f22007-09-17 10:26:40 +000010428 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010429 NewTypes.reserve(FTy->getNumParams()+1);
10430
Duncan Sands74833f22007-09-17 10:26:40 +000010431 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010432 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010433 {
10434 unsigned Idx = 1;
10435 FunctionType::param_iterator I = FTy->param_begin(),
10436 E = FTy->param_end();
10437
10438 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010439 if (Idx == NestIdx)
10440 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010441 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010442
10443 if (I == E)
10444 break;
10445
Duncan Sands48b81112008-01-14 19:52:09 +000010446 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010447 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010448
10449 ++Idx, ++I;
10450 } while (1);
10451 }
10452
10453 // Replace the trampoline call with a direct call. Let the generic
10454 // code sort out any function type mismatches.
10455 FunctionType *NewFTy =
Owen Anderson24be4c12009-07-03 00:17:18 +000010456 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10457 FTy->isVarArg());
10458 Constant *NewCallee =
10459 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10460 NestF : Context->getConstantExprBitCast(NestF,
10461 Context->getPointerTypeUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +000010462 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010463
10464 Instruction *NewCaller;
10465 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010466 NewCaller = InvokeInst::Create(NewCallee,
10467 II->getNormalDest(), II->getUnwindDest(),
10468 NewArgs.begin(), NewArgs.end(),
10469 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010470 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010471 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010472 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010473 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10474 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010475 if (cast<CallInst>(Caller)->isTailCall())
10476 cast<CallInst>(NewCaller)->setTailCall();
10477 cast<CallInst>(NewCaller)->
10478 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010479 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010480 }
10481 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10482 Caller->replaceAllUsesWith(NewCaller);
10483 Caller->eraseFromParent();
10484 RemoveFromWorkList(Caller);
10485 return 0;
10486 }
10487 }
10488
10489 // Replace the trampoline call with a direct call. Since there is no 'nest'
10490 // parameter, there is no need to adjust the argument list. Let the generic
10491 // code sort out any function type mismatches.
10492 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010493 NestF->getType() == PTy ? NestF :
10494 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010495 CS.setCalledFunction(NewCallee);
10496 return CS.getInstruction();
10497}
10498
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010499/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10500/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10501/// and a single binop.
10502Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10503 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010504 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010505 unsigned Opc = FirstInst->getOpcode();
10506 Value *LHSVal = FirstInst->getOperand(0);
10507 Value *RHSVal = FirstInst->getOperand(1);
10508
10509 const Type *LHSType = LHSVal->getType();
10510 const Type *RHSType = RHSVal->getType();
10511
10512 // Scan to see if all operands are the same opcode, all have one use, and all
10513 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010514 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010515 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10516 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10517 // Verify type of the LHS matches so we don't fold cmp's of different
10518 // types or GEP's with different index types.
10519 I->getOperand(0)->getType() != LHSType ||
10520 I->getOperand(1)->getType() != RHSType)
10521 return 0;
10522
10523 // If they are CmpInst instructions, check their predicates
10524 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10525 if (cast<CmpInst>(I)->getPredicate() !=
10526 cast<CmpInst>(FirstInst)->getPredicate())
10527 return 0;
10528
10529 // Keep track of which operand needs a phi node.
10530 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10531 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10532 }
10533
Chris Lattner30078012008-12-01 03:42:51 +000010534 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010535
10536 Value *InLHS = FirstInst->getOperand(0);
10537 Value *InRHS = FirstInst->getOperand(1);
10538 PHINode *NewLHS = 0, *NewRHS = 0;
10539 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010540 NewLHS = PHINode::Create(LHSType,
10541 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010542 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10543 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10544 InsertNewInstBefore(NewLHS, PN);
10545 LHSVal = NewLHS;
10546 }
10547
10548 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010549 NewRHS = PHINode::Create(RHSType,
10550 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010551 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10552 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10553 InsertNewInstBefore(NewRHS, PN);
10554 RHSVal = NewRHS;
10555 }
10556
10557 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010558 if (NewLHS || NewRHS) {
10559 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10560 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10561 if (NewLHS) {
10562 Value *NewInLHS = InInst->getOperand(0);
10563 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10564 }
10565 if (NewRHS) {
10566 Value *NewInRHS = InInst->getOperand(1);
10567 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10568 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010569 }
10570 }
10571
10572 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010573 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010574 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson6601fcd2009-07-09 23:48:35 +000010575 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10576 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010577}
10578
Chris Lattner9e1916e2008-12-01 02:34:36 +000010579Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10580 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10581
10582 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10583 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010584 // This is true if all GEP bases are allocas and if all indices into them are
10585 // constants.
10586 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010587
10588 // Scan to see if all operands are the same opcode, all have one use, and all
10589 // kill their operands (i.e. the operands have one use).
10590 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10591 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10592 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10593 GEP->getNumOperands() != FirstInst->getNumOperands())
10594 return 0;
10595
Chris Lattneradf354b2009-02-21 00:46:50 +000010596 // Keep track of whether or not all GEPs are of alloca pointers.
10597 if (AllBasePointersAreAllocas &&
10598 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10599 !GEP->hasAllConstantIndices()))
10600 AllBasePointersAreAllocas = false;
10601
Chris Lattner9e1916e2008-12-01 02:34:36 +000010602 // Compare the operand lists.
10603 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10604 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10605 continue;
10606
10607 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10608 // if one of the PHIs has a constant for the index. The index may be
10609 // substantially cheaper to compute for the constants, so making it a
10610 // variable index could pessimize the path. This also handles the case
10611 // for struct indices, which must always be constant.
10612 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10613 isa<ConstantInt>(GEP->getOperand(op)))
10614 return 0;
10615
10616 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10617 return 0;
10618 FixedOperands[op] = 0; // Needs a PHI.
10619 }
10620 }
10621
Chris Lattneradf354b2009-02-21 00:46:50 +000010622 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010623 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010624 // offset calculation, but all the predecessors will have to materialize the
10625 // stack address into a register anyway. We'd actually rather *clone* the
10626 // load up into the predecessors so that we have a load of a gep of an alloca,
10627 // which can usually all be folded into the load.
10628 if (AllBasePointersAreAllocas)
10629 return 0;
10630
Chris Lattner9e1916e2008-12-01 02:34:36 +000010631 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10632 // that is variable.
10633 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10634
10635 bool HasAnyPHIs = false;
10636 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10637 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10638 Value *FirstOp = FirstInst->getOperand(i);
10639 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10640 FirstOp->getName()+".pn");
10641 InsertNewInstBefore(NewPN, PN);
10642
10643 NewPN->reserveOperandSpace(e);
10644 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10645 OperandPhis[i] = NewPN;
10646 FixedOperands[i] = NewPN;
10647 HasAnyPHIs = true;
10648 }
10649
10650
10651 // Add all operands to the new PHIs.
10652 if (HasAnyPHIs) {
10653 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10654 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10655 BasicBlock *InBB = PN.getIncomingBlock(i);
10656
10657 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10658 if (PHINode *OpPhi = OperandPhis[op])
10659 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10660 }
10661 }
10662
10663 Value *Base = FixedOperands[0];
10664 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10665 FixedOperands.end());
10666}
10667
10668
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010669/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10670/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010671/// obvious the value of the load is not changed from the point of the load to
10672/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010673///
10674/// Finally, it is safe, but not profitable, to sink a load targetting a
10675/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10676/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010677static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010678 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10679
10680 for (++BBI; BBI != E; ++BBI)
10681 if (BBI->mayWriteToMemory())
10682 return false;
10683
10684 // Check for non-address taken alloca. If not address-taken already, it isn't
10685 // profitable to do this xform.
10686 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10687 bool isAddressTaken = false;
10688 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10689 UI != E; ++UI) {
10690 if (isa<LoadInst>(UI)) continue;
10691 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10692 // If storing TO the alloca, then the address isn't taken.
10693 if (SI->getOperand(1) == AI) continue;
10694 }
10695 isAddressTaken = true;
10696 break;
10697 }
10698
Chris Lattneradf354b2009-02-21 00:46:50 +000010699 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010700 return false;
10701 }
10702
Chris Lattneradf354b2009-02-21 00:46:50 +000010703 // If this load is a load from a GEP with a constant offset from an alloca,
10704 // then we don't want to sink it. In its present form, it will be
10705 // load [constant stack offset]. Sinking it will cause us to have to
10706 // materialize the stack addresses in each predecessor in a register only to
10707 // do a shared load from register in the successor.
10708 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10709 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10710 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10711 return false;
10712
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010713 return true;
10714}
10715
10716
10717// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10718// operator and they all are only used by the PHI, PHI together their
10719// inputs, and do the operation once, to the result of the PHI.
10720Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10721 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10722
10723 // Scan the instruction, looking for input operations that can be folded away.
10724 // If all input operands to the phi are the same instruction (e.g. a cast from
10725 // the same type or "+42") we can pull the operation through the PHI, reducing
10726 // code size and simplifying code.
10727 Constant *ConstantOp = 0;
10728 const Type *CastSrcTy = 0;
10729 bool isVolatile = false;
10730 if (isa<CastInst>(FirstInst)) {
10731 CastSrcTy = FirstInst->getOperand(0)->getType();
10732 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10733 // Can fold binop, compare or shift here if the RHS is a constant,
10734 // otherwise call FoldPHIArgBinOpIntoPHI.
10735 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10736 if (ConstantOp == 0)
10737 return FoldPHIArgBinOpIntoPHI(PN);
10738 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10739 isVolatile = LI->isVolatile();
10740 // We can't sink the load if the loaded value could be modified between the
10741 // load and the PHI.
10742 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010743 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010744 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010745
10746 // If the PHI is of volatile loads and the load block has multiple
10747 // successors, sinking it would remove a load of the volatile value from
10748 // the path through the other successor.
10749 if (isVolatile &&
10750 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10751 return 0;
10752
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010753 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010754 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010755 } else {
10756 return 0; // Cannot fold this operation.
10757 }
10758
10759 // Check to see if all arguments are the same operation.
10760 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10761 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10762 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10763 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10764 return 0;
10765 if (CastSrcTy) {
10766 if (I->getOperand(0)->getType() != CastSrcTy)
10767 return 0; // Cast operation must match.
10768 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10769 // We can't sink the load if the loaded value could be modified between
10770 // the load and the PHI.
10771 if (LI->isVolatile() != isVolatile ||
10772 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010773 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010774 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010775
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010776 // If the PHI is of volatile loads and the load block has multiple
10777 // successors, sinking it would remove a load of the volatile value from
10778 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010779 if (isVolatile &&
10780 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10781 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010782
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010783 } else if (I->getOperand(1) != ConstantOp) {
10784 return 0;
10785 }
10786 }
10787
10788 // Okay, they are all the same operation. Create a new PHI node of the
10789 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010790 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10791 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010792 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10793
10794 Value *InVal = FirstInst->getOperand(0);
10795 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10796
10797 // Add all operands to the new PHI.
10798 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10799 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10800 if (NewInVal != InVal)
10801 InVal = 0;
10802 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10803 }
10804
10805 Value *PhiVal;
10806 if (InVal) {
10807 // The new PHI unions all of the same values together. This is really
10808 // common, so we handle it intelligently here for compile-time speed.
10809 PhiVal = InVal;
10810 delete NewPN;
10811 } else {
10812 InsertNewInstBefore(NewPN, PN);
10813 PhiVal = NewPN;
10814 }
10815
10816 // Insert and return the new operation.
10817 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010818 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010819 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010820 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010821 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson6601fcd2009-07-09 23:48:35 +000010822 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010823 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010824 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10825
10826 // If this was a volatile load that we are merging, make sure to loop through
10827 // and mark all the input loads as non-volatile. If we don't do this, we will
10828 // insert a new volatile load and the old ones will not be deletable.
10829 if (isVolatile)
10830 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10831 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10832
10833 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010834}
10835
10836/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10837/// that is dead.
10838static bool DeadPHICycle(PHINode *PN,
10839 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10840 if (PN->use_empty()) return true;
10841 if (!PN->hasOneUse()) return false;
10842
10843 // Remember this node, and if we find the cycle, return.
10844 if (!PotentiallyDeadPHIs.insert(PN))
10845 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010846
10847 // Don't scan crazily complex things.
10848 if (PotentiallyDeadPHIs.size() == 16)
10849 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010850
10851 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10852 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10853
10854 return false;
10855}
10856
Chris Lattner27b695d2007-11-06 21:52:06 +000010857/// PHIsEqualValue - Return true if this phi node is always equal to
10858/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10859/// z = some value; x = phi (y, z); y = phi (x, z)
10860static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10861 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10862 // See if we already saw this PHI node.
10863 if (!ValueEqualPHIs.insert(PN))
10864 return true;
10865
10866 // Don't scan crazily complex things.
10867 if (ValueEqualPHIs.size() == 16)
10868 return false;
10869
10870 // Scan the operands to see if they are either phi nodes or are equal to
10871 // the value.
10872 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10873 Value *Op = PN->getIncomingValue(i);
10874 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10875 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10876 return false;
10877 } else if (Op != NonPhiInVal)
10878 return false;
10879 }
10880
10881 return true;
10882}
10883
10884
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010885// PHINode simplification
10886//
10887Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10888 // If LCSSA is around, don't mess with Phi nodes
10889 if (MustPreserveLCSSA) return 0;
10890
10891 if (Value *V = PN.hasConstantValue())
10892 return ReplaceInstUsesWith(PN, V);
10893
10894 // If all PHI operands are the same operation, pull them through the PHI,
10895 // reducing code size.
10896 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010897 isa<Instruction>(PN.getIncomingValue(1)) &&
10898 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10899 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10900 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10901 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010902 PN.getIncomingValue(0)->hasOneUse())
10903 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10904 return Result;
10905
10906 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10907 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10908 // PHI)... break the cycle.
10909 if (PN.hasOneUse()) {
10910 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10911 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10912 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10913 PotentiallyDeadPHIs.insert(&PN);
10914 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson24be4c12009-07-03 00:17:18 +000010915 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010916 }
10917
10918 // If this phi has a single use, and if that use just computes a value for
10919 // the next iteration of a loop, delete the phi. This occurs with unused
10920 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10921 // common case here is good because the only other things that catch this
10922 // are induction variable analysis (sometimes) and ADCE, which is only run
10923 // late.
10924 if (PHIUser->hasOneUse() &&
10925 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10926 PHIUser->use_back() == &PN) {
Owen Anderson24be4c12009-07-03 00:17:18 +000010927 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010928 }
10929 }
10930
Chris Lattner27b695d2007-11-06 21:52:06 +000010931 // We sometimes end up with phi cycles that non-obviously end up being the
10932 // same value, for example:
10933 // z = some value; x = phi (y, z); y = phi (x, z)
10934 // where the phi nodes don't necessarily need to be in the same block. Do a
10935 // quick check to see if the PHI node only contains a single non-phi value, if
10936 // so, scan to see if the phi cycle is actually equal to that value.
10937 {
10938 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10939 // Scan for the first non-phi operand.
10940 while (InValNo != NumOperandVals &&
10941 isa<PHINode>(PN.getIncomingValue(InValNo)))
10942 ++InValNo;
10943
10944 if (InValNo != NumOperandVals) {
10945 Value *NonPhiInVal = PN.getOperand(InValNo);
10946
10947 // Scan the rest of the operands to see if there are any conflicts, if so
10948 // there is no need to recursively scan other phis.
10949 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10950 Value *OpVal = PN.getIncomingValue(InValNo);
10951 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10952 break;
10953 }
10954
10955 // If we scanned over all operands, then we have one unique value plus
10956 // phi values. Scan PHI nodes to see if they all merge in each other or
10957 // the value.
10958 if (InValNo == NumOperandVals) {
10959 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10960 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10961 return ReplaceInstUsesWith(PN, NonPhiInVal);
10962 }
10963 }
10964 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010965 return 0;
10966}
10967
10968static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10969 Instruction *InsertPoint,
10970 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000010971 unsigned PtrSize = DTy->getScalarSizeInBits();
10972 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010973 // We must cast correctly to the pointer type. Ensure that we
10974 // sign extend the integer value if it is smaller as this is
10975 // used for address computation.
10976 Instruction::CastOps opcode =
10977 (VTySize < PtrSize ? Instruction::SExt :
10978 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10979 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10980}
10981
10982
10983Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10984 Value *PtrOp = GEP.getOperand(0);
10985 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10986 // If so, eliminate the noop.
10987 if (GEP.getNumOperands() == 1)
10988 return ReplaceInstUsesWith(GEP, PtrOp);
10989
10990 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson24be4c12009-07-03 00:17:18 +000010991 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010992
10993 bool HasZeroPointerIndex = false;
10994 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10995 HasZeroPointerIndex = C->isNullValue();
10996
10997 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10998 return ReplaceInstUsesWith(GEP, PtrOp);
10999
11000 // Eliminate unneeded casts for indices.
11001 bool MadeChange = false;
11002
11003 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011004 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11005 i != e; ++i, ++GTI) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011006 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000011007 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011008 if (CI->getOpcode() == Instruction::ZExt ||
11009 CI->getOpcode() == Instruction::SExt) {
11010 const Type *SrcTy = CI->getOperand(0)->getType();
11011 // We can eliminate a cast from i32 to i64 iff the target
11012 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000011013 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011014 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000011015 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011016 }
11017 }
11018 }
11019 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000011020 // to what we need. If narrower, sign-extend it to what we need.
11021 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011022 // insert it. This explicit cast can make subsequent optimizations more
11023 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000011024 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011025 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011026 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011027 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011028 MadeChange = true;
11029 } else {
11030 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11031 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011032 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011033 MadeChange = true;
11034 }
Dan Gohman5d639ed2008-09-11 23:06:38 +000011035 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11036 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011037 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman5d639ed2008-09-11 23:06:38 +000011038 MadeChange = true;
11039 } else {
11040 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11041 GEP);
11042 *i = Op;
11043 MadeChange = true;
11044 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011045 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011046 }
11047 }
11048 if (MadeChange) return &GEP;
11049
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011050 // Combine Indices - If the source pointer to this getelementptr instruction
11051 // is a getelementptr instruction, combine the indices of the two
11052 // getelementptr instructions into a single instruction.
11053 //
11054 SmallVector<Value*, 8> SrcGEPOperands;
11055 if (User *Src = dyn_castGetElementPtr(PtrOp))
11056 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11057
11058 if (!SrcGEPOperands.empty()) {
11059 // Note that if our source is a gep chain itself that we wait for that
11060 // chain to be resolved before we perform this transformation. This
11061 // avoids us creating a TON of code in some cases.
11062 //
11063 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11064 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11065 return 0; // Wait until our source is folded to completion.
11066
11067 SmallVector<Value*, 8> Indices;
11068
11069 // Find out whether the last index in the source GEP is a sequential idx.
11070 bool EndsWithSequential = false;
11071 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11072 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11073 EndsWithSequential = !isa<StructType>(*I);
11074
11075 // Can we combine the two pointer arithmetics offsets?
11076 if (EndsWithSequential) {
11077 // Replace: gep (gep %P, long B), long A, ...
11078 // With: T = long A+B; gep %P, T, ...
11079 //
11080 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011081 if (SO1 == Context->getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011082 Sum = GO1;
Owen Anderson24be4c12009-07-03 00:17:18 +000011083 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011084 Sum = SO1;
11085 } else {
11086 // If they aren't the same type, convert both to an integer of the
11087 // target's pointer size.
11088 if (SO1->getType() != GO1->getType()) {
11089 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011090 SO1 =
11091 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011092 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011093 GO1 =
11094 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmana80e2712009-07-21 23:21:54 +000011095 } else if (TD) {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011096 unsigned PS = TD->getPointerSizeInBits();
11097 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011098 // Convert GO1 to SO1's type.
11099 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11100
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011101 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011102 // Convert SO1 to GO1's type.
11103 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11104 } else {
11105 const Type *PT = TD->getIntPtrType();
11106 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11107 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11108 }
11109 }
11110 }
11111 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Anderson24be4c12009-07-03 00:17:18 +000011112 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11113 cast<Constant>(GO1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011114 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011115 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011116 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11117 }
11118 }
11119
11120 // Recycle the GEP we already have if possible.
11121 if (SrcGEPOperands.size() == 2) {
11122 GEP.setOperand(0, SrcGEPOperands[0]);
11123 GEP.setOperand(1, Sum);
11124 return &GEP;
11125 } else {
11126 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11127 SrcGEPOperands.end()-1);
11128 Indices.push_back(Sum);
11129 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11130 }
11131 } else if (isa<Constant>(*GEP.idx_begin()) &&
11132 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11133 SrcGEPOperands.size() != 1) {
11134 // Otherwise we can do the fold if the first index of the GEP is a zero
11135 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11136 SrcGEPOperands.end());
11137 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11138 }
11139
11140 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000011141 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11142 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011143
11144 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11145 // GEP of global variable. If all of the indices for this GEP are
11146 // constants, we can promote this to a constexpr instead of an instruction.
11147
11148 // Scan for nonconstants...
11149 SmallVector<Constant*, 8> Indices;
11150 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11151 for (; I != E && isa<Constant>(*I); ++I)
11152 Indices.push_back(cast<Constant>(*I));
11153
11154 if (I == E) { // If they are all constants...
Owen Anderson24be4c12009-07-03 00:17:18 +000011155 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011156 &Indices[0],Indices.size());
11157
11158 // Replace all uses of the GEP with the new constexpr...
11159 return ReplaceInstUsesWith(GEP, CE);
11160 }
11161 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11162 if (!isa<PointerType>(X->getType())) {
11163 // Not interesting. Source pointer must be a cast from pointer.
11164 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011165 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11166 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011167 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011168 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11169 // into : GEP i8* X, ...
11170 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011171 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011172 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11173 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011174 if (const ArrayType *CATy =
11175 dyn_cast<ArrayType>(CPTy->getElementType())) {
11176 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11177 if (CATy->getElementType() == XTy->getElementType()) {
11178 // -> GEP i8* X, ...
11179 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11180 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11181 GEP.getName());
11182 } else if (const ArrayType *XATy =
11183 dyn_cast<ArrayType>(XTy->getElementType())) {
11184 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011185 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011186 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011187 // At this point, we know that the cast source type is a pointer
11188 // to an array of the same type as the destination pointer
11189 // array. Because the array type is never stepped over (there
11190 // is a leading zero) we can fold the cast into this GEP.
11191 GEP.setOperand(0, X);
11192 return &GEP;
11193 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011194 }
11195 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011196 } else if (GEP.getNumOperands() == 2) {
11197 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011198 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11199 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011200 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11201 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +000011202 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011203 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11204 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011205 Value *Idx[2];
Owen Anderson24be4c12009-07-03 00:17:18 +000011206 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011207 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011208 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000011209 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011210 // V and GEP are both pointer types --> BitCast
11211 return new BitCastInst(V, GEP.getType());
11212 }
11213
11214 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011215 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011216 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011217 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011218
Dan Gohmana80e2712009-07-21 23:21:54 +000011219 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011220 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011221 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011222
11223 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11224 // allow either a mul, shift, or constant here.
11225 Value *NewIdx = 0;
11226 ConstantInt *Scale = 0;
11227 if (ArrayEltSize == 1) {
11228 NewIdx = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011229 Scale =
11230 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011231 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011232 NewIdx = Context->getConstantInt(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011233 Scale = CI;
11234 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11235 if (Inst->getOpcode() == Instruction::Shl &&
11236 isa<ConstantInt>(Inst->getOperand(1))) {
11237 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11238 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Anderson24be4c12009-07-03 00:17:18 +000011239 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011240 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011241 NewIdx = Inst->getOperand(0);
11242 } else if (Inst->getOpcode() == Instruction::Mul &&
11243 isa<ConstantInt>(Inst->getOperand(1))) {
11244 Scale = cast<ConstantInt>(Inst->getOperand(1));
11245 NewIdx = Inst->getOperand(0);
11246 }
11247 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011248
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011249 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011250 // out, perform the transformation. Note, we don't know whether Scale is
11251 // signed or not. We'll use unsigned version of division/modulo
11252 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011253 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011254 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011255 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011256 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011257 if (Scale->getZExtValue() != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011258 Constant *C =
11259 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011260 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011261 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011262 NewIdx = InsertNewInstBefore(Sc, GEP);
11263 }
11264
11265 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011266 Value *Idx[2];
Owen Anderson24be4c12009-07-03 00:17:18 +000011267 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011268 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011269 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011270 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011271 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11272 // The NewGEP must be pointer typed, so must the old one -> BitCast
11273 return new BitCastInst(NewGEP, GEP.getType());
11274 }
11275 }
11276 }
11277 }
Chris Lattner111ea772009-01-09 04:53:57 +000011278
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011279 /// See if we can simplify:
11280 /// X = bitcast A to B*
11281 /// Y = gep X, <...constant indices...>
11282 /// into a gep of the original struct. This is important for SROA and alias
11283 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011284 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +000011285 if (TD &&
11286 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011287 // Determine how much the GEP moves the pointer. We are guaranteed to get
11288 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011289 ConstantInt *OffsetV =
11290 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011291 int64_t Offset = OffsetV->getSExtValue();
11292
11293 // If this GEP instruction doesn't move the pointer, just replace the GEP
11294 // with a bitcast of the real input to the dest type.
11295 if (Offset == 0) {
11296 // If the bitcast is of an allocation, and the allocation will be
11297 // converted to match the type of the cast, don't touch this.
11298 if (isa<AllocationInst>(BCI->getOperand(0))) {
11299 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11300 if (Instruction *I = visitBitCast(*BCI)) {
11301 if (I != BCI) {
11302 I->takeName(BCI);
11303 BCI->getParent()->getInstList().insert(BCI, I);
11304 ReplaceInstUsesWith(*BCI, I);
11305 }
11306 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011307 }
Chris Lattner111ea772009-01-09 04:53:57 +000011308 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011309 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011310 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011311
11312 // Otherwise, if the offset is non-zero, we need to find out if there is a
11313 // field at Offset in 'A's type. If so, we can pull the cast through the
11314 // GEP.
11315 SmallVector<Value*, 8> NewIndices;
11316 const Type *InTy =
11317 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011318 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011319 Instruction *NGEP =
11320 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11321 NewIndices.end());
11322 if (NGEP->getType() == GEP.getType()) return NGEP;
11323 InsertNewInstBefore(NGEP, GEP);
11324 NGEP->takeName(&GEP);
11325 return new BitCastInst(NGEP, GEP.getType());
11326 }
Chris Lattner111ea772009-01-09 04:53:57 +000011327 }
11328 }
11329
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011330 return 0;
11331}
11332
11333Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11334 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011335 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011336 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11337 const Type *NewTy =
Owen Anderson24be4c12009-07-03 00:17:18 +000011338 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011339 AllocationInst *New = 0;
11340
11341 // Create and insert the replacement instruction...
11342 if (isa<MallocInst>(AI))
Owen Anderson140166d2009-07-15 23:53:25 +000011343 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011344 else {
11345 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson140166d2009-07-15 23:53:25 +000011346 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011347 }
11348
11349 InsertNewInstBefore(New, AI);
11350
11351 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011352 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011353 //
11354 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011355 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011356
11357 // Now that I is pointing to the first non-allocation-inst in the block,
11358 // insert our getelementptr instruction...
11359 //
Owen Anderson24be4c12009-07-03 00:17:18 +000011360 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011361 Value *Idx[2];
11362 Idx[0] = NullIdx;
11363 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011364 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11365 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011366
11367 // Now make everything use the getelementptr instead of the original
11368 // allocation.
11369 return ReplaceInstUsesWith(AI, V);
11370 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011371 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011372 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011373 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011374
Dan Gohmana80e2712009-07-21 23:21:54 +000011375 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman28e78f02009-01-13 20:18:38 +000011376 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011377 // Note that we only do this for alloca's, because malloc should allocate
11378 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011379 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Anderson24be4c12009-07-03 00:17:18 +000011380 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011381
11382 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11383 if (AI.getAlignment() == 0)
11384 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11385 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011386
11387 return 0;
11388}
11389
11390Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11391 Value *Op = FI.getOperand(0);
11392
11393 // free undef -> unreachable.
11394 if (isa<UndefValue>(Op)) {
11395 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson71f286c62009-07-21 18:03:38 +000011396 new StoreInst(Context->getTrue(),
Owen Anderson24be4c12009-07-03 00:17:18 +000011397 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011398 return EraseInstFromFunction(FI);
11399 }
11400
11401 // If we have 'free null' delete the instruction. This can happen in stl code
11402 // when lots of inlining happens.
11403 if (isa<ConstantPointerNull>(Op))
11404 return EraseInstFromFunction(FI);
11405
11406 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11407 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11408 FI.setOperand(0, CI->getOperand(0));
11409 return &FI;
11410 }
11411
11412 // Change free (gep X, 0,0,0,0) into free(X)
11413 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11414 if (GEPI->hasAllZeroIndices()) {
11415 AddToWorkList(GEPI);
11416 FI.setOperand(0, GEPI->getOperand(0));
11417 return &FI;
11418 }
11419 }
11420
11421 // Change free(malloc) into nothing, if the malloc has a single use.
11422 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11423 if (MI->hasOneUse()) {
11424 EraseInstFromFunction(FI);
11425 return EraseInstFromFunction(*MI);
11426 }
11427
11428 return 0;
11429}
11430
11431
11432/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011433static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011434 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011435 User *CI = cast<User>(LI.getOperand(0));
11436 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011437 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011438
Nick Lewycky291c5942009-05-08 06:47:37 +000011439 if (TD) {
11440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11441 // Instead of loading constant c string, use corresponding integer value
11442 // directly if string length is small enough.
11443 std::string Str;
11444 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11445 unsigned len = Str.length();
11446 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11447 unsigned numBits = Ty->getPrimitiveSizeInBits();
11448 // Replace LI with immediate integer store.
11449 if ((numBits >> 3) == len + 1) {
11450 APInt StrVal(numBits, 0);
11451 APInt SingleChar(numBits, 0);
11452 if (TD->isLittleEndian()) {
11453 for (signed i = len-1; i >= 0; i--) {
11454 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11455 StrVal = (StrVal << 8) | SingleChar;
11456 }
11457 } else {
11458 for (unsigned i = 0; i < len; i++) {
11459 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11460 StrVal = (StrVal << 8) | SingleChar;
11461 }
11462 // Append NULL at the end.
11463 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011464 StrVal = (StrVal << 8) | SingleChar;
11465 }
Owen Anderson24be4c12009-07-03 00:17:18 +000011466 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011467 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011468 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011469 }
11470 }
11471 }
11472
Mon P Wangbd05ed82009-02-07 22:19:29 +000011473 const PointerType *DestTy = cast<PointerType>(CI->getType());
11474 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011475 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011476
11477 // If the address spaces don't match, don't eliminate the cast.
11478 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11479 return 0;
11480
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011481 const Type *SrcPTy = SrcTy->getElementType();
11482
11483 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11484 isa<VectorType>(DestPTy)) {
11485 // If the source is an array, the code below will not succeed. Check to
11486 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11487 // constants.
11488 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11489 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11490 if (ASrcTy->getNumElements() != 0) {
11491 Value *Idxs[2];
Owen Anderson24be4c12009-07-03 00:17:18 +000011492 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11493 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011494 SrcTy = cast<PointerType>(CastOp->getType());
11495 SrcPTy = SrcTy->getElementType();
11496 }
11497
Dan Gohmana80e2712009-07-21 23:21:54 +000011498 if (IC.getTargetData() &&
11499 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011500 isa<VectorType>(SrcPTy)) &&
11501 // Do not allow turning this into a load of an integer, which is then
11502 // casted to a pointer, this pessimizes pointer analysis a lot.
11503 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmana80e2712009-07-21 23:21:54 +000011504 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11505 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011506
11507 // Okay, we are casting from one integer or pointer type to another of
11508 // the same size. Instead of casting the pointer before the load, cast
11509 // the result of the loaded value.
11510 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11511 CI->getName(),
11512 LI.isVolatile()),LI);
11513 // Now cast the result of the load.
11514 return new BitCastInst(NewLoad, LI.getType());
11515 }
11516 }
11517 }
11518 return 0;
11519}
11520
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011521Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11522 Value *Op = LI.getOperand(0);
11523
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011524 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011525 if (TD) {
11526 unsigned KnownAlign =
11527 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11528 if (KnownAlign >
11529 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11530 LI.getAlignment()))
11531 LI.setAlignment(KnownAlign);
11532 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011533
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011534 // load (cast X) --> cast (load X) iff safe
11535 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011536 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011537 return Res;
11538
11539 // None of the following transforms are legal for volatile loads.
11540 if (LI.isVolatile()) return 0;
11541
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011542 // Do really simple store-to-load forwarding and load CSE, to catch cases
11543 // where there are several consequtive memory accesses to the same location,
11544 // separated by a few arithmetic operations.
11545 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011546 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11547 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011548
Christopher Lamb2c175392007-12-29 07:56:53 +000011549 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11550 const Value *GEPI0 = GEPI->getOperand(0);
11551 // TODO: Consider a target hook for valid address spaces for this xform.
11552 if (isa<ConstantPointerNull>(GEPI0) &&
11553 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011554 // Insert a new store to null instruction before the load to indicate
11555 // that this code is not reachable. We do this instead of inserting
11556 // an unreachable instruction directly because we cannot modify the
11557 // CFG.
Owen Anderson24be4c12009-07-03 00:17:18 +000011558 new StoreInst(Context->getUndef(LI.getType()),
11559 Context->getNullValue(Op->getType()), &LI);
11560 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011561 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011562 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011563
11564 if (Constant *C = dyn_cast<Constant>(Op)) {
11565 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011566 // TODO: Consider a target hook for valid address spaces for this xform.
11567 if (isa<UndefValue>(C) || (C->isNullValue() &&
11568 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011569 // Insert a new store to null instruction before the load to indicate that
11570 // this code is not reachable. We do this instead of inserting an
11571 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson24be4c12009-07-03 00:17:18 +000011572 new StoreInst(Context->getUndef(LI.getType()),
11573 Context->getNullValue(Op->getType()), &LI);
11574 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011575 }
11576
11577 // Instcombine load (constant global) into the value loaded.
11578 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011579 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011580 return ReplaceInstUsesWith(LI, GV->getInitializer());
11581
11582 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011583 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011584 if (CE->getOpcode() == Instruction::GetElementPtr) {
11585 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011586 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011587 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011588 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Anderson175b6542009-07-22 00:24:57 +000011589 *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011590 return ReplaceInstUsesWith(LI, V);
11591 if (CE->getOperand(0)->isNullValue()) {
11592 // Insert a new store to null instruction before the load to indicate
11593 // that this code is not reachable. We do this instead of inserting
11594 // an unreachable instruction directly because we cannot modify the
11595 // CFG.
Owen Anderson24be4c12009-07-03 00:17:18 +000011596 new StoreInst(Context->getUndef(LI.getType()),
11597 Context->getNullValue(Op->getType()), &LI);
11598 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011599 }
11600
11601 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011602 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011603 return Res;
11604 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011605 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011606 }
Chris Lattner0270a112007-08-11 18:48:48 +000011607
11608 // If this load comes from anywhere in a constant global, and if the global
11609 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011610 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011611 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011612 if (GV->getInitializer()->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +000011613 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011614 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson24be4c12009-07-03 00:17:18 +000011615 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011616 }
11617 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011618
11619 if (Op->hasOneUse()) {
11620 // Change select and PHI nodes to select values instead of addresses: this
11621 // helps alias analysis out a lot, allows many others simplifications, and
11622 // exposes redundancy in the code.
11623 //
11624 // Note that we cannot do the transformation unless we know that the
11625 // introduced loads cannot trap! Something like this is valid as long as
11626 // the condition is always false: load (select bool %C, int* null, int* %G),
11627 // but it would not be valid if we transformed it to load from null
11628 // unconditionally.
11629 //
11630 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11631 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11632 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11633 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11634 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11635 SI->getOperand(1)->getName()+".val"), LI);
11636 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11637 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011638 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011639 }
11640
11641 // load (select (cond, null, P)) -> load P
11642 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11643 if (C->isNullValue()) {
11644 LI.setOperand(0, SI->getOperand(2));
11645 return &LI;
11646 }
11647
11648 // load (select (cond, P, null)) -> load P
11649 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11650 if (C->isNullValue()) {
11651 LI.setOperand(0, SI->getOperand(1));
11652 return &LI;
11653 }
11654 }
11655 }
11656 return 0;
11657}
11658
11659/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011660/// when possible. This makes it generally easy to do alias analysis and/or
11661/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011662static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11663 User *CI = cast<User>(SI.getOperand(1));
11664 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011665 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011666
11667 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011668 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11669 if (SrcTy == 0) return 0;
11670
11671 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011672
Chris Lattnera032c0e2009-01-16 20:08:59 +000011673 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11674 return 0;
11675
Chris Lattner54dddc72009-01-24 01:00:13 +000011676 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11677 /// to its first element. This allows us to handle things like:
11678 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11679 /// on 32-bit hosts.
11680 SmallVector<Value*, 4> NewGEPIndices;
11681
Chris Lattnera032c0e2009-01-16 20:08:59 +000011682 // If the source is an array, the code below will not succeed. Check to
11683 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11684 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011685 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11686 // Index through pointer.
Owen Anderson24be4c12009-07-03 00:17:18 +000011687 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner54dddc72009-01-24 01:00:13 +000011688 NewGEPIndices.push_back(Zero);
11689
11690 while (1) {
11691 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011692 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011693 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011694 NewGEPIndices.push_back(Zero);
11695 SrcPTy = STy->getElementType(0);
11696 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11697 NewGEPIndices.push_back(Zero);
11698 SrcPTy = ATy->getElementType();
11699 } else {
11700 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011701 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011702 }
11703
Owen Anderson24be4c12009-07-03 00:17:18 +000011704 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011705 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011706
11707 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11708 return 0;
11709
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011710 // If the pointers point into different address spaces or if they point to
11711 // values with different sizes, we can't do the transformation.
Dan Gohmana80e2712009-07-21 23:21:54 +000011712 if (!IC.getTargetData() ||
11713 SrcTy->getAddressSpace() !=
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011714 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmana80e2712009-07-21 23:21:54 +000011715 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11716 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattnera032c0e2009-01-16 20:08:59 +000011717 return 0;
11718
11719 // Okay, we are casting from one integer or pointer type to another of
11720 // the same size. Instead of casting the pointer before
11721 // the store, cast the value to be stored.
11722 Value *NewCast;
11723 Value *SIOp0 = SI.getOperand(0);
11724 Instruction::CastOps opcode = Instruction::BitCast;
11725 const Type* CastSrcTy = SIOp0->getType();
11726 const Type* CastDstTy = SrcPTy;
11727 if (isa<PointerType>(CastDstTy)) {
11728 if (CastSrcTy->isInteger())
11729 opcode = Instruction::IntToPtr;
11730 } else if (isa<IntegerType>(CastDstTy)) {
11731 if (isa<PointerType>(SIOp0->getType()))
11732 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011733 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011734
11735 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11736 // emit a GEP to index into its first field.
11737 if (!NewGEPIndices.empty()) {
11738 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Anderson24be4c12009-07-03 00:17:18 +000011739 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner54dddc72009-01-24 01:00:13 +000011740 NewGEPIndices.size());
11741 else
11742 CastOp = IC.InsertNewInstBefore(
11743 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11744 NewGEPIndices.end()), SI);
11745 }
11746
Chris Lattnera032c0e2009-01-16 20:08:59 +000011747 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Anderson24be4c12009-07-03 00:17:18 +000011748 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattnera032c0e2009-01-16 20:08:59 +000011749 else
11750 NewCast = IC.InsertNewInstBefore(
11751 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11752 SI);
11753 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011754}
11755
Chris Lattner6fd8c802008-11-27 08:56:30 +000011756/// equivalentAddressValues - Test if A and B will obviously have the same
11757/// value. This includes recognizing that %t0 and %t1 will have the same
11758/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011759/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011760/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011761/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011762/// %t2 = load i32* %t1
11763///
11764static bool equivalentAddressValues(Value *A, Value *B) {
11765 // Test if the values are trivially equivalent.
11766 if (A == B) return true;
11767
11768 // Test if the values come form identical arithmetic instructions.
11769 if (isa<BinaryOperator>(A) ||
11770 isa<CastInst>(A) ||
11771 isa<PHINode>(A) ||
11772 isa<GetElementPtrInst>(A))
11773 if (Instruction *BI = dyn_cast<Instruction>(B))
11774 if (cast<Instruction>(A)->isIdenticalTo(BI))
11775 return true;
11776
11777 // Otherwise they may not be equivalent.
11778 return false;
11779}
11780
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011781// If this instruction has two uses, one of which is a llvm.dbg.declare,
11782// return the llvm.dbg.declare.
11783DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11784 if (!V->hasNUses(2))
11785 return 0;
11786 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11787 UI != E; ++UI) {
11788 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11789 return DI;
11790 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11791 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11792 return DI;
11793 }
11794 }
11795 return 0;
11796}
11797
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011798Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11799 Value *Val = SI.getOperand(0);
11800 Value *Ptr = SI.getOperand(1);
11801
11802 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11803 EraseInstFromFunction(SI);
11804 ++NumCombined;
11805 return 0;
11806 }
11807
11808 // If the RHS is an alloca with a single use, zapify the store, making the
11809 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011810 // If the RHS is an alloca with a two uses, the other one being a
11811 // llvm.dbg.declare, zapify the store and the declare, making the
11812 // alloca dead. We must do this to prevent declare's from affecting
11813 // codegen.
11814 if (!SI.isVolatile()) {
11815 if (Ptr->hasOneUse()) {
11816 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011817 EraseInstFromFunction(SI);
11818 ++NumCombined;
11819 return 0;
11820 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011821 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11822 if (isa<AllocaInst>(GEP->getOperand(0))) {
11823 if (GEP->getOperand(0)->hasOneUse()) {
11824 EraseInstFromFunction(SI);
11825 ++NumCombined;
11826 return 0;
11827 }
11828 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11829 EraseInstFromFunction(*DI);
11830 EraseInstFromFunction(SI);
11831 ++NumCombined;
11832 return 0;
11833 }
11834 }
11835 }
11836 }
11837 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11838 EraseInstFromFunction(*DI);
11839 EraseInstFromFunction(SI);
11840 ++NumCombined;
11841 return 0;
11842 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011843 }
11844
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011845 // Attempt to improve the alignment.
Dan Gohmana80e2712009-07-21 23:21:54 +000011846 if (TD) {
11847 unsigned KnownAlign =
11848 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11849 if (KnownAlign >
11850 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11851 SI.getAlignment()))
11852 SI.setAlignment(KnownAlign);
11853 }
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011854
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011855 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011856 // stores to the same location, separated by a few arithmetic operations. This
11857 // situation often occurs with bitfield accesses.
11858 BasicBlock::iterator BBI = &SI;
11859 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11860 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011861 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011862 // Don't count debug info directives, lest they affect codegen,
11863 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11864 // It is necessary for correctness to skip those that feed into a
11865 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011866 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011867 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011868 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011869 continue;
11870 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011871
11872 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11873 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011874 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11875 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011876 ++NumDeadStore;
11877 ++BBI;
11878 EraseInstFromFunction(*PrevSI);
11879 continue;
11880 }
11881 break;
11882 }
11883
11884 // If this is a load, we have to stop. However, if the loaded value is from
11885 // the pointer we're loading and is producing the pointer we're storing,
11886 // then *this* store is dead (X = load P; store X -> P).
11887 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011888 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11889 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011890 EraseInstFromFunction(SI);
11891 ++NumCombined;
11892 return 0;
11893 }
11894 // Otherwise, this is a load from some other location. Stores before it
11895 // may not be dead.
11896 break;
11897 }
11898
11899 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011900 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011901 break;
11902 }
11903
11904
11905 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11906
11907 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011908 if (isa<ConstantPointerNull>(Ptr) &&
11909 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011910 if (!isa<UndefValue>(Val)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011911 SI.setOperand(0, Context->getUndef(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011912 if (Instruction *U = dyn_cast<Instruction>(Val))
11913 AddToWorkList(U); // Dropped a use.
11914 ++NumCombined;
11915 }
11916 return 0; // Do not modify these!
11917 }
11918
11919 // store undef, Ptr -> noop
11920 if (isa<UndefValue>(Val)) {
11921 EraseInstFromFunction(SI);
11922 ++NumCombined;
11923 return 0;
11924 }
11925
11926 // If the pointer destination is a cast, see if we can fold the cast into the
11927 // source instead.
11928 if (isa<CastInst>(Ptr))
11929 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11930 return Res;
11931 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11932 if (CE->isCast())
11933 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11934 return Res;
11935
11936
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011937 // If this store is the last instruction in the basic block (possibly
11938 // excepting debug info instructions and the pointer bitcasts that feed
11939 // into them), and if the block ends with an unconditional branch, try
11940 // to move it to the successor block.
11941 BBI = &SI;
11942 do {
11943 ++BBI;
11944 } while (isa<DbgInfoIntrinsic>(BBI) ||
11945 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011946 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11947 if (BI->isUnconditional())
11948 if (SimplifyStoreAtEndOfBlock(SI))
11949 return 0; // xform done!
11950
11951 return 0;
11952}
11953
11954/// SimplifyStoreAtEndOfBlock - Turn things like:
11955/// if () { *P = v1; } else { *P = v2 }
11956/// into a phi node with a store in the successor.
11957///
11958/// Simplify things like:
11959/// *P = v1; if () { *P = v2; }
11960/// into a phi node with a store in the successor.
11961///
11962bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11963 BasicBlock *StoreBB = SI.getParent();
11964
11965 // Check to see if the successor block has exactly two incoming edges. If
11966 // so, see if the other predecessor contains a store to the same location.
11967 // if so, insert a PHI node (if needed) and move the stores down.
11968 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11969
11970 // Determine whether Dest has exactly two predecessors and, if so, compute
11971 // the other predecessor.
11972 pred_iterator PI = pred_begin(DestBB);
11973 BasicBlock *OtherBB = 0;
11974 if (*PI != StoreBB)
11975 OtherBB = *PI;
11976 ++PI;
11977 if (PI == pred_end(DestBB))
11978 return false;
11979
11980 if (*PI != StoreBB) {
11981 if (OtherBB)
11982 return false;
11983 OtherBB = *PI;
11984 }
11985 if (++PI != pred_end(DestBB))
11986 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011987
11988 // Bail out if all the relevant blocks aren't distinct (this can happen,
11989 // for example, if SI is in an infinite loop)
11990 if (StoreBB == DestBB || OtherBB == DestBB)
11991 return false;
11992
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011993 // Verify that the other block ends in a branch and is not otherwise empty.
11994 BasicBlock::iterator BBI = OtherBB->getTerminator();
11995 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11996 if (!OtherBr || BBI == OtherBB->begin())
11997 return false;
11998
11999 // If the other block ends in an unconditional branch, check for the 'if then
12000 // else' case. there is an instruction before the branch.
12001 StoreInst *OtherStore = 0;
12002 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012003 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012004 // Skip over debugging info.
12005 while (isa<DbgInfoIntrinsic>(BBI) ||
12006 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12007 if (BBI==OtherBB->begin())
12008 return false;
12009 --BBI;
12010 }
12011 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012012 OtherStore = dyn_cast<StoreInst>(BBI);
12013 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12014 return false;
12015 } else {
12016 // Otherwise, the other block ended with a conditional branch. If one of the
12017 // destinations is StoreBB, then we have the if/then case.
12018 if (OtherBr->getSuccessor(0) != StoreBB &&
12019 OtherBr->getSuccessor(1) != StoreBB)
12020 return false;
12021
12022 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12023 // if/then triangle. See if there is a store to the same ptr as SI that
12024 // lives in OtherBB.
12025 for (;; --BBI) {
12026 // Check to see if we find the matching store.
12027 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12028 if (OtherStore->getOperand(1) != SI.getOperand(1))
12029 return false;
12030 break;
12031 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012032 // If we find something that may be using or overwriting the stored
12033 // value, or if we run out of instructions, we can't do the xform.
12034 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012035 BBI == OtherBB->begin())
12036 return false;
12037 }
12038
12039 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012040 // make sure nothing reads or overwrites the stored value in
12041 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012042 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12043 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012044 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012045 return false;
12046 }
12047 }
12048
12049 // Insert a PHI node now if we need it.
12050 Value *MergedVal = OtherStore->getOperand(0);
12051 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012052 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012053 PN->reserveOperandSpace(2);
12054 PN->addIncoming(SI.getOperand(0), SI.getParent());
12055 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12056 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12057 }
12058
12059 // Advance to a place where it is safe to insert the new store and
12060 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012061 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012062 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12063 OtherStore->isVolatile()), *BBI);
12064
12065 // Nuke the old stores.
12066 EraseInstFromFunction(SI);
12067 EraseInstFromFunction(*OtherStore);
12068 ++NumCombined;
12069 return true;
12070}
12071
12072
12073Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12074 // Change br (not X), label True, label False to: br X, label False, True
12075 Value *X = 0;
12076 BasicBlock *TrueDest;
12077 BasicBlock *FalseDest;
Owen Andersona21eb582009-07-10 17:35:01 +000012078 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012079 !isa<Constant>(X)) {
12080 // Swap Destinations and condition...
12081 BI.setCondition(X);
12082 BI.setSuccessor(0, FalseDest);
12083 BI.setSuccessor(1, TrueDest);
12084 return &BI;
12085 }
12086
12087 // Cannonicalize fcmp_one -> fcmp_oeq
12088 FCmpInst::Predicate FPred; Value *Y;
12089 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersona21eb582009-07-10 17:35:01 +000012090 TrueDest, FalseDest), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012091 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12092 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12093 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12094 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012095 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012096 NewSCC->takeName(I);
12097 // Swap Destinations and condition...
12098 BI.setCondition(NewSCC);
12099 BI.setSuccessor(0, FalseDest);
12100 BI.setSuccessor(1, TrueDest);
12101 RemoveFromWorkList(I);
12102 I->eraseFromParent();
12103 AddToWorkList(NewSCC);
12104 return &BI;
12105 }
12106
12107 // Cannonicalize icmp_ne -> icmp_eq
12108 ICmpInst::Predicate IPred;
12109 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersona21eb582009-07-10 17:35:01 +000012110 TrueDest, FalseDest), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012111 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12112 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12113 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12114 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12115 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012116 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012117 NewSCC->takeName(I);
12118 // Swap Destinations and condition...
12119 BI.setCondition(NewSCC);
12120 BI.setSuccessor(0, FalseDest);
12121 BI.setSuccessor(1, TrueDest);
12122 RemoveFromWorkList(I);
12123 I->eraseFromParent();;
12124 AddToWorkList(NewSCC);
12125 return &BI;
12126 }
12127
12128 return 0;
12129}
12130
12131Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12132 Value *Cond = SI.getCondition();
12133 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12134 if (I->getOpcode() == Instruction::Add)
12135 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12136 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12137 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012138 SI.setOperand(i,
12139 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012140 AddRHS));
12141 SI.setOperand(0, I->getOperand(0));
12142 AddToWorkList(I);
12143 return &SI;
12144 }
12145 }
12146 return 0;
12147}
12148
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012149Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012150 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012151
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012152 if (!EV.hasIndices())
12153 return ReplaceInstUsesWith(EV, Agg);
12154
12155 if (Constant *C = dyn_cast<Constant>(Agg)) {
12156 if (isa<UndefValue>(C))
Owen Anderson24be4c12009-07-03 00:17:18 +000012157 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012158
12159 if (isa<ConstantAggregateZero>(C))
Owen Anderson24be4c12009-07-03 00:17:18 +000012160 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012161
12162 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12163 // Extract the element indexed by the first index out of the constant
12164 Value *V = C->getOperand(*EV.idx_begin());
12165 if (EV.getNumIndices() > 1)
12166 // Extract the remaining indices out of the constant indexed by the
12167 // first index
12168 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12169 else
12170 return ReplaceInstUsesWith(EV, V);
12171 }
12172 return 0; // Can't handle other constants
12173 }
12174 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12175 // We're extracting from an insertvalue instruction, compare the indices
12176 const unsigned *exti, *exte, *insi, *inse;
12177 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12178 exte = EV.idx_end(), inse = IV->idx_end();
12179 exti != exte && insi != inse;
12180 ++exti, ++insi) {
12181 if (*insi != *exti)
12182 // The insert and extract both reference distinctly different elements.
12183 // This means the extract is not influenced by the insert, and we can
12184 // replace the aggregate operand of the extract with the aggregate
12185 // operand of the insert. i.e., replace
12186 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12187 // %E = extractvalue { i32, { i32 } } %I, 0
12188 // with
12189 // %E = extractvalue { i32, { i32 } } %A, 0
12190 return ExtractValueInst::Create(IV->getAggregateOperand(),
12191 EV.idx_begin(), EV.idx_end());
12192 }
12193 if (exti == exte && insi == inse)
12194 // Both iterators are at the end: Index lists are identical. Replace
12195 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12196 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12197 // with "i32 42"
12198 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12199 if (exti == exte) {
12200 // The extract list is a prefix of the insert list. i.e. replace
12201 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12202 // %E = extractvalue { i32, { i32 } } %I, 1
12203 // with
12204 // %X = extractvalue { i32, { i32 } } %A, 1
12205 // %E = insertvalue { i32 } %X, i32 42, 0
12206 // by switching the order of the insert and extract (though the
12207 // insertvalue should be left in, since it may have other uses).
12208 Value *NewEV = InsertNewInstBefore(
12209 ExtractValueInst::Create(IV->getAggregateOperand(),
12210 EV.idx_begin(), EV.idx_end()),
12211 EV);
12212 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12213 insi, inse);
12214 }
12215 if (insi == inse)
12216 // The insert list is a prefix of the extract list
12217 // We can simply remove the common indices from the extract and make it
12218 // operate on the inserted value instead of the insertvalue result.
12219 // i.e., replace
12220 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12221 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12222 // with
12223 // %E extractvalue { i32 } { i32 42 }, 0
12224 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12225 exti, exte);
12226 }
12227 // Can't simplify extracts from other values. Note that nested extracts are
12228 // already simplified implicitely by the above (extract ( extract (insert) )
12229 // will be translated into extract ( insert ( extract ) ) first and then just
12230 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012231 return 0;
12232}
12233
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012234/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12235/// is to leave as a vector operation.
12236static bool CheapToScalarize(Value *V, bool isConstant) {
12237 if (isa<ConstantAggregateZero>(V))
12238 return true;
12239 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12240 if (isConstant) return true;
12241 // If all elts are the same, we can extract.
12242 Constant *Op0 = C->getOperand(0);
12243 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12244 if (C->getOperand(i) != Op0)
12245 return false;
12246 return true;
12247 }
12248 Instruction *I = dyn_cast<Instruction>(V);
12249 if (!I) return false;
12250
12251 // Insert element gets simplified to the inserted element or is deleted if
12252 // this is constant idx extract element and its a constant idx insertelt.
12253 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12254 isa<ConstantInt>(I->getOperand(2)))
12255 return true;
12256 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12257 return true;
12258 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12259 if (BO->hasOneUse() &&
12260 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12261 CheapToScalarize(BO->getOperand(1), isConstant)))
12262 return true;
12263 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12264 if (CI->hasOneUse() &&
12265 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12266 CheapToScalarize(CI->getOperand(1), isConstant)))
12267 return true;
12268
12269 return false;
12270}
12271
12272/// Read and decode a shufflevector mask.
12273///
12274/// It turns undef elements into values that are larger than the number of
12275/// elements in the input.
12276static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12277 unsigned NElts = SVI->getType()->getNumElements();
12278 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12279 return std::vector<unsigned>(NElts, 0);
12280 if (isa<UndefValue>(SVI->getOperand(2)))
12281 return std::vector<unsigned>(NElts, 2*NElts);
12282
12283 std::vector<unsigned> Result;
12284 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012285 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12286 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012287 Result.push_back(NElts*2); // undef -> 8
12288 else
Gabor Greif17396002008-06-12 21:37:33 +000012289 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012290 return Result;
12291}
12292
12293/// FindScalarElement - Given a vector and an element number, see if the scalar
12294/// value is already around as a register, for example if it were inserted then
12295/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012296static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012297 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012298 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12299 const VectorType *PTy = cast<VectorType>(V->getType());
12300 unsigned Width = PTy->getNumElements();
12301 if (EltNo >= Width) // Out of range access.
Owen Anderson24be4c12009-07-03 00:17:18 +000012302 return Context->getUndef(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012303
12304 if (isa<UndefValue>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +000012305 return Context->getUndef(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012306 else if (isa<ConstantAggregateZero>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +000012307 return Context->getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012308 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12309 return CP->getOperand(EltNo);
12310 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12311 // If this is an insert to a variable element, we don't know what it is.
12312 if (!isa<ConstantInt>(III->getOperand(2)))
12313 return 0;
12314 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12315
12316 // If this is an insert to the element we are looking for, return the
12317 // inserted value.
12318 if (EltNo == IIElt)
12319 return III->getOperand(1);
12320
12321 // Otherwise, the insertelement doesn't modify the value, recurse on its
12322 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012323 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012324 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012325 unsigned LHSWidth =
12326 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012327 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012328 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012329 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012330 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012331 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012332 else
Owen Anderson24be4c12009-07-03 00:17:18 +000012333 return Context->getUndef(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012334 }
12335
12336 // Otherwise, we don't know.
12337 return 0;
12338}
12339
12340Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012341 // If vector val is undef, replace extract with scalar undef.
12342 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson24be4c12009-07-03 00:17:18 +000012343 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012344
12345 // If vector val is constant 0, replace extract with scalar 0.
12346 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Anderson24be4c12009-07-03 00:17:18 +000012347 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012348
12349 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012350 // If vector val is constant with all elements the same, replace EI with
12351 // that element. When the elements are not identical, we cannot replace yet
12352 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012353 Constant *op0 = C->getOperand(0);
12354 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12355 if (C->getOperand(i) != op0) {
12356 op0 = 0;
12357 break;
12358 }
12359 if (op0)
12360 return ReplaceInstUsesWith(EI, op0);
12361 }
Eli Friedmanf34209b2009-07-18 19:04:16 +000012362
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012363 // If extracting a specified index from the vector, see if we can recursively
12364 // find a previously computed scalar that was inserted into the vector.
12365 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12366 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedmanf34209b2009-07-18 19:04:16 +000012367 unsigned VectorWidth =
12368 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012369
12370 // If this is extracting an invalid index, turn this into undef, to avoid
12371 // crashing the code below.
12372 if (IndexVal >= VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012373 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012374
12375 // This instruction only demands the single element from the input vector.
12376 // If the input vector has a single use, simplify it based on this use
12377 // property.
Eli Friedmanf34209b2009-07-18 19:04:16 +000012378 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012379 APInt UndefElts(VectorWidth, 0);
12380 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012381 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012382 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012383 EI.setOperand(0, V);
12384 return &EI;
12385 }
12386 }
12387
Owen Anderson24be4c12009-07-03 00:17:18 +000012388 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012389 return ReplaceInstUsesWith(EI, Elt);
12390
12391 // If the this extractelement is directly using a bitcast from a vector of
12392 // the same number of elements, see if we can find the source element from
12393 // it. In this case, we will end up needing to bitcast the scalars.
12394 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12395 if (const VectorType *VT =
12396 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12397 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012398 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12399 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012400 return new BitCastInst(Elt, EI.getType());
12401 }
12402 }
12403
12404 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12405 if (I->hasOneUse()) {
12406 // Push extractelement into predecessor operation if legal and
12407 // profitable to do so
12408 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12409 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12410 if (CheapToScalarize(BO, isConstantElt)) {
12411 ExtractElementInst *newEI0 =
12412 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12413 EI.getName()+".lhs");
12414 ExtractElementInst *newEI1 =
12415 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12416 EI.getName()+".rhs");
12417 InsertNewInstBefore(newEI0, EI);
12418 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012419 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012420 }
12421 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012422 unsigned AS =
12423 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012424 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +000012425 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012426 GetElementPtrInst *GEP =
12427 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012428 InsertNewInstBefore(GEP, EI);
12429 return new LoadInst(GEP);
12430 }
12431 }
12432 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12433 // Extracting the inserted element?
12434 if (IE->getOperand(2) == EI.getOperand(1))
12435 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12436 // If the inserted and extracted elements are constants, they must not
12437 // be the same value, extract from the pre-inserted value instead.
12438 if (isa<Constant>(IE->getOperand(2)) &&
12439 isa<Constant>(EI.getOperand(1))) {
12440 AddUsesToWorkList(EI);
12441 EI.setOperand(0, IE->getOperand(0));
12442 return &EI;
12443 }
12444 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12445 // If this is extracting an element from a shufflevector, figure out where
12446 // it came from and extract from the appropriate input element instead.
12447 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12448 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12449 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012450 unsigned LHSWidth =
12451 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12452
12453 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012454 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012455 else if (SrcIdx < LHSWidth*2) {
12456 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012457 Src = SVI->getOperand(1);
12458 } else {
Owen Anderson24be4c12009-07-03 00:17:18 +000012459 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012460 }
Owen Anderson9f5b2aa2009-07-14 23:09:55 +000012461 return new ExtractElementInst(Src,
12462 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012463 }
12464 }
Eli Friedman1d31dee2009-07-18 23:06:53 +000012465 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012466 }
12467 return 0;
12468}
12469
12470/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12471/// elements from either LHS or RHS, return the shuffle mask and true.
12472/// Otherwise, return false.
12473static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012474 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012475 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012476 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12477 "Invalid CollectSingleShuffleElements");
12478 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12479
12480 if (isa<UndefValue>(V)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012481 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012482 return true;
12483 } else if (V == LHS) {
12484 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson24be4c12009-07-03 00:17:18 +000012485 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012486 return true;
12487 } else if (V == RHS) {
12488 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson24be4c12009-07-03 00:17:18 +000012489 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012490 return true;
12491 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12492 // If this is an insert of an extract from some other vector, include it.
12493 Value *VecOp = IEI->getOperand(0);
12494 Value *ScalarOp = IEI->getOperand(1);
12495 Value *IdxOp = IEI->getOperand(2);
12496
12497 if (!isa<ConstantInt>(IdxOp))
12498 return false;
12499 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12500
12501 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12502 // Okay, we can handle this if the vector we are insertinting into is
12503 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012504 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012505 // If so, update the mask to reflect the inserted undef.
Owen Anderson24be4c12009-07-03 00:17:18 +000012506 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012507 return true;
12508 }
12509 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12510 if (isa<ConstantInt>(EI->getOperand(1)) &&
12511 EI->getOperand(0)->getType() == V->getType()) {
12512 unsigned ExtractedIdx =
12513 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12514
12515 // This must be extracting from either LHS or RHS.
12516 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12517 // Okay, we can handle this if the vector we are insertinting into is
12518 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012519 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012520 // If so, update the mask to reflect the inserted value.
12521 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012522 Mask[InsertedIdx % NumElts] =
Owen Anderson24be4c12009-07-03 00:17:18 +000012523 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012524 } else {
12525 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012526 Mask[InsertedIdx % NumElts] =
Owen Anderson24be4c12009-07-03 00:17:18 +000012527 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012528
12529 }
12530 return true;
12531 }
12532 }
12533 }
12534 }
12535 }
12536 // TODO: Handle shufflevector here!
12537
12538 return false;
12539}
12540
12541/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12542/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12543/// that computes V and the LHS value of the shuffle.
12544static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012545 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012546 assert(isa<VectorType>(V->getType()) &&
12547 (RHS == 0 || V->getType() == RHS->getType()) &&
12548 "Invalid shuffle!");
12549 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12550
12551 if (isa<UndefValue>(V)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012552 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012553 return V;
12554 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012555 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012556 return V;
12557 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12558 // If this is an insert of an extract from some other vector, include it.
12559 Value *VecOp = IEI->getOperand(0);
12560 Value *ScalarOp = IEI->getOperand(1);
12561 Value *IdxOp = IEI->getOperand(2);
12562
12563 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12564 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12565 EI->getOperand(0)->getType() == V->getType()) {
12566 unsigned ExtractedIdx =
12567 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12568 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12569
12570 // Either the extracted from or inserted into vector must be RHSVec,
12571 // otherwise we'd end up with a shuffle of three inputs.
12572 if (EI->getOperand(0) == RHS || RHS == 0) {
12573 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012574 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012575 Mask[InsertedIdx % NumElts] =
Owen Anderson24be4c12009-07-03 00:17:18 +000012576 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012577 return V;
12578 }
12579
12580 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012581 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12582 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012583 // Everything but the extracted element is replaced with the RHS.
12584 for (unsigned i = 0; i != NumElts; ++i) {
12585 if (i != InsertedIdx)
Owen Anderson24be4c12009-07-03 00:17:18 +000012586 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012587 }
12588 return V;
12589 }
12590
12591 // If this insertelement is a chain that comes from exactly these two
12592 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012593 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12594 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012595 return EI->getOperand(0);
12596
12597 }
12598 }
12599 }
12600 // TODO: Handle shufflevector here!
12601
12602 // Otherwise, can't do anything fancy. Return an identity vector.
12603 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson24be4c12009-07-03 00:17:18 +000012604 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012605 return V;
12606}
12607
12608Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12609 Value *VecOp = IE.getOperand(0);
12610 Value *ScalarOp = IE.getOperand(1);
12611 Value *IdxOp = IE.getOperand(2);
12612
12613 // Inserting an undef or into an undefined place, remove this.
12614 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12615 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanf34209b2009-07-18 19:04:16 +000012616
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012617 // If the inserted element was extracted from some other vector, and if the
12618 // indexes are constant, try to turn this into a shufflevector operation.
12619 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12620 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12621 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedmanf34209b2009-07-18 19:04:16 +000012622 unsigned NumVectorElts = IE.getType()->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012623 unsigned ExtractedIdx =
12624 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12625 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12626
12627 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12628 return ReplaceInstUsesWith(IE, VecOp);
12629
12630 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson24be4c12009-07-03 00:17:18 +000012631 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012632
12633 // If we are extracting a value from a vector, then inserting it right
12634 // back into the same place, just use the input vector.
12635 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12636 return ReplaceInstUsesWith(IE, VecOp);
12637
12638 // We could theoretically do this for ANY input. However, doing so could
12639 // turn chains of insertelement instructions into a chain of shufflevector
12640 // instructions, and right now we do not merge shufflevectors. As such,
12641 // only do this in a situation where it is clear that there is benefit.
12642 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12643 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12644 // the values of VecOp, except then one read from EIOp0.
12645 // Build a new shuffle mask.
12646 std::vector<Constant*> Mask;
12647 if (isa<UndefValue>(VecOp))
Owen Anderson24be4c12009-07-03 00:17:18 +000012648 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012649 else {
12650 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson24be4c12009-07-03 00:17:18 +000012651 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012652 NumVectorElts));
12653 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012654 Mask[InsertedIdx] =
12655 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012656 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson24be4c12009-07-03 00:17:18 +000012657 Context->getConstantVector(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012658 }
12659
12660 // If this insertelement isn't used by some other insertelement, turn it
12661 // (and any insertelements it points to), into one big shuffle.
12662 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12663 std::vector<Constant*> Mask;
12664 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012665 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12666 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012667 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012668 return new ShuffleVectorInst(LHS, RHS,
12669 Context->getConstantVector(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012670 }
12671 }
12672 }
12673
Eli Friedmanbefee262009-06-06 20:08:03 +000012674 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12675 APInt UndefElts(VWidth, 0);
12676 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12677 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12678 return &IE;
12679
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012680 return 0;
12681}
12682
12683
12684Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12685 Value *LHS = SVI.getOperand(0);
12686 Value *RHS = SVI.getOperand(1);
12687 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12688
12689 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012690
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012691 // Undefined shuffle mask -> undefined value.
12692 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson24be4c12009-07-03 00:17:18 +000012693 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012694
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012695 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012696
12697 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12698 return 0;
12699
Evan Cheng63295ab2009-02-03 10:05:09 +000012700 APInt UndefElts(VWidth, 0);
12701 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12702 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012703 LHS = SVI.getOperand(0);
12704 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012705 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012706 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012707
12708 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12709 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12710 if (LHS == RHS || isa<UndefValue>(LHS)) {
12711 if (isa<UndefValue>(LHS) && LHS == RHS) {
12712 // shuffle(undef,undef,mask) -> undef.
12713 return ReplaceInstUsesWith(SVI, LHS);
12714 }
12715
12716 // Remap any references to RHS to use LHS.
12717 std::vector<Constant*> Elts;
12718 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12719 if (Mask[i] >= 2*e)
Owen Anderson24be4c12009-07-03 00:17:18 +000012720 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012721 else {
12722 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012723 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012724 Mask[i] = 2*e; // Turn into undef.
Owen Anderson24be4c12009-07-03 00:17:18 +000012725 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012726 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012727 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson24be4c12009-07-03 00:17:18 +000012728 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012729 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012730 }
12731 }
12732 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson24be4c12009-07-03 00:17:18 +000012733 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12734 SVI.setOperand(2, Context->getConstantVector(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012735 LHS = SVI.getOperand(0);
12736 RHS = SVI.getOperand(1);
12737 MadeChange = true;
12738 }
12739
12740 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12741 bool isLHSID = true, isRHSID = true;
12742
12743 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12744 if (Mask[i] >= e*2) continue; // Ignore undef values.
12745 // Is this an identity shuffle of the LHS value?
12746 isLHSID &= (Mask[i] == i);
12747
12748 // Is this an identity shuffle of the RHS value?
12749 isRHSID &= (Mask[i]-e == i);
12750 }
12751
12752 // Eliminate identity shuffles.
12753 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12754 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12755
12756 // If the LHS is a shufflevector itself, see if we can combine it with this
12757 // one without producing an unusual shuffle. Here we are really conservative:
12758 // we are absolutely afraid of producing a shuffle mask not in the input
12759 // program, because the code gen may not be smart enough to turn a merged
12760 // shuffle into two specific shuffles: it may produce worse code. As such,
12761 // we only merge two shuffles if the result is one of the two input shuffle
12762 // masks. In this case, merging the shuffles just removes one instruction,
12763 // which we know is safe. This is good for things like turning:
12764 // (splat(splat)) -> splat.
12765 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12766 if (isa<UndefValue>(RHS)) {
12767 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12768
12769 std::vector<unsigned> NewMask;
12770 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12771 if (Mask[i] >= 2*e)
12772 NewMask.push_back(2*e);
12773 else
12774 NewMask.push_back(LHSMask[Mask[i]]);
12775
12776 // If the result mask is equal to the src shuffle or this shuffle mask, do
12777 // the replacement.
12778 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012779 unsigned LHSInNElts =
12780 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012781 std::vector<Constant*> Elts;
12782 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012783 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012784 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012785 } else {
Owen Anderson24be4c12009-07-03 00:17:18 +000012786 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012787 }
12788 }
12789 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12790 LHSSVI->getOperand(1),
Owen Anderson24be4c12009-07-03 00:17:18 +000012791 Context->getConstantVector(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012792 }
12793 }
12794 }
12795
12796 return MadeChange ? &SVI : 0;
12797}
12798
12799
12800
12801
12802/// TryToSinkInstruction - Try to move the specified instruction from its
12803/// current block into the beginning of DestBlock, which can only happen if it's
12804/// safe to move the instruction past all of the instructions between it and the
12805/// end of its block.
12806static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12807 assert(I->hasOneUse() && "Invariants didn't hold!");
12808
12809 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012810 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012811 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012812
12813 // Do not sink alloca instructions out of the entry block.
12814 if (isa<AllocaInst>(I) && I->getParent() ==
12815 &DestBlock->getParent()->getEntryBlock())
12816 return false;
12817
12818 // We can only sink load instructions if there is nothing between the load and
12819 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012820 if (I->mayReadFromMemory()) {
12821 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012822 Scan != E; ++Scan)
12823 if (Scan->mayWriteToMemory())
12824 return false;
12825 }
12826
Dan Gohman514277c2008-05-23 21:05:58 +000012827 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012828
Dale Johannesen24339f12009-03-03 01:09:07 +000012829 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012830 I->moveBefore(InsertPos);
12831 ++NumSunkInst;
12832 return true;
12833}
12834
12835
12836/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12837/// all reachable code to the worklist.
12838///
12839/// This has a couple of tricks to make the code faster and more powerful. In
12840/// particular, we constant fold and DCE instructions as we go, to avoid adding
12841/// them to the worklist (this significantly speeds up instcombine on code where
12842/// many instructions are dead or constant). Additionally, if we find a branch
12843/// whose condition is a known constant, we only visit the reachable successors.
12844///
12845static void AddReachableCodeToWorklist(BasicBlock *BB,
12846 SmallPtrSet<BasicBlock*, 64> &Visited,
12847 InstCombiner &IC,
12848 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012849 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012850 Worklist.push_back(BB);
12851
12852 while (!Worklist.empty()) {
12853 BB = Worklist.back();
12854 Worklist.pop_back();
12855
12856 // We have now visited this block! If we've already been here, ignore it.
12857 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012858
12859 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012860 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12861 Instruction *Inst = BBI++;
12862
12863 // DCE instruction if trivially dead.
12864 if (isInstructionTriviallyDead(Inst)) {
12865 ++NumDeadInst;
12866 DOUT << "IC: DCE: " << *Inst;
12867 Inst->eraseFromParent();
12868 continue;
12869 }
12870
12871 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012872 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012873 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12874 Inst->replaceAllUsesWith(C);
12875 ++NumConstProp;
12876 Inst->eraseFromParent();
12877 continue;
12878 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012879
Devang Patel794140c2008-11-19 18:56:50 +000012880 // If there are two consecutive llvm.dbg.stoppoint calls then
12881 // it is likely that the optimizer deleted code in between these
12882 // two intrinsics.
12883 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12884 if (DBI_Next) {
12885 if (DBI_Prev
12886 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12887 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12888 IC.RemoveFromWorkList(DBI_Prev);
12889 DBI_Prev->eraseFromParent();
12890 }
12891 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012892 } else {
12893 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012894 }
12895
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012896 IC.AddToWorkList(Inst);
12897 }
12898
12899 // Recursively visit successors. If this is a branch or switch on a
12900 // constant, only visit the reachable successor.
12901 TerminatorInst *TI = BB->getTerminator();
12902 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12903 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12904 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012905 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012906 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012907 continue;
12908 }
12909 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12910 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12911 // See if this is an explicit destination.
12912 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12913 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012914 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012915 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012916 continue;
12917 }
12918
12919 // Otherwise it is the default destination.
12920 Worklist.push_back(SI->getSuccessor(0));
12921 continue;
12922 }
12923 }
12924
12925 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12926 Worklist.push_back(TI->getSuccessor(i));
12927 }
12928}
12929
12930bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12931 bool Changed = false;
Dan Gohmana80e2712009-07-21 23:21:54 +000012932 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012933
12934 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12935 << F.getNameStr() << "\n");
12936
12937 {
12938 // Do a depth-first traversal of the function, populate the worklist with
12939 // the reachable instructions. Ignore blocks that are not reachable. Keep
12940 // track of which blocks we visit.
12941 SmallPtrSet<BasicBlock*, 64> Visited;
12942 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12943
12944 // Do a quick scan over the function. If we find any blocks that are
12945 // unreachable, remove any instructions inside of them. This prevents
12946 // the instcombine code from having to deal with some bad special cases.
12947 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12948 if (!Visited.count(BB)) {
12949 Instruction *Term = BB->getTerminator();
12950 while (Term != BB->begin()) { // Remove instrs bottom-up
12951 BasicBlock::iterator I = Term; --I;
12952
12953 DOUT << "IC: DCE: " << *I;
Dale Johannesendf356c62009-03-10 21:19:49 +000012954 // A debug intrinsic shouldn't force another iteration if we weren't
12955 // going to do one without it.
12956 if (!isa<DbgInfoIntrinsic>(I)) {
12957 ++NumDeadInst;
12958 Changed = true;
12959 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012960 if (!I->use_empty())
Owen Anderson24be4c12009-07-03 00:17:18 +000012961 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012962 I->eraseFromParent();
12963 }
12964 }
12965 }
12966
12967 while (!Worklist.empty()) {
12968 Instruction *I = RemoveOneFromWorkList();
12969 if (I == 0) continue; // skip null values.
12970
12971 // Check to see if we can DCE the instruction.
12972 if (isInstructionTriviallyDead(I)) {
12973 // Add operands to the worklist.
12974 if (I->getNumOperands() < 4)
12975 AddUsesToWorkList(*I);
12976 ++NumDeadInst;
12977
12978 DOUT << "IC: DCE: " << *I;
12979
12980 I->eraseFromParent();
12981 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012982 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012983 continue;
12984 }
12985
12986 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000012987 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012988 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12989
12990 // Add operands to the worklist.
12991 AddUsesToWorkList(*I);
12992 ReplaceInstUsesWith(*I, C);
12993
12994 ++NumConstProp;
12995 I->eraseFromParent();
12996 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012997 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012998 continue;
12999 }
13000
Eli Friedman5c619182009-07-15 22:13:34 +000013001 if (TD) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000013002 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000013003 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13004 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000013005 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13006 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000013007 if (NewC != CE) {
13008 i->set(NewC);
13009 Changed = true;
13010 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000013011 }
13012
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013013 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013014 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013015 BasicBlock *BB = I->getParent();
13016 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13017 if (UserParent != BB) {
13018 bool UserIsSuccessor = false;
13019 // See if the user is one of our successors.
13020 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13021 if (*SI == UserParent) {
13022 UserIsSuccessor = true;
13023 break;
13024 }
13025
13026 // If the user is one of our immediate successors, and if that successor
13027 // only has us as a predecessors (we'd have to split the critical edge
13028 // otherwise), we can keep going.
13029 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13030 next(pred_begin(UserParent)) == pred_end(UserParent))
13031 // Okay, the CFG is simple enough, try to sink this instruction.
13032 Changed |= TryToSinkInstruction(I, UserParent);
13033 }
13034 }
13035
13036 // Now that we have an instruction, try combining it to simplify it...
13037#ifndef NDEBUG
13038 std::string OrigI;
13039#endif
13040 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13041 if (Instruction *Result = visit(*I)) {
13042 ++NumCombined;
13043 // Should we replace the old instruction with a new one?
13044 if (Result != I) {
13045 DOUT << "IC: Old = " << *I
13046 << " New = " << *Result;
13047
13048 // Everything uses the new instruction now.
13049 I->replaceAllUsesWith(Result);
13050
13051 // Push the new instruction and any users onto the worklist.
13052 AddToWorkList(Result);
13053 AddUsersToWorkList(*Result);
13054
13055 // Move the name to the new instruction first.
13056 Result->takeName(I);
13057
13058 // Insert the new instruction into the basic block...
13059 BasicBlock *InstParent = I->getParent();
13060 BasicBlock::iterator InsertPos = I;
13061
13062 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13063 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13064 ++InsertPos;
13065
13066 InstParent->getInstList().insert(InsertPos, Result);
13067
13068 // Make sure that we reprocess all operands now that we reduced their
13069 // use counts.
13070 AddUsesToWorkList(*I);
13071
13072 // Instructions can end up on the worklist more than once. Make sure
13073 // we do not process an instruction that has been deleted.
13074 RemoveFromWorkList(I);
13075
13076 // Erase the old instruction.
13077 InstParent->getInstList().erase(I);
13078 } else {
13079#ifndef NDEBUG
13080 DOUT << "IC: Mod = " << OrigI
13081 << " New = " << *I;
13082#endif
13083
13084 // If the instruction was modified, it's possible that it is now dead.
13085 // if so, remove it.
13086 if (isInstructionTriviallyDead(I)) {
13087 // Make sure we process all operands now that we are reducing their
13088 // use counts.
13089 AddUsesToWorkList(*I);
13090
13091 // Instructions may end up in the worklist more than once. Erase all
13092 // occurrences of this instruction.
13093 RemoveFromWorkList(I);
13094 I->eraseFromParent();
13095 } else {
13096 AddToWorkList(I);
13097 AddUsersToWorkList(*I);
13098 }
13099 }
13100 Changed = true;
13101 }
13102 }
13103
13104 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013105
13106 // Do an explicit clear, this shrinks the map if needed.
13107 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013108 return Changed;
13109}
13110
13111
13112bool InstCombiner::runOnFunction(Function &F) {
13113 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Anderson175b6542009-07-22 00:24:57 +000013114 Context = &F.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013115
13116 bool EverMadeChange = false;
13117
13118 // Iterate while there is work to do.
13119 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013120 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013121 EverMadeChange = true;
13122 return EverMadeChange;
13123}
13124
13125FunctionPass *llvm::createInstructionCombiningPass() {
13126 return new InstCombiner();
13127}