blob: 16e5ce07c349389dd2bcfbb92b71986fff81e8c7 [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"
39#include "llvm/Pass.h"
40#include "llvm/DerivedTypes.h"
41#include "llvm/GlobalVariable.h"
42#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000061#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include <sstream>
63using namespace llvm;
64using namespace llvm::PatternMatch;
65
66STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72namespace {
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
79 TargetData *TD;
80 bool MustPreserveLCSSA;
81 public:
82 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
109
110
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 UI != UE; ++UI)
118 AddToWorkList(cast<Instruction>(*UI));
119 }
120
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 AddToWorkList(Op);
128 }
129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif17396002008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
Gabor Greif17396002008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
145
146 return R;
147 }
148
149 public:
150 virtual bool runOnFunction(Function &F);
151
152 bool DoOneIteration(Function &F, unsigned ItNum);
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
158 }
159
160 TargetData &getTargetData() const { return *TD; }
161
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
168 //
169 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000170 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000172 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000174 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 Instruction *visitURem(BinaryOperator &I);
176 Instruction *visitSRem(BinaryOperator &I);
177 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000178 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 Instruction *commonRemTransforms(BinaryOperator &I);
180 Instruction *commonIRemTransforms(BinaryOperator &I);
181 Instruction *commonDivTransforms(BinaryOperator &I);
182 Instruction *commonIDivTransforms(BinaryOperator &I);
183 Instruction *visitUDiv(BinaryOperator &I);
184 Instruction *visitSDiv(BinaryOperator &I);
185 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000186 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000188 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000189 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000190 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 Instruction *visitOr (BinaryOperator &I);
192 Instruction *visitXor(BinaryOperator &I);
193 Instruction *visitShl(BinaryOperator &I);
194 Instruction *visitAShr(BinaryOperator &I);
195 Instruction *visitLShr(BinaryOperator &I);
196 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000197 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 Instruction *visitFCmpInst(FCmpInst &I);
200 Instruction *visitICmpInst(ICmpInst &I);
201 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
202 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203 Instruction *LHS,
204 ConstantInt *RHS);
205 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206 ConstantInt *DivRHS);
207
208 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209 ICmpInst::Predicate Cond, Instruction &I);
210 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
211 BinaryOperator &I);
212 Instruction *commonCastTransforms(CastInst &CI);
213 Instruction *commonIntCastTransforms(CastInst &CI);
214 Instruction *commonPointerCastTransforms(CastInst &CI);
215 Instruction *visitTrunc(TruncInst &CI);
216 Instruction *visitZExt(ZExtInst &CI);
217 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000218 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000220 Instruction *visitFPToUI(FPToUIInst &FI);
221 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 Instruction *visitUIToFP(CastInst &CI);
223 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000224 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000225 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 Instruction *visitBitCast(BitCastInst &CI);
227 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000229 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000230 Instruction *visitSelectInst(SelectInst &SI);
231 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 Instruction *visitCallInst(CallInst &CI);
233 Instruction *visitInvokeInst(InvokeInst &II);
234 Instruction *visitPHINode(PHINode &PN);
235 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
236 Instruction *visitAllocationInst(AllocationInst &AI);
237 Instruction *visitFreeInst(FreeInst &FI);
238 Instruction *visitLoadInst(LoadInst &LI);
239 Instruction *visitStoreInst(StoreInst &SI);
240 Instruction *visitBranchInst(BranchInst &BI);
241 Instruction *visitSwitchInst(SwitchInst &SI);
242 Instruction *visitInsertElementInst(InsertElementInst &IE);
243 Instruction *visitExtractElementInst(ExtractElementInst &EI);
244 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000245 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246
247 // visitInstruction - Specify what to return for unhandled instructions...
248 Instruction *visitInstruction(Instruction &I) { return 0; }
249
250 private:
251 Instruction *visitCallSite(CallSite CS);
252 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000253 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000254 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000256 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000257 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259
260 public:
261 // InsertNewInstBefore - insert an instruction New before instruction Old
262 // in the program. Add the new instruction to the worklist.
263 //
264 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
265 assert(New && New->getParent() == 0 &&
266 "New instruction already inserted into a basic block!");
267 BasicBlock *BB = Old.getParent();
268 BB->getInstList().insert(&Old, New); // Insert inst
269 AddToWorkList(New);
270 return New;
271 }
272
273 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274 /// This also adds the cast to the worklist. Finally, this returns the
275 /// cast.
276 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277 Instruction &Pos) {
278 if (V->getType() == Ty) return V;
279
280 if (Constant *CV = dyn_cast<Constant>(V))
281 return ConstantExpr::getCast(opc, CV, Ty);
282
Gabor Greifa645dd32008-05-16 19:29:10 +0000283 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 AddToWorkList(C);
285 return C;
286 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000287
288 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290 }
291
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292
293 // ReplaceInstUsesWith - This method is to be used when an instruction is
294 // found to be dead, replacable with another preexisting expression. Here
295 // we add all uses of I to the worklist, replace all uses of I with the new
296 // value, then return I, so that the inst combiner will know that I was
297 // modified.
298 //
299 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
300 AddUsersToWorkList(I); // Add all modified instrs to worklist
301 if (&I != V) {
302 I.replaceAllUsesWith(V);
303 return &I;
304 } else {
305 // If we are replacing the instruction with itself, this must be in a
306 // segment of unreachable code, so just clobber the instruction.
307 I.replaceAllUsesWith(UndefValue::get(I.getType()));
308 return &I;
309 }
310 }
311
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
319 RemoveFromWorkList(&I);
320 I.eraseFromParent();
321 return 0; // Don't do anything with FI
322 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000323
324 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325 APInt &KnownOne, unsigned Depth = 0) const {
326 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327 }
328
329 bool MaskedValueIsZero(Value *V, const APInt &Mask,
330 unsigned Depth = 0) const {
331 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332 }
333 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334 return llvm::ComputeNumSignBits(Op, TD, Depth);
335 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
337 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338
339 /// SimplifyCommutative - This performs a few simplifications for
340 /// commutative operators.
341 bool SimplifyCommutative(BinaryOperator &I);
342
343 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344 /// most-complex to least-complex order.
345 bool SimplifyCompare(CmpInst &I);
346
Chris Lattner676c78e2009-01-31 08:15:18 +0000347 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348 /// based on the demanded bits.
349 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
350 APInt& KnownZero, APInt& KnownOne,
351 unsigned Depth);
352 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000354 unsigned Depth=0);
355
356 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357 /// SimplifyDemandedBits knows about. See if the instruction has any
358 /// properties that allow us to simplify its operands.
359 bool SimplifyDemandedInstructionBits(Instruction &Inst);
360
Evan Cheng63295ab2009-02-03 10:05:09 +0000361 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363
364 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365 // PHI node as operand #0, see if we can fold the instruction into the PHI
366 // (which is only possible if all operands to the PHI are constants).
367 Instruction *FoldOpIntoPhi(Instruction &I);
368
369 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370 // operator and they all are only used by the PHI, PHI together their
371 // inputs, and do the operation once, to the result of the PHI.
372 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
373 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000374 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376
377 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378 ConstantInt *AndRHS, BinaryOperator &TheAnd);
379
380 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
381 bool isSub, Instruction &I);
382 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
383 bool isSigned, bool Inside, Instruction &IB);
384 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
385 Instruction *MatchBSwap(BinaryOperator &I);
386 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000387 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000388 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000389
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390
391 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000392
Dan Gohman8fd520a2009-06-15 22:12:54 +0000393 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000394 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000395 unsigned GetOrEnforceKnownAlignment(Value *V,
396 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000397
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399}
400
Dan Gohman089efff2008-05-13 00:00:25 +0000401char InstCombiner::ID = 0;
402static RegisterPass<InstCombiner>
403X("instcombine", "Combine redundant instructions");
404
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405// getComplexity: Assign a complexity or rank value to LLVM Values...
406// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
407static unsigned getComplexity(Value *V) {
408 if (isa<Instruction>(V)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +0000409 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 return 3;
412 return 4;
413 }
414 if (isa<Argument>(V)) return 3;
415 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
416}
417
418// isOnlyUse - Return true if this instruction will be deleted if we stop using
419// it.
420static bool isOnlyUse(Value *V) {
421 return V->hasOneUse() || isa<Constant>(V);
422}
423
424// getPromotedType - Return the specified type promoted as it would be to pass
425// though a va_arg area...
426static const Type *getPromotedType(const Type *Ty) {
427 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428 if (ITy->getBitWidth() < 32)
429 return Type::Int32Ty;
430 }
431 return Ty;
432}
433
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000434/// getBitCastOperand - If the specified operand is a CastInst, a constant
435/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000439 // BitCastInst?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 return I->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000441 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442 // GetElementPtrInst?
443 if (GEP->hasAllZeroIndices())
444 return GEP->getOperand(0);
445 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000447 // BitCast ConstantExp?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 return CE->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000449 else if (CE->getOpcode() == Instruction::GetElementPtr) {
450 // GetElementPtr ConstantExp?
451 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452 I != E; ++I) {
453 ConstantInt *CI = dyn_cast<ConstantInt>(I);
454 if (!CI || !CI->isZero())
455 // Any non-zero indices? Not cast-like.
456 return 0;
457 }
458 // All-zero indices? This is just like casting.
459 return CE->getOperand(0);
460 }
461 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 return 0;
463}
464
465/// This function is a wrapper around CastInst::isEliminableCastPair. It
466/// simply extracts arguments and returns what that function returns.
467static Instruction::CastOps
468isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
473) {
474
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
477
478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
481
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000482 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483 DstTy, TD->getIntPtrType());
484
485 // We don't want to form an inttoptr or ptrtoint that converts to an integer
486 // type that differs from the pointer size.
487 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489 Res = 0;
490
491 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492}
493
494/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495/// in any code being generated. It does not require codegen if V is simple
496/// enough or if the cast can be folded into other casts.
497static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
498 const Type *Ty, TargetData *TD) {
499 if (V->getType() == Ty || isa<Constant>(V)) return false;
500
501 // If this is another cast that can be eliminated, it isn't codegen either.
502 if (const CastInst *CI = dyn_cast<CastInst>(V))
503 if (isEliminableCastPair(CI, opcode, Ty, TD))
504 return false;
505 return true;
506}
507
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508// SimplifyCommutative - This performs a few simplifications for commutative
509// operators:
510//
511// 1. Order operands such that they are listed from right (least complex) to
512// left (most complex). This puts constants before unary operators before
513// binary operators.
514//
515// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
517//
518bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
519 bool Changed = false;
520 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521 Changed = !I.swapOperands();
522
523 if (!I.isAssociative()) return Changed;
524 Instruction::BinaryOps Opcode = I.getOpcode();
525 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527 if (isa<Constant>(I.getOperand(1))) {
528 Constant *Folded = ConstantExpr::get(I.getOpcode(),
529 cast<Constant>(I.getOperand(1)),
530 cast<Constant>(Op->getOperand(1)));
531 I.setOperand(0, Op->getOperand(0));
532 I.setOperand(1, Folded);
533 return true;
534 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536 isOnlyUse(Op) && isOnlyUse(Op1)) {
537 Constant *C1 = cast<Constant>(Op->getOperand(1));
538 Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
541 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000542 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 Op1->getOperand(0),
544 Op1->getName(), &I);
545 AddToWorkList(New);
546 I.setOperand(0, New);
547 I.setOperand(1, Folded);
548 return true;
549 }
550 }
551 return Changed;
552}
553
554/// SimplifyCompare - For a CmpInst this function just orders the operands
555/// so that theyare listed from right (least complex) to left (most complex).
556/// This puts constants before unary operators before binary operators.
557bool InstCombiner::SimplifyCompare(CmpInst &I) {
558 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559 return false;
560 I.swapOperands();
561 // Compare instructions are not associative so there's nothing else we can do.
562 return true;
563}
564
565// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566// if the LHS is a constant zero (which is the 'negate' form).
567//
568static inline Value *dyn_castNegVal(Value *V) {
569 if (BinaryOperator::isNeg(V))
570 return BinaryOperator::getNegArgument(V);
571
572 // Constants can be considered to be negated values if they can be folded.
573 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000575
576 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577 if (C->getType()->getElementType()->isInteger())
578 return ConstantExpr::getNeg(C);
579
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580 return 0;
581}
582
Dan Gohman7ce405e2009-06-04 22:49:04 +0000583// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584// instruction if the LHS is a constant negative zero (which is the 'negate'
585// form).
586//
587static inline Value *dyn_castFNegVal(Value *V) {
588 if (BinaryOperator::isFNeg(V))
589 return BinaryOperator::getFNegArgument(V);
590
591 // Constants can be considered to be negated values if they can be folded.
592 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593 return ConstantExpr::getFNeg(C);
594
595 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596 if (C->getType()->getElementType()->isFloatingPoint())
597 return ConstantExpr::getFNeg(C);
598
599 return 0;
600}
601
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602static inline Value *dyn_castNotVal(Value *V) {
603 if (BinaryOperator::isNot(V))
604 return BinaryOperator::getNotArgument(V);
605
606 // Constants can be considered to be not'ed values...
607 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
608 return ConstantInt::get(~C->getValue());
609 return 0;
610}
611
612// dyn_castFoldableMul - If this value is a multiply that can be folded into
613// other computations (because it has a constant operand), return the
614// non-constant operand of the multiply, and set CST to point to the multiplier.
615// Otherwise, return null.
616//
617static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
618 if (V->hasOneUse() && V->getType()->isInteger())
619 if (Instruction *I = dyn_cast<Instruction>(V)) {
620 if (I->getOpcode() == Instruction::Mul)
621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
622 return I->getOperand(0);
623 if (I->getOpcode() == Instruction::Shl)
624 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
625 // The multiplier is really 1 << CST.
626 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
627 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
628 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
629 return I->getOperand(0);
630 }
631 }
632 return 0;
633}
634
635/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636/// expression, return it.
637static User *dyn_castGetElementPtr(Value *V) {
638 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640 if (CE->getOpcode() == Instruction::GetElementPtr)
641 return cast<User>(V);
642 return false;
643}
644
Dan Gohman2d648bb2008-04-10 18:43:06 +0000645/// getOpcode - If this is an Instruction or a ConstantExpr, return the
646/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000647static unsigned getOpcode(const Value *V) {
648 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000649 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000650 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000651 return CE->getOpcode();
652 // Use UserOp1 to mean there's no opcode.
653 return Instruction::UserOp1;
654}
655
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656/// AddOne - Add one to a ConstantInt
Dan Gohman8fd520a2009-06-15 22:12:54 +0000657static Constant *AddOne(Constant *C) {
658 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659}
660/// SubOne - Subtract one from a ConstantInt
Dan Gohman8fd520a2009-06-15 22:12:54 +0000661static Constant *SubOne(ConstantInt *C) {
662 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000664/// MultiplyOverflows - True if the multiply can not be expressed in an int
665/// this size.
666static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
667 uint32_t W = C1->getBitWidth();
668 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
669 if (sign) {
670 LHSExt.sext(W * 2);
671 RHSExt.sext(W * 2);
672 } else {
673 LHSExt.zext(W * 2);
674 RHSExt.zext(W * 2);
675 }
676
677 APInt MulExt = LHSExt * RHSExt;
678
679 if (sign) {
680 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
681 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
682 return MulExt.slt(Min) || MulExt.sgt(Max);
683 } else
684 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
685}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687
688/// ShrinkDemandedConstant - Check to see if the specified operand of the
689/// specified instruction is a constant integer. If so, check to see if there
690/// are any bits set in the constant that are not demanded. If so, shrink the
691/// constant and return true.
692static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
693 APInt Demanded) {
694 assert(I && "No instruction?");
695 assert(OpNo < I->getNumOperands() && "Operand index too large");
696
697 // If the operand is not a constant integer, nothing to do.
698 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
699 if (!OpC) return false;
700
701 // If there are no bits set that aren't demanded, nothing to do.
702 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
703 if ((~Demanded & OpC->getValue()) == 0)
704 return false;
705
706 // This instruction is producing bits that are not demanded. Shrink the RHS.
707 Demanded &= OpC->getValue();
708 I->setOperand(OpNo, ConstantInt::get(Demanded));
709 return true;
710}
711
712// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
713// set of known zero and one bits, compute the maximum and minimum values that
714// could have the specified known zero and known one bits, returning them in
715// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000716static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 const APInt& KnownOne,
718 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000719 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
720 KnownZero.getBitWidth() == Min.getBitWidth() &&
721 KnownZero.getBitWidth() == Max.getBitWidth() &&
722 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 APInt UnknownBits = ~(KnownZero|KnownOne);
724
725 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
726 // bit if it is unknown.
727 Min = KnownOne;
728 Max = KnownOne|UnknownBits;
729
Dan Gohman7934d592009-04-25 17:12:48 +0000730 if (UnknownBits.isNegative()) { // Sign bit is unknown
731 Min.set(Min.getBitWidth()-1);
732 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 }
734}
735
736// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
737// a set of known zero and one bits, compute the maximum and minimum values that
738// could have the specified known zero and known one bits, returning them in
739// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000740static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000741 const APInt &KnownOne,
742 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000743 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
744 KnownZero.getBitWidth() == Min.getBitWidth() &&
745 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
747 APInt UnknownBits = ~(KnownZero|KnownOne);
748
749 // The minimum value is when the unknown bits are all zeros.
750 Min = KnownOne;
751 // The maximum value is when the unknown bits are all ones.
752 Max = KnownOne|UnknownBits;
753}
754
Chris Lattner676c78e2009-01-31 08:15:18 +0000755/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
756/// SimplifyDemandedBits knows about. See if the instruction has any
757/// properties that allow us to simplify its operands.
758bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000759 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000760 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
761 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
762
763 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
764 KnownZero, KnownOne, 0);
765 if (V == 0) return false;
766 if (V == &Inst) return true;
767 ReplaceInstUsesWith(Inst, V);
768 return true;
769}
770
771/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
772/// specified instruction operand if possible, updating it in place. It returns
773/// true if it made any change and false otherwise.
774bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
775 APInt &KnownZero, APInt &KnownOne,
776 unsigned Depth) {
777 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
778 KnownZero, KnownOne, Depth);
779 if (NewVal == 0) return false;
780 U.set(NewVal);
781 return true;
782}
783
784
785/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
786/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787/// that only the bits set in DemandedMask of the result of V are ever used
788/// downstream. Consequently, depending on the mask and V, it may be possible
789/// to replace V with a constant or one of its operands. In such cases, this
790/// function does the replacement and returns true. In all other cases, it
791/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000792/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793/// to be zero in the expression. These are provided to potentially allow the
794/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
795/// the expression. KnownOne and KnownZero always follow the invariant that
796/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
797/// the bits in KnownOne and KnownZero may only be accurate for those bits set
798/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
799/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000800///
801/// This returns null if it did not change anything and it permits no
802/// simplification. This returns V itself if it did some simplification of V's
803/// operands based on the information about what bits are demanded. This returns
804/// some other non-null value if it found out that V is equal to another value
805/// in the context where the specified bits are demanded, but not for all users.
806Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
807 APInt &KnownZero, APInt &KnownOne,
808 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809 assert(V != 0 && "Null pointer of Value???");
810 assert(Depth <= 6 && "Limit Search Depth");
811 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000812 const Type *VTy = V->getType();
813 assert((TD || !isa<PointerType>(VTy)) &&
814 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000815 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
816 (!VTy->isIntOrIntVector() ||
817 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000818 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000820 "Value *V, DemandedMask, KnownZero and KnownOne "
821 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000826 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 }
Dan Gohman7934d592009-04-25 17:12:48 +0000828 if (isa<ConstantPointerNull>(V)) {
829 // We know all of the bits for a constant!
830 KnownOne.clear();
831 KnownZero = DemandedMask;
832 return 0;
833 }
834
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000835 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000837 if (DemandedMask == 0) { // Not demanding any bits from V.
838 if (isa<UndefValue>(V))
839 return 0;
840 return UndefValue::get(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 }
842
Chris Lattner08817332009-01-31 08:24:16 +0000843 if (Depth == 6) // Limit search depth.
844 return 0;
845
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000846 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
847 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
848
Dan Gohman7934d592009-04-25 17:12:48 +0000849 Instruction *I = dyn_cast<Instruction>(V);
850 if (!I) {
851 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
852 return 0; // Only analyze instructions.
853 }
854
Chris Lattner08817332009-01-31 08:24:16 +0000855 // If there are multiple uses of this value and we aren't at the root, then
856 // we can't do any simplifications of the operands, because DemandedMask
857 // only reflects the bits demanded by *one* of the users.
858 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000859 // Despite the fact that we can't simplify this instruction in all User's
860 // context, we can at least compute the knownzero/knownone bits, and we can
861 // do simplifications that apply to *just* the one user if we know that
862 // this instruction has a simpler value in that context.
863 if (I->getOpcode() == Instruction::And) {
864 // If either the LHS or the RHS are Zero, the result is zero.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
868 LHSKnownZero, LHSKnownOne, Depth+1);
869
870 // If all of the demanded bits are known 1 on one side, return the other.
871 // These bits cannot contribute to the result of the 'and' in this
872 // context.
873 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
874 (DemandedMask & ~LHSKnownZero))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
877 (DemandedMask & ~RHSKnownZero))
878 return I->getOperand(1);
879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
882 return Constant::getNullValue(VTy);
883
884 } else if (I->getOpcode() == Instruction::Or) {
885 // We can simplify (X|Y) -> X or Y in the user's context if we know that
886 // only bits from X or Y are demanded.
887
888 // If either the LHS or the RHS are One, the result is One.
889 ComputeMaskedBits(I->getOperand(1), DemandedMask,
890 RHSKnownZero, RHSKnownOne, Depth+1);
891 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
892 LHSKnownZero, LHSKnownOne, Depth+1);
893
894 // If all of the demanded bits are known zero on one side, return the
895 // other. These bits cannot contribute to the result of the 'or' in this
896 // context.
897 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
898 (DemandedMask & ~LHSKnownOne))
899 return I->getOperand(0);
900 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
901 (DemandedMask & ~RHSKnownOne))
902 return I->getOperand(1);
903
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
907 (DemandedMask & (~RHSKnownZero)))
908 return I->getOperand(0);
909 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
910 (DemandedMask & (~LHSKnownZero)))
911 return I->getOperand(1);
912 }
913
Chris Lattner08817332009-01-31 08:24:16 +0000914 // Compute the KnownZero/KnownOne bits to simplify things downstream.
915 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
916 return 0;
917 }
918
919 // If this is the root being simplified, allow it to have multiple uses,
920 // just set the DemandedMask to all bits so that we can try to simplify the
921 // operands. This allows visitTruncInst (for example) to simplify the
922 // operand of a trunc without duplicating all the logic below.
923 if (Depth == 0 && !V->hasOneUse())
924 DemandedMask = APInt::getAllOnesValue(BitWidth);
925
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000927 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000928 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000929 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 case Instruction::And:
931 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000932 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
933 RHSKnownZero, RHSKnownOne, Depth+1) ||
934 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000936 return I;
937 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
938 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939
940 // If all of the demanded bits are known 1 on one side, return the other.
941 // These bits cannot contribute to the result of the 'and'.
942 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
943 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000944 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
946 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000947 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948
949 // If all of the demanded bits in the inputs are known zeros, return zero.
950 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +0000951 return Constant::getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952
953 // If the RHS is a constant, see if we can simplify it.
954 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000955 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956
957 // Output known-1 bits are only known if set in both the LHS & RHS.
958 RHSKnownOne &= LHSKnownOne;
959 // Output known-0 are known to be clear if zero in either the LHS | RHS.
960 RHSKnownZero |= LHSKnownZero;
961 break;
962 case Instruction::Or:
963 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000964 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
965 RHSKnownZero, RHSKnownOne, Depth+1) ||
966 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000968 return I;
969 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
970 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971
972 // If all of the demanded bits are known zero on one side, return the other.
973 // These bits cannot contribute to the result of the 'or'.
974 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
975 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000976 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
978 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000979 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980
981 // If all of the potentially set bits on one side are known to be set on
982 // the other side, just use the 'other' side.
983 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
984 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000985 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
987 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000988 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989
990 // If the RHS is a constant, see if we can simplify it.
991 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +0000992 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
994 // Output known-0 bits are only known if clear in both the LHS & RHS.
995 RHSKnownZero &= LHSKnownZero;
996 // Output known-1 are known to be set if set in either the LHS | RHS.
997 RHSKnownOne |= LHSKnownOne;
998 break;
999 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001000 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001 RHSKnownZero, RHSKnownOne, Depth+1) ||
1002 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001004 return I;
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1006 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007
1008 // If all of the demanded bits are known zero on one side, return the other.
1009 // These bits cannot contribute to the result of the 'xor'.
1010 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001011 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001013 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014
1015 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1016 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1017 (RHSKnownOne & LHSKnownOne);
1018 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1019 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1020 (RHSKnownOne & LHSKnownZero);
1021
1022 // If all of the demanded bits are known to be zero on one side or the
1023 // other, turn this into an *inclusive* or.
1024 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1025 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1026 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001027 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001029 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 }
1031
1032 // If all of the demanded bits on one side are known, and all of the set
1033 // bits on that side are also known to be set on the other side, turn this
1034 // into an AND, as we know the bits will be cleared.
1035 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1036 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1037 // all known
1038 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1039 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1040 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001041 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001042 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044 }
1045
1046 // If the RHS is a constant, see if we can simplify it.
1047 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner676c78e2009-01-31 08:15:18 +00001049 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001050
1051 RHSKnownZero = KnownZeroOut;
1052 RHSKnownOne = KnownOneOut;
1053 break;
1054 }
1055 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063
1064 // If the operands are constants, see if we can simplify them.
Chris Lattner676c78e2009-01-31 08:15:18 +00001065 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066 ShrinkDemandedConstant(I, 2, DemandedMask))
1067 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068
1069 // Only known if known in both the LHS and RHS.
1070 RHSKnownOne &= LHSKnownOne;
1071 RHSKnownZero &= LHSKnownZero;
1072 break;
1073 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001074 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001075 DemandedMask.zext(truncBf);
1076 RHSKnownZero.zext(truncBf);
1077 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001080 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 DemandedMask.trunc(BitWidth);
1082 RHSKnownZero.trunc(BitWidth);
1083 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 break;
1086 }
1087 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001088 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001089 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001090
1091 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1092 if (const VectorType *SrcVTy =
1093 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1094 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1095 // Don't touch a bitcast between vectors of different element counts.
1096 return false;
1097 } else
1098 // Don't touch a scalar-to-vector bitcast.
1099 return false;
1100 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1101 // Don't touch a vector-to-scalar bitcast.
1102 return false;
1103
Chris Lattner676c78e2009-01-31 08:15:18 +00001104 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001106 return I;
1107 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 break;
1109 case Instruction::ZExt: {
1110 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001111 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112
1113 DemandedMask.trunc(SrcBitWidth);
1114 RHSKnownZero.trunc(SrcBitWidth);
1115 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001116 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001118 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 DemandedMask.zext(BitWidth);
1120 RHSKnownZero.zext(BitWidth);
1121 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001122 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 // The top bits are known to be zero.
1124 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1125 break;
1126 }
1127 case Instruction::SExt: {
1128 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001129 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130
1131 APInt InputDemandedBits = DemandedMask &
1132 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1133
1134 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1135 // If any of the sign extended bits are demanded, we know that the sign
1136 // bit is demanded.
1137 if ((NewBits & DemandedMask) != 0)
1138 InputDemandedBits.set(SrcBitWidth-1);
1139
1140 InputDemandedBits.trunc(SrcBitWidth);
1141 RHSKnownZero.trunc(SrcBitWidth);
1142 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001143 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001145 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 InputDemandedBits.zext(BitWidth);
1147 RHSKnownZero.zext(BitWidth);
1148 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001149 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150
1151 // If the sign bit of the input is known set or clear, then we know the
1152 // top bits of the result.
1153
1154 // If the input sign bit is known zero, or if the NewBits are not demanded
1155 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001156 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001157 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001158 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1159 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1161 RHSKnownOne |= NewBits;
1162 }
1163 break;
1164 }
1165 case Instruction::Add: {
1166 // Figure out what the input bits are. If the top bits of the and result
1167 // are not demanded, then the add doesn't demand them from its input
1168 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001169 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170
1171 // If there is a constant on the RHS, there are a variety of xformations
1172 // we can do.
1173 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174 // If null, this should be simplified elsewhere. Some of the xforms here
1175 // won't work if the RHS is zero.
1176 if (RHS->isZero())
1177 break;
1178
1179 // If the top bit of the output is demanded, demand everything from the
1180 // input. Otherwise, we demand all the input bits except NLZ top bits.
1181 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1182
1183 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001184 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001185 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001186 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187
1188 // If the RHS of the add has bits set that can't affect the input, reduce
1189 // the constant.
1190 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner676c78e2009-01-31 08:15:18 +00001191 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192
1193 // Avoid excess work.
1194 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1195 break;
1196
1197 // Turn it into OR if input bits are zero.
1198 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1199 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001200 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001202 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 }
1204
1205 // We can say something about the output known-zero and known-one bits,
1206 // depending on potential carries from the input constant and the
1207 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1208 // bits set and the RHS constant is 0x01001, then we know we have a known
1209 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1210
1211 // To compute this, we first compute the potential carry bits. These are
1212 // the bits which may be modified. I'm not aware of a better way to do
1213 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001214 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1216
1217 // Now that we know which bits have carries, compute the known-1/0 sets.
1218
1219 // Bits are known one if they are known zero in one operand and one in the
1220 // other, and there is no input carry.
1221 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1222 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1223
1224 // Bits are known zero if they are known zero in both operands and there
1225 // is no input carry.
1226 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1227 } else {
1228 // If the high-bits of this ADD are not demanded, then it does not demand
1229 // the high bits of its LHS or RHS.
1230 if (DemandedMask[BitWidth-1] == 0) {
1231 // Right fill the mask of bits for this ADD to demand the most
1232 // significant bit and all those below it.
1233 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001234 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1235 LHSKnownZero, LHSKnownOne, Depth+1) ||
1236 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001238 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 }
1240 }
1241 break;
1242 }
1243 case Instruction::Sub:
1244 // If the high-bits of this SUB are not demanded, then it does not demand
1245 // the high bits of its LHS or RHS.
1246 if (DemandedMask[BitWidth-1] == 0) {
1247 // Right fill the mask of bits for this SUB to demand the most
1248 // significant bit and all those below it.
1249 uint32_t NLZ = DemandedMask.countLeadingZeros();
1250 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1252 LHSKnownZero, LHSKnownOne, Depth+1) ||
1253 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001255 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001257 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1258 // the known zeros and ones.
1259 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 break;
1261 case Instruction::Shl:
1262 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1263 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1264 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001265 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001267 return I;
1268 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 RHSKnownZero <<= ShiftAmt;
1270 RHSKnownOne <<= ShiftAmt;
1271 // low bits known zero.
1272 if (ShiftAmt)
1273 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1274 }
1275 break;
1276 case Instruction::LShr:
1277 // For a logical shift right
1278 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1279 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1280
1281 // Unsigned shift right.
1282 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001283 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001285 return I;
1286 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1288 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1289 if (ShiftAmt) {
1290 // Compute the new bits that are at the top now.
1291 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1292 RHSKnownZero |= HighBits; // high bits known zero.
1293 }
1294 }
1295 break;
1296 case Instruction::AShr:
1297 // If this is an arithmetic shift right and only the low-bit is set, we can
1298 // always convert this into a logical shr, even if the shift amount is
1299 // variable. The low bit of the shift cannot be an input sign bit unless
1300 // the shift amount is >= the size of the datatype, which is undefined.
1301 if (DemandedMask == 1) {
1302 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001303 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001305 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 }
1307
1308 // If the sign bit is the only bit demanded by this ashr, then there is no
1309 // need to do it, the shift doesn't change the high bit.
1310 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001311 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312
1313 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1314 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1315
1316 // Signed shift right.
1317 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1318 // If any of the "high bits" are demanded, we should set the sign bit as
1319 // demanded.
1320 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1321 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001322 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001324 return I;
1325 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 // Compute the new bits that are at the top now.
1327 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1328 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1329 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1330
1331 // Handle the sign bits.
1332 APInt SignBit(APInt::getSignBit(BitWidth));
1333 // Adjust to where it is now in the mask.
1334 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1335
1336 // If the input sign bit is known to be zero, or if none of the top bits
1337 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001338 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 (HighBits & ~DemandedMask) == HighBits) {
1340 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001341 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001343 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1345 RHSKnownOne |= HighBits;
1346 }
1347 }
1348 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001349 case Instruction::SRem:
1350 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001351 APInt RA = Rem->getValue().abs();
1352 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001353 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001354 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001355
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001356 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001357 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001358 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001359 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001360 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001361
1362 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1363 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001364
1365 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001366
Chris Lattner676c78e2009-01-31 08:15:18 +00001367 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001368 }
1369 }
1370 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001371 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001372 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1373 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001374 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1375 KnownZero2, KnownOne2, Depth+1) ||
1376 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001377 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001378 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001379
Chris Lattneree5417c2009-01-21 18:09:24 +00001380 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001381 Leaders = std::max(Leaders,
1382 KnownZero2.countLeadingOnes());
1383 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001384 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 }
Chris Lattner989ba312008-06-18 04:33:20 +00001386 case Instruction::Call:
1387 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1388 switch (II->getIntrinsicID()) {
1389 default: break;
1390 case Intrinsic::bswap: {
1391 // If the only bits demanded come from one byte of the bswap result,
1392 // just shift the input byte into position to eliminate the bswap.
1393 unsigned NLZ = DemandedMask.countLeadingZeros();
1394 unsigned NTZ = DemandedMask.countTrailingZeros();
1395
1396 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1397 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1398 // have 14 leading zeros, round to 8.
1399 NLZ &= ~7;
1400 NTZ &= ~7;
1401 // If we need exactly one byte, we can do this transformation.
1402 if (BitWidth-NLZ-NTZ == 8) {
1403 unsigned ResultBit = NTZ;
1404 unsigned InputBit = BitWidth-NTZ-8;
1405
1406 // Replace this with either a left or right shift to get the byte into
1407 // the right place.
1408 Instruction *NewVal;
1409 if (InputBit > ResultBit)
1410 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1411 ConstantInt::get(I->getType(), InputBit-ResultBit));
1412 else
1413 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1414 ConstantInt::get(I->getType(), ResultBit-InputBit));
1415 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001416 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001417 }
1418
1419 // TODO: Could compute known zero/one bits based on the input.
1420 break;
1421 }
1422 }
1423 }
Chris Lattner4946e222008-06-18 18:11:55 +00001424 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001425 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427
1428 // If the client is only demanding bits that we know, return the known
1429 // constant.
Dan Gohman7934d592009-04-25 17:12:48 +00001430 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1431 Constant *C = ConstantInt::get(RHSKnownOne);
1432 if (isa<PointerType>(V->getType()))
1433 C = ConstantExpr::getIntToPtr(C, V->getType());
1434 return C;
1435 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 return false;
1437}
1438
1439
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001440/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001441/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442/// actually used by the caller. This method analyzes which elements of the
1443/// operand are undef and returns that information in UndefElts.
1444///
1445/// If the information about demanded elements can be used to simplify the
1446/// operation, the operation is simplified, then the resultant value is
1447/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001448Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1449 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 unsigned Depth) {
1451 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001452 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001453 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454
1455 if (isa<UndefValue>(V)) {
1456 // If the entire vector is undefined, just return this info.
1457 UndefElts = EltMask;
1458 return 0;
1459 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1460 UndefElts = EltMask;
1461 return UndefValue::get(V->getType());
1462 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001463
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 UndefElts = 0;
1465 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1466 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1467 Constant *Undef = UndefValue::get(EltTy);
1468
1469 std::vector<Constant*> Elts;
1470 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001471 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001473 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001474 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1475 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001476 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 } else { // Otherwise, defined.
1478 Elts.push_back(CP->getOperand(i));
1479 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001480
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001481 // If we changed the constant, return it.
1482 Constant *NewCP = ConstantVector::get(Elts);
1483 return NewCP != CP ? NewCP : 0;
1484 } else if (isa<ConstantAggregateZero>(V)) {
1485 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1486 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001487
1488 // Check if this is identity. If so, return 0 since we are not simplifying
1489 // anything.
1490 if (DemandedElts == ((1ULL << VWidth) -1))
1491 return 0;
1492
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1494 Constant *Zero = Constant::getNullValue(EltTy);
1495 Constant *Undef = UndefValue::get(EltTy);
1496 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001497 for (unsigned i = 0; i != VWidth; ++i) {
1498 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1499 Elts.push_back(Elt);
1500 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501 UndefElts = DemandedElts ^ EltMask;
1502 return ConstantVector::get(Elts);
1503 }
1504
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001505 // Limit search depth.
1506 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001507 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001508
1509 // If multiple users are using the root value, procede with
1510 // simplification conservatively assuming that all elements
1511 // are needed.
1512 if (!V->hasOneUse()) {
1513 // Quit if we find multiple users of a non-root value though.
1514 // They'll be handled when it's their turn to be visited by
1515 // the main instcombine process.
1516 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001518 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001519
1520 // Conservatively assume that all elements are needed.
1521 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522 }
1523
1524 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001525 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526
1527 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001528 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529 Value *TmpV;
1530 switch (I->getOpcode()) {
1531 default: break;
1532
1533 case Instruction::InsertElement: {
1534 // If this is a variable index, we don't know which element it overwrites.
1535 // demand exactly the same input as we produce.
1536 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1537 if (Idx == 0) {
1538 // Note that we can't propagate undef elt info, because we don't know
1539 // which elt is getting updated.
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541 UndefElts2, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543 break;
1544 }
1545
1546 // If this is inserting an element that isn't demanded, remove this
1547 // insertelement.
1548 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001549 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550 return AddSoonDeadInstToWorklist(*I, 0);
1551
1552 // Otherwise, the element inserted overwrites whatever was there, so the
1553 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001554 APInt DemandedElts2 = DemandedElts;
1555 DemandedElts2.clear(IdxNo);
1556 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557 UndefElts, Depth+1);
1558 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1559
1560 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001561 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001562 break;
1563 }
1564 case Instruction::ShuffleVector: {
1565 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001566 uint64_t LHSVWidth =
1567 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001568 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001569 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001570 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001571 unsigned MaskVal = Shuffle->getMaskValue(i);
1572 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001573 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001574 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001575 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001576 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001577 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001578 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001579 }
1580 }
1581 }
1582
Nate Begemanb4d176f2009-02-11 22:36:25 +00001583 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001584 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001585 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001586 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1587
Nate Begemanb4d176f2009-02-11 22:36:25 +00001588 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001589 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1590 UndefElts3, Depth+1);
1591 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1592
1593 bool NewUndefElts = false;
1594 for (unsigned i = 0; i < VWidth; i++) {
1595 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001596 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001597 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001598 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001599 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001600 NewUndefElts = true;
1601 UndefElts.set(i);
1602 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001603 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001604 if (UndefElts3[MaskVal - LHSVWidth]) {
1605 NewUndefElts = true;
1606 UndefElts.set(i);
1607 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001608 }
1609 }
1610
1611 if (NewUndefElts) {
1612 // Add additional discovered undefs.
1613 std::vector<Constant*> Elts;
1614 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001615 if (UndefElts[i])
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001616 Elts.push_back(UndefValue::get(Type::Int32Ty));
1617 else
1618 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1619 Shuffle->getMaskValue(i)));
1620 }
1621 I->setOperand(2, ConstantVector::get(Elts));
1622 MadeChange = true;
1623 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624 break;
1625 }
1626 case Instruction::BitCast: {
1627 // Vector->vector casts only.
1628 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1629 if (!VTy) break;
1630 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001631 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001632 unsigned Ratio;
1633
1634 if (VWidth == InVWidth) {
1635 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1636 // elements as are demanded of us.
1637 Ratio = 1;
1638 InputDemandedElts = DemandedElts;
1639 } else if (VWidth > InVWidth) {
1640 // Untested so far.
1641 break;
1642
1643 // If there are more elements in the result than there are in the source,
1644 // then an input element is live if any of the corresponding output
1645 // elements are live.
1646 Ratio = VWidth/InVWidth;
1647 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001648 if (DemandedElts[OutIdx])
1649 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650 }
1651 } else {
1652 // Untested so far.
1653 break;
1654
1655 // If there are more elements in the source than there are in the result,
1656 // then an input element is live if the corresponding output element is
1657 // live.
1658 Ratio = InVWidth/VWidth;
1659 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001660 if (DemandedElts[InIdx/Ratio])
1661 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001662 }
1663
1664 // div/rem demand all inputs, because they don't want divide by zero.
1665 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1666 UndefElts2, Depth+1);
1667 if (TmpV) {
1668 I->setOperand(0, TmpV);
1669 MadeChange = true;
1670 }
1671
1672 UndefElts = UndefElts2;
1673 if (VWidth > InVWidth) {
1674 assert(0 && "Unimp");
1675 // If there are more elements in the result than there are in the source,
1676 // then an output element is undef if the corresponding input element is
1677 // undef.
1678 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001679 if (UndefElts2[OutIdx/Ratio])
1680 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681 } else if (VWidth < InVWidth) {
1682 assert(0 && "Unimp");
1683 // If there are more elements in the source than there are in the result,
1684 // then a result element is undef if all of the corresponding input
1685 // elements are undef.
1686 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1687 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001688 if (!UndefElts2[InIdx]) // Not undef?
1689 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690 }
1691 break;
1692 }
1693 case Instruction::And:
1694 case Instruction::Or:
1695 case Instruction::Xor:
1696 case Instruction::Add:
1697 case Instruction::Sub:
1698 case Instruction::Mul:
1699 // div/rem demand all inputs, because they don't want divide by zero.
1700 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1701 UndefElts, Depth+1);
1702 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1703 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1704 UndefElts2, Depth+1);
1705 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1706
1707 // Output elements are undefined if both are undefined. Consider things
1708 // like undef&0. The result is known zero, not undef.
1709 UndefElts &= UndefElts2;
1710 break;
1711
1712 case Instruction::Call: {
1713 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1714 if (!II) break;
1715 switch (II->getIntrinsicID()) {
1716 default: break;
1717
1718 // Binary vector operations that work column-wise. A dest element is a
1719 // function of the corresponding input elements from the two inputs.
1720 case Intrinsic::x86_sse_sub_ss:
1721 case Intrinsic::x86_sse_mul_ss:
1722 case Intrinsic::x86_sse_min_ss:
1723 case Intrinsic::x86_sse_max_ss:
1724 case Intrinsic::x86_sse2_sub_sd:
1725 case Intrinsic::x86_sse2_mul_sd:
1726 case Intrinsic::x86_sse2_min_sd:
1727 case Intrinsic::x86_sse2_max_sd:
1728 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1729 UndefElts, Depth+1);
1730 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1731 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1732 UndefElts2, Depth+1);
1733 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1734
1735 // If only the low elt is demanded and this is a scalarizable intrinsic,
1736 // scalarize it now.
1737 if (DemandedElts == 1) {
1738 switch (II->getIntrinsicID()) {
1739 default: break;
1740 case Intrinsic::x86_sse_sub_ss:
1741 case Intrinsic::x86_sse_mul_ss:
1742 case Intrinsic::x86_sse2_sub_sd:
1743 case Intrinsic::x86_sse2_mul_sd:
1744 // TODO: Lower MIN/MAX/ABS/etc
1745 Value *LHS = II->getOperand(1);
1746 Value *RHS = II->getOperand(2);
1747 // Extract the element as scalars.
1748 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1749 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1750
1751 switch (II->getIntrinsicID()) {
1752 default: assert(0 && "Case stmts out of sync!");
1753 case Intrinsic::x86_sse_sub_ss:
1754 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001755 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001756 II->getName()), *II);
1757 break;
1758 case Intrinsic::x86_sse_mul_ss:
1759 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001760 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761 II->getName()), *II);
1762 break;
1763 }
1764
1765 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001766 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1767 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768 InsertNewInstBefore(New, *II);
1769 AddSoonDeadInstToWorklist(*II, 0);
1770 return New;
1771 }
1772 }
1773
1774 // Output elements are undefined if both are undefined. Consider things
1775 // like undef&0. The result is known zero, not undef.
1776 UndefElts &= UndefElts2;
1777 break;
1778 }
1779 break;
1780 }
1781 }
1782 return MadeChange ? I : 0;
1783}
1784
Dan Gohman5d56fd42008-05-19 22:14:15 +00001785
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786/// AssociativeOpt - Perform an optimization on an associative operator. This
1787/// function is designed to check a chain of associative operators for a
1788/// potential to apply a certain optimization. Since the optimization may be
1789/// applicable if the expression was reassociated, this checks the chain, then
1790/// reassociates the expression as necessary to expose the optimization
1791/// opportunity. This makes use of a special Functor, which must define
1792/// 'shouldApply' and 'apply' methods.
1793///
1794template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001795static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 unsigned Opcode = Root.getOpcode();
1797 Value *LHS = Root.getOperand(0);
1798
1799 // Quick check, see if the immediate LHS matches...
1800 if (F.shouldApply(LHS))
1801 return F.apply(Root);
1802
1803 // Otherwise, if the LHS is not of the same opcode as the root, return.
1804 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1805 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1806 // Should we apply this transform to the RHS?
1807 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1808
1809 // If not to the RHS, check to see if we should apply to the LHS...
1810 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1811 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1812 ShouldApply = true;
1813 }
1814
1815 // If the functor wants to apply the optimization to the RHS of LHSI,
1816 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1817 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001818 // Now all of the instructions are in the current basic block, go ahead
1819 // and perform the reassociation.
1820 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1821
1822 // First move the selected RHS to the LHS of the root...
1823 Root.setOperand(0, LHSI->getOperand(1));
1824
1825 // Make what used to be the LHS of the root be the user of the root...
1826 Value *ExtraOperand = TmpLHSI->getOperand(1);
1827 if (&Root == TmpLHSI) {
1828 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1829 return 0;
1830 }
1831 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1832 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001833 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001834 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 ARI = Root;
1836
1837 // Now propagate the ExtraOperand down the chain of instructions until we
1838 // get to LHSI.
1839 while (TmpLHSI != LHSI) {
1840 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1841 // Move the instruction to immediately before the chain we are
1842 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001843 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001844 ARI = NextLHSI;
1845
1846 Value *NextOp = NextLHSI->getOperand(1);
1847 NextLHSI->setOperand(1, ExtraOperand);
1848 TmpLHSI = NextLHSI;
1849 ExtraOperand = NextOp;
1850 }
1851
1852 // Now that the instructions are reassociated, have the functor perform
1853 // the transformation...
1854 return F.apply(Root);
1855 }
1856
1857 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1858 }
1859 return 0;
1860}
1861
Dan Gohman089efff2008-05-13 00:00:25 +00001862namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863
Nick Lewycky27f6c132008-05-23 04:34:58 +00001864// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001865struct AddRHS {
1866 Value *RHS;
1867 AddRHS(Value *rhs) : RHS(rhs) {}
1868 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1869 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001870 return BinaryOperator::CreateShl(Add.getOperand(0),
1871 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 }
1873};
1874
1875// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1876// iff C1&C2 == 0
1877struct AddMaskingAnd {
1878 Constant *C2;
1879 AddMaskingAnd(Constant *c) : C2(c) {}
1880 bool shouldApply(Value *LHS) const {
1881 ConstantInt *C1;
1882 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1883 ConstantExpr::getAnd(C1, C2)->isNullValue();
1884 }
1885 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001886 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001887 }
1888};
1889
Dan Gohman089efff2008-05-13 00:00:25 +00001890}
1891
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1893 InstCombiner *IC) {
1894 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001895 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 }
1897
1898 // Figure out if the constant is the left or the right argument.
1899 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1900 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1901
1902 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1903 if (ConstIsRHS)
1904 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1905 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1906 }
1907
1908 Value *Op0 = SO, *Op1 = ConstOperand;
1909 if (!ConstIsRHS)
1910 std::swap(Op0, Op1);
1911 Instruction *New;
1912 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001913 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001914 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001915 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001916 SO->getName()+".cmp");
1917 else {
1918 assert(0 && "Unknown binary instruction type!");
1919 abort();
1920 }
1921 return IC->InsertNewInstBefore(New, I);
1922}
1923
1924// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1925// constant as the other operand, try to fold the binary operator into the
1926// select arguments. This also works for Cast instructions, which obviously do
1927// not have a second operand.
1928static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1929 InstCombiner *IC) {
1930 // Don't modify shared select instructions
1931 if (!SI->hasOneUse()) return 0;
1932 Value *TV = SI->getOperand(1);
1933 Value *FV = SI->getOperand(2);
1934
1935 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1936 // Bool selects with constant operands can be folded to logical ops.
1937 if (SI->getType() == Type::Int1Ty) return 0;
1938
1939 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1940 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1941
Gabor Greifd6da1d02008-04-06 20:25:17 +00001942 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1943 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001944 }
1945 return 0;
1946}
1947
1948
1949/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1950/// node as operand #0, see if we can fold the instruction into the PHI (which
1951/// is only possible if all operands to the PHI are constants).
1952Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1953 PHINode *PN = cast<PHINode>(I.getOperand(0));
1954 unsigned NumPHIValues = PN->getNumIncomingValues();
1955 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1956
1957 // Check to see if all of the operands of the PHI are constants. If there is
1958 // one non-constant value, remember the BB it is. If there is more than one
1959 // or if *it* is a PHI, bail out.
1960 BasicBlock *NonConstBB = 0;
1961 for (unsigned i = 0; i != NumPHIValues; ++i)
1962 if (!isa<Constant>(PN->getIncomingValue(i))) {
1963 if (NonConstBB) return 0; // More than one non-const value.
1964 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1965 NonConstBB = PN->getIncomingBlock(i);
1966
1967 // If the incoming non-constant value is in I's block, we have an infinite
1968 // loop.
1969 if (NonConstBB == I.getParent())
1970 return 0;
1971 }
1972
1973 // If there is exactly one non-constant value, we can insert a copy of the
1974 // operation in that block. However, if this is a critical edge, we would be
1975 // inserting the computation one some other paths (e.g. inside a loop). Only
1976 // do this if the pred block is unconditionally branching into the phi block.
1977 if (NonConstBB) {
1978 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1979 if (!BI || !BI->isUnconditional()) return 0;
1980 }
1981
1982 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001983 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1985 InsertNewInstBefore(NewPN, *PN);
1986 NewPN->takeName(PN);
1987
1988 // Next, add all of the operands to the PHI.
1989 if (I.getNumOperands() == 2) {
1990 Constant *C = cast<Constant>(I.getOperand(1));
1991 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001992 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1994 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1995 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1996 else
1997 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1998 } else {
1999 assert(PN->getIncomingBlock(i) == NonConstBB);
2000 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002001 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002002 PN->getIncomingValue(i), C, "phitmp",
2003 NonConstBB->getTerminator());
2004 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002005 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002006 CI->getPredicate(),
2007 PN->getIncomingValue(i), C, "phitmp",
2008 NonConstBB->getTerminator());
2009 else
2010 assert(0 && "Unknown binop!");
2011
2012 AddToWorkList(cast<Instruction>(InV));
2013 }
2014 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2015 }
2016 } else {
2017 CastInst *CI = cast<CastInst>(&I);
2018 const Type *RetTy = CI->getType();
2019 for (unsigned i = 0; i != NumPHIValues; ++i) {
2020 Value *InV;
2021 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2022 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2023 } else {
2024 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002025 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026 I.getType(), "phitmp",
2027 NonConstBB->getTerminator());
2028 AddToWorkList(cast<Instruction>(InV));
2029 }
2030 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2031 }
2032 }
2033 return ReplaceInstUsesWith(I, NewPN);
2034}
2035
Chris Lattner55476162008-01-29 06:52:45 +00002036
Chris Lattner3554f972008-05-20 05:46:13 +00002037/// WillNotOverflowSignedAdd - Return true if we can prove that:
2038/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2039/// This basically requires proving that the add in the original type would not
2040/// overflow to change the sign bit or have a carry out.
2041bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2042 // There are different heuristics we can use for this. Here are some simple
2043 // ones.
2044
2045 // Add has the property that adding any two 2's complement numbers can only
2046 // have one carry bit which can change a sign. As such, if LHS and RHS each
2047 // have at least two sign bits, we know that the addition of the two values will
2048 // sign extend fine.
2049 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2050 return true;
2051
2052
2053 // If one of the operands only has one non-zero bit, and if the other operand
2054 // has a known-zero bit in a more significant place than it (not including the
2055 // sign bit) the ripple may go up to and fill the zero, but won't change the
2056 // sign. For example, (X & ~4) + 1.
2057
2058 // TODO: Implement.
2059
2060 return false;
2061}
2062
Chris Lattner55476162008-01-29 06:52:45 +00002063
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002064Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2065 bool Changed = SimplifyCommutative(I);
2066 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2067
2068 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2069 // X + undef -> undef
2070 if (isa<UndefValue>(RHS))
2071 return ReplaceInstUsesWith(I, RHS);
2072
2073 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002074 if (RHSC->isNullValue())
2075 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076
2077 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2078 // X + (signbit) --> X ^ signbit
2079 const APInt& Val = CI->getValue();
2080 uint32_t BitWidth = Val.getBitWidth();
2081 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002082 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002083
2084 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2085 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002086 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002087 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002088
2089 // zext(i1) - 1 -> select i1, 0, -1
2090 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2091 if (CI->isAllOnesValue() &&
2092 ZI->getOperand(0)->getType() == Type::Int1Ty)
2093 return SelectInst::Create(ZI->getOperand(0),
2094 Constant::getNullValue(I.getType()),
2095 ConstantInt::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002096 }
2097
2098 if (isa<PHINode>(LHS))
2099 if (Instruction *NV = FoldOpIntoPhi(I))
2100 return NV;
2101
2102 ConstantInt *XorRHS = 0;
2103 Value *XorLHS = 0;
2104 if (isa<ConstantInt>(RHSC) &&
2105 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002106 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2108
2109 uint32_t Size = TySizeBits / 2;
2110 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2111 APInt CFF80Val(-C0080Val);
2112 do {
2113 if (TySizeBits > Size) {
2114 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2115 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2116 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2117 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2118 // This is a sign extend if the top bits are known zero.
2119 if (!MaskedValueIsZero(XorLHS,
2120 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2121 Size = 0; // Not a sign ext, but can't be any others either.
2122 break;
2123 }
2124 }
2125 Size >>= 1;
2126 C0080Val = APIntOps::lshr(C0080Val, Size);
2127 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2128 } while (Size >= 1);
2129
2130 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002131 // with funny bit widths then this switch statement should be removed. It
2132 // is just here to get the size of the "middle" type back up to something
2133 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002134 const Type *MiddleType = 0;
2135 switch (Size) {
2136 default: break;
2137 case 32: MiddleType = Type::Int32Ty; break;
2138 case 16: MiddleType = Type::Int16Ty; break;
2139 case 8: MiddleType = Type::Int8Ty; break;
2140 }
2141 if (MiddleType) {
2142 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2143 InsertNewInstBefore(NewTrunc, I);
2144 return new SExtInst(NewTrunc, I.getType(), I.getName());
2145 }
2146 }
2147 }
2148
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002149 if (I.getType() == Type::Int1Ty)
2150 return BinaryOperator::CreateXor(LHS, RHS);
2151
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002152 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002153 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2155
2156 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2157 if (RHSI->getOpcode() == Instruction::Sub)
2158 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2159 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2160 }
2161 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2162 if (LHSI->getOpcode() == Instruction::Sub)
2163 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2164 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2165 }
2166 }
2167
2168 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002169 // -A + -B --> -(A + B)
2170 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002171 if (LHS->getType()->isIntOrIntVector()) {
2172 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002173 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002174 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002175 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002176 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002177 }
2178
Gabor Greifa645dd32008-05-16 19:29:10 +00002179 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002180 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181
2182 // A + -B --> A - B
2183 if (!isa<Constant>(RHS))
2184 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002185 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002186
2187
2188 ConstantInt *C2;
2189 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2190 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002191 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002192
2193 // X*C1 + X*C2 --> X * (C1+C2)
2194 ConstantInt *C1;
2195 if (X == dyn_castFoldableMul(RHS, C1))
Dan Gohman8fd520a2009-06-15 22:12:54 +00002196 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002197 }
2198
2199 // X + X*C --> X * (C+1)
2200 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002201 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202
2203 // X + ~X --> -1 since ~X = -X-1
2204 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2205 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2206
2207
2208 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2209 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2210 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2211 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002212
2213 // A+B --> A|B iff A and B have no bits set in common.
2214 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2215 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2216 APInt LHSKnownOne(IT->getBitWidth(), 0);
2217 APInt LHSKnownZero(IT->getBitWidth(), 0);
2218 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2219 if (LHSKnownZero != 0) {
2220 APInt RHSKnownOne(IT->getBitWidth(), 0);
2221 APInt RHSKnownZero(IT->getBitWidth(), 0);
2222 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2223
2224 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002225 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002226 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002227 }
2228 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002229
Nick Lewycky83598a72008-02-03 07:42:09 +00002230 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002231 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002232 Value *W, *X, *Y, *Z;
2233 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2234 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2235 if (W != Y) {
2236 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002237 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002238 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002239 std::swap(W, X);
2240 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002241 std::swap(Y, Z);
2242 std::swap(W, X);
2243 }
2244 }
2245
2246 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002247 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002248 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002249 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002250 }
2251 }
2252 }
2253
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002254 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2255 Value *X = 0;
2256 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002257 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258
2259 // (X & FF00) + xx00 -> (X+xx00) & FF00
2260 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002261 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002262 if (Anded == CRHS) {
2263 // See if all bits from the first bit set in the Add RHS up are included
2264 // in the mask. First, get the rightmost bit.
2265 const APInt& AddRHSV = CRHS->getValue();
2266
2267 // Form a mask of all bits from the lowest bit added through the top.
2268 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2269
2270 // See if the and mask includes all of these bits.
2271 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2272
2273 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2274 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002275 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002276 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002278 }
2279 }
2280 }
2281
2282 // Try to fold constant add into select arguments.
2283 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2284 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2285 return R;
2286 }
2287
2288 // add (cast *A to intptrtype) B ->
Dan Gohman9e1657f2009-06-14 23:30:43 +00002289 // cast (GEP (cast *A to i8*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002290 {
2291 CastInst *CI = dyn_cast<CastInst>(LHS);
2292 Value *Other = RHS;
2293 if (!CI) {
2294 CI = dyn_cast<CastInst>(RHS);
2295 Other = LHS;
2296 }
2297 if (CI && CI->getType()->isSized() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00002298 (CI->getType()->getScalarSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299 TD->getIntPtrType()->getPrimitiveSizeInBits())
2300 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002301 unsigned AS =
2302 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002303 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2304 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002305 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002306 return new PtrToIntInst(I2, CI->getType());
2307 }
2308 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002309
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002310 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002311 {
2312 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002313 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002314 if (!SI) {
2315 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002316 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002317 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002318 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002319 Value *TV = SI->getTrueValue();
2320 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002321 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002322
2323 // Can we fold the add into the argument of the select?
2324 // We check both true and false select arguments for a matching subtract.
Chris Lattner641ea462008-11-16 04:46:19 +00002325 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2326 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002327 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner641ea462008-11-16 04:46:19 +00002328 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2329 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002330 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002331 }
2332 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002333
Chris Lattner3554f972008-05-20 05:46:13 +00002334 // Check for (add (sext x), y), see if we can merge this into an
2335 // integer add followed by a sext.
2336 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2337 // (add (sext x), cst) --> (sext (add x, cst'))
2338 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2339 Constant *CI =
2340 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2341 if (LHSConv->hasOneUse() &&
2342 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2343 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2344 // Insert the new, smaller add.
2345 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2346 CI, "addconv");
2347 InsertNewInstBefore(NewAdd, I);
2348 return new SExtInst(NewAdd, I.getType());
2349 }
2350 }
2351
2352 // (add (sext x), (sext y)) --> (sext (add int x, y))
2353 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2354 // Only do this if x/y have the same type, if at last one of them has a
2355 // single use (so we don't increase the number of sexts), and if the
2356 // integer add will not overflow.
2357 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2358 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2359 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2360 RHSConv->getOperand(0))) {
2361 // Insert the new integer add.
2362 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2363 RHSConv->getOperand(0),
2364 "addconv");
2365 InsertNewInstBefore(NewAdd, I);
2366 return new SExtInst(NewAdd, I.getType());
2367 }
2368 }
2369 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002370
2371 return Changed ? &I : 0;
2372}
2373
2374Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2375 bool Changed = SimplifyCommutative(I);
2376 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2377
2378 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2379 // X + 0 --> X
2380 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2381 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2382 (I.getType())->getValueAPF()))
2383 return ReplaceInstUsesWith(I, LHS);
2384 }
2385
2386 if (isa<PHINode>(LHS))
2387 if (Instruction *NV = FoldOpIntoPhi(I))
2388 return NV;
2389 }
2390
2391 // -A + B --> B - A
2392 // -A + -B --> -(A + B)
2393 if (Value *LHSV = dyn_castFNegVal(LHS))
2394 return BinaryOperator::CreateFSub(RHS, LHSV);
2395
2396 // A + -B --> A - B
2397 if (!isa<Constant>(RHS))
2398 if (Value *V = dyn_castFNegVal(RHS))
2399 return BinaryOperator::CreateFSub(LHS, V);
2400
2401 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2402 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2403 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2404 return ReplaceInstUsesWith(I, LHS);
2405
Chris Lattner3554f972008-05-20 05:46:13 +00002406 // Check for (add double (sitofp x), y), see if we can merge this into an
2407 // integer add followed by a promotion.
2408 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2409 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2410 // ... if the constant fits in the integer value. This is useful for things
2411 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2412 // requires a constant pool load, and generally allows the add to be better
2413 // instcombined.
2414 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2415 Constant *CI =
2416 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2417 if (LHSConv->hasOneUse() &&
2418 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2419 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2420 // Insert the new integer add.
2421 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2422 CI, "addconv");
2423 InsertNewInstBefore(NewAdd, I);
2424 return new SIToFPInst(NewAdd, I.getType());
2425 }
2426 }
2427
2428 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2429 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2430 // Only do this if x/y have the same type, if at last one of them has a
2431 // single use (so we don't increase the number of int->fp conversions),
2432 // and if the integer add will not overflow.
2433 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2434 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2435 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2436 RHSConv->getOperand(0))) {
2437 // Insert the new integer add.
2438 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2439 RHSConv->getOperand(0),
2440 "addconv");
2441 InsertNewInstBefore(NewAdd, I);
2442 return new SIToFPInst(NewAdd, I.getType());
2443 }
2444 }
2445 }
2446
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002447 return Changed ? &I : 0;
2448}
2449
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002450Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2451 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2452
Dan Gohman7ce405e2009-06-04 22:49:04 +00002453 if (Op0 == Op1) // sub X, X -> 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002454 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2455
2456 // If this is a 'B = x-(-A)', change to B = x+A...
2457 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002458 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459
2460 if (isa<UndefValue>(Op0))
2461 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2462 if (isa<UndefValue>(Op1))
2463 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2464
2465 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2466 // Replace (-1 - A) with (~A)...
2467 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002468 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002469
2470 // C - ~X == X + (1+C)
2471 Value *X = 0;
2472 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002473 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002474
2475 // -(X >>u 31) -> (X >>s 31)
2476 // -(X >>s 31) -> (X >>u 31)
2477 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002478 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002479 if (SI->getOpcode() == Instruction::LShr) {
2480 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2481 // Check to see if we are shifting out everything but the sign bit.
2482 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2483 SI->getType()->getPrimitiveSizeInBits()-1) {
2484 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002485 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486 SI->getOperand(0), CU, SI->getName());
2487 }
2488 }
2489 }
2490 else if (SI->getOpcode() == Instruction::AShr) {
2491 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2492 // Check to see if we are shifting out everything but the sign bit.
2493 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2494 SI->getType()->getPrimitiveSizeInBits()-1) {
2495 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002496 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002497 SI->getOperand(0), CU, SI->getName());
2498 }
2499 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002500 }
2501 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002502 }
2503
2504 // Try to fold constant sub into select arguments.
2505 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2506 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2507 return R;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002508 }
2509
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002510 if (I.getType() == Type::Int1Ty)
2511 return BinaryOperator::CreateXor(Op0, Op1);
2512
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002513 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002514 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002518 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2520 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2521 // C1-(X+C2) --> (C1-C2)-X
Dan Gohman8fd520a2009-06-15 22:12:54 +00002522 return BinaryOperator::CreateSub(ConstantExpr::getSub(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002523 Op1I->getOperand(0));
2524 }
2525 }
2526
2527 if (Op1I->hasOneUse()) {
2528 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2529 // is not used by anyone else...
2530 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002531 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002532 // Swap the two operands of the subexpr...
2533 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2534 Op1I->setOperand(0, IIOp1);
2535 Op1I->setOperand(1, IIOp0);
2536
2537 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002539 }
2540
2541 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2542 //
2543 if (Op1I->getOpcode() == Instruction::And &&
2544 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2545 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2546
2547 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002548 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2549 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 }
2551
2552 // 0 - (X sdiv C) -> (X sdiv -C)
2553 if (Op1I->getOpcode() == Instruction::SDiv)
2554 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2555 if (CSI->isZero())
2556 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002557 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 ConstantExpr::getNeg(DivRHS));
2559
2560 // X - X*C --> X * (1-C)
2561 ConstantInt *C2 = 0;
2562 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002563 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2564 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002565 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566 }
2567 }
2568 }
2569
Dan Gohman7ce405e2009-06-04 22:49:04 +00002570 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2571 if (Op0I->getOpcode() == Instruction::Add) {
2572 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2573 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2574 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2575 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2576 } else if (Op0I->getOpcode() == Instruction::Sub) {
2577 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2578 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002579 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002580 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002581
2582 ConstantInt *C1;
2583 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2584 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002585 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586
2587 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2588 if (X == dyn_castFoldableMul(Op1, C2))
Dan Gohman8fd520a2009-06-15 22:12:54 +00002589 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 }
2591 return 0;
2592}
2593
Dan Gohman7ce405e2009-06-04 22:49:04 +00002594Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2595 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2596
2597 // If this is a 'B = x-(-A)', change to B = x+A...
2598 if (Value *V = dyn_castFNegVal(Op1))
2599 return BinaryOperator::CreateFAdd(Op0, V);
2600
2601 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2602 if (Op1I->getOpcode() == Instruction::FAdd) {
2603 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2604 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2605 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2606 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2607 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002608 }
2609
2610 return 0;
2611}
2612
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002613/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2614/// comparison only checks the sign bit. If it only checks the sign bit, set
2615/// TrueIfSigned if the result of the comparison is true when the input value is
2616/// signed.
2617static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2618 bool &TrueIfSigned) {
2619 switch (pred) {
2620 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2621 TrueIfSigned = true;
2622 return RHS->isZero();
2623 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2624 TrueIfSigned = true;
2625 return RHS->isAllOnesValue();
2626 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2627 TrueIfSigned = false;
2628 return RHS->isAllOnesValue();
2629 case ICmpInst::ICMP_UGT:
2630 // True if LHS u> RHS and RHS == high-bit-mask - 1
2631 TrueIfSigned = true;
2632 return RHS->getValue() ==
2633 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2634 case ICmpInst::ICMP_UGE:
2635 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2636 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002637 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 default:
2639 return false;
2640 }
2641}
2642
2643Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2644 bool Changed = SimplifyCommutative(I);
2645 Value *Op0 = I.getOperand(0);
2646
Dan Gohmana22a8402009-06-04 17:12:12 +00002647 // TODO: If Op1 is undef and Op0 is finite, return zero.
2648 if (!I.getType()->isFPOrFPVector() &&
2649 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002650 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2651
2652 // Simplify mul instructions with a constant RHS...
2653 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2654 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2655
2656 // ((X << C1)*C2) == (X * (C2 << C1))
2657 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2658 if (SI->getOpcode() == Instruction::Shl)
2659 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002660 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002661 ConstantExpr::getShl(CI, ShOp));
2662
2663 if (CI->isZero())
2664 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2665 if (CI->equalsInt(1)) // X * 1 == X
2666 return ReplaceInstUsesWith(I, Op0);
2667 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
2670 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2671 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 ConstantInt::get(Op0->getType(), Val.logBase2()));
2674 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002675 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohmana22a8402009-06-04 17:12:12 +00002676 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky94418732008-11-27 20:21:08 +00002677
2678 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2679 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2680 return BinaryOperator::CreateNeg(Op0, I.getName());
2681
2682 // As above, vector X*splat(1.0) -> X in all defined cases.
2683 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002684 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2685 if (CI->equalsInt(1))
2686 return ReplaceInstUsesWith(I, Op0);
2687 }
2688 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002689 }
2690
2691 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2692 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002693 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002694 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002695 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002696 Op1, "tmp");
2697 InsertNewInstBefore(Add, I);
2698 Value *C1C2 = ConstantExpr::getMul(Op1,
2699 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002700 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002701
2702 }
2703
2704 // Try to fold constant mul into select arguments.
2705 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2706 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2707 return R;
2708
2709 if (isa<PHINode>(Op0))
2710 if (Instruction *NV = FoldOpIntoPhi(I))
2711 return NV;
2712 }
2713
2714 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2715 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002716 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717
Nick Lewycky1c246402008-11-21 07:33:58 +00002718 // (X / Y) * Y = X - (X % Y)
2719 // (X / Y) * -Y = (X % Y) - X
2720 {
2721 Value *Op1 = I.getOperand(1);
2722 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2723 if (!BO ||
2724 (BO->getOpcode() != Instruction::UDiv &&
2725 BO->getOpcode() != Instruction::SDiv)) {
2726 Op1 = Op0;
2727 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2728 }
2729 Value *Neg = dyn_castNegVal(Op1);
2730 if (BO && BO->hasOneUse() &&
2731 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2732 (BO->getOpcode() == Instruction::UDiv ||
2733 BO->getOpcode() == Instruction::SDiv)) {
2734 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2735
2736 Instruction *Rem;
2737 if (BO->getOpcode() == Instruction::UDiv)
2738 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2739 else
2740 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2741
2742 InsertNewInstBefore(Rem, I);
2743 Rem->takeName(BO);
2744
2745 if (Op1BO == Op1)
2746 return BinaryOperator::CreateSub(Op0BO, Rem);
2747 else
2748 return BinaryOperator::CreateSub(Rem, Op0BO);
2749 }
2750 }
2751
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002752 if (I.getType() == Type::Int1Ty)
2753 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2754
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755 // If one of the operands of the multiply is a cast from a boolean value, then
2756 // we know the bool is either zero or one, so this is a 'masking' multiply.
2757 // See if we can simplify things based on how the boolean was originally
2758 // formed.
2759 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002760 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2762 BoolCast = CI;
2763 if (!BoolCast)
2764 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2765 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2766 BoolCast = CI;
2767 if (BoolCast) {
2768 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2769 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2770 const Type *SCOpTy = SCIOp0->getType();
2771 bool TIS = false;
2772
2773 // If the icmp is true iff the sign bit of X is set, then convert this
2774 // multiply into a shift/and combination.
2775 if (isa<ConstantInt>(SCIOp1) &&
2776 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2777 TIS) {
2778 // Shift the X value right to turn it into "all signbits".
2779 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2780 SCOpTy->getPrimitiveSizeInBits()-1);
2781 Value *V =
2782 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002783 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002784 BoolCast->getOperand(0)->getName()+
2785 ".mask"), I);
2786
2787 // If the multiply type is not the same as the source type, sign extend
2788 // or truncate to the multiply type.
2789 if (I.getType() != V->getType()) {
2790 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2791 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2792 Instruction::CastOps opcode =
2793 (SrcBits == DstBits ? Instruction::BitCast :
2794 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2795 V = InsertCastBefore(opcode, V, I.getType(), I);
2796 }
2797
2798 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002799 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002800 }
2801 }
2802 }
2803
2804 return Changed ? &I : 0;
2805}
2806
Dan Gohman7ce405e2009-06-04 22:49:04 +00002807Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2808 bool Changed = SimplifyCommutative(I);
2809 Value *Op0 = I.getOperand(0);
2810
2811 // Simplify mul instructions with a constant RHS...
2812 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2813 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2814 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2815 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2816 if (Op1F->isExactlyValue(1.0))
2817 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2818 } else if (isa<VectorType>(Op1->getType())) {
2819 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2820 // As above, vector X*splat(1.0) -> X in all defined cases.
2821 if (Constant *Splat = Op1V->getSplatValue()) {
2822 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2823 if (F->isExactlyValue(1.0))
2824 return ReplaceInstUsesWith(I, Op0);
2825 }
2826 }
2827 }
2828
2829 // Try to fold constant mul into select arguments.
2830 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2831 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2832 return R;
2833
2834 if (isa<PHINode>(Op0))
2835 if (Instruction *NV = FoldOpIntoPhi(I))
2836 return NV;
2837 }
2838
2839 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2840 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2841 return BinaryOperator::CreateFMul(Op0v, Op1v);
2842
2843 return Changed ? &I : 0;
2844}
2845
Chris Lattner76972db2008-07-14 00:15:52 +00002846/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2847/// instruction.
2848bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2849 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2850
2851 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2852 int NonNullOperand = -1;
2853 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2854 if (ST->isNullValue())
2855 NonNullOperand = 2;
2856 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2857 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2858 if (ST->isNullValue())
2859 NonNullOperand = 1;
2860
2861 if (NonNullOperand == -1)
2862 return false;
2863
2864 Value *SelectCond = SI->getOperand(0);
2865
2866 // Change the div/rem to use 'Y' instead of the select.
2867 I.setOperand(1, SI->getOperand(NonNullOperand));
2868
2869 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2870 // problem. However, the select, or the condition of the select may have
2871 // multiple uses. Based on our knowledge that the operand must be non-zero,
2872 // propagate the known value for the select into other uses of it, and
2873 // propagate a known value of the condition into its other users.
2874
2875 // If the select and condition only have a single use, don't bother with this,
2876 // early exit.
2877 if (SI->use_empty() && SelectCond->hasOneUse())
2878 return true;
2879
2880 // Scan the current block backward, looking for other uses of SI.
2881 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2882
2883 while (BBI != BBFront) {
2884 --BBI;
2885 // If we found a call to a function, we can't assume it will return, so
2886 // information from below it cannot be propagated above it.
2887 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2888 break;
2889
2890 // Replace uses of the select or its condition with the known values.
2891 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2892 I != E; ++I) {
2893 if (*I == SI) {
2894 *I = SI->getOperand(NonNullOperand);
2895 AddToWorkList(BBI);
2896 } else if (*I == SelectCond) {
2897 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2898 ConstantInt::getFalse();
2899 AddToWorkList(BBI);
2900 }
2901 }
2902
2903 // If we past the instruction, quit looking for it.
2904 if (&*BBI == SI)
2905 SI = 0;
2906 if (&*BBI == SelectCond)
2907 SelectCond = 0;
2908
2909 // If we ran out of things to eliminate, break out of the loop.
2910 if (SelectCond == 0 && SI == 0)
2911 break;
2912
2913 }
2914 return true;
2915}
2916
2917
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918/// This function implements the transforms on div instructions that work
2919/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2920/// used by the visitors to those instructions.
2921/// @brief Transforms common to all three div instructions
2922Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2924
Chris Lattner653ef3c2008-02-19 06:12:18 +00002925 // undef / X -> 0 for integer.
2926 // undef / X -> undef for FP (the undef could be a snan).
2927 if (isa<UndefValue>(Op0)) {
2928 if (Op0->getType()->isFPOrFPVector())
2929 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002930 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002931 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932
2933 // X / undef -> undef
2934 if (isa<UndefValue>(Op1))
2935 return ReplaceInstUsesWith(I, Op1);
2936
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937 return 0;
2938}
2939
2940/// This function implements the transforms common to both integer division
2941/// instructions (udiv and sdiv). It is called by the visitors to those integer
2942/// division instructions.
2943/// @brief Common integer divide transforms
2944Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2945 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2946
Chris Lattnercefb36c2008-05-16 02:59:42 +00002947 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002948 if (Op0 == Op1) {
2949 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002950 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002951 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2952 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2953 }
2954
Dan Gohman8fd520a2009-06-15 22:12:54 +00002955 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002956 return ReplaceInstUsesWith(I, CI);
2957 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002958
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002959 if (Instruction *Common = commonDivTransforms(I))
2960 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002961
2962 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2963 // This does not apply for fdiv.
2964 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2965 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966
2967 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2968 // div X, 1 == X
2969 if (RHS->equalsInt(1))
2970 return ReplaceInstUsesWith(I, Op0);
2971
2972 // (X / C1) / C2 -> X / (C1*C2)
2973 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2974 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2975 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002976 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2978 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002979 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002980 ConstantExpr::getMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 }
2982
2983 if (!RHS->isZero()) { // avoid X udiv 0
2984 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2986 return R;
2987 if (isa<PHINode>(Op0))
2988 if (Instruction *NV = FoldOpIntoPhi(I))
2989 return NV;
2990 }
2991 }
2992
2993 // 0 / X == 0, we don't need to preserve faults!
2994 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2995 if (LHS->equalsInt(0))
2996 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2997
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002998 // It can't be division by zero, hence it must be division by one.
2999 if (I.getType() == Type::Int1Ty)
3000 return ReplaceInstUsesWith(I, Op0);
3001
Nick Lewycky94418732008-11-27 20:21:08 +00003002 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3003 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3004 // div X, 1 == X
3005 if (X->isOne())
3006 return ReplaceInstUsesWith(I, Op0);
3007 }
3008
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009 return 0;
3010}
3011
3012Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
3015 // Handle the integer div common cases
3016 if (Instruction *Common = commonIDivTransforms(I))
3017 return Common;
3018
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003019 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003020 // X udiv C^2 -> X >> C
3021 // Check to see if this is an unsigned division with an exact power of 2,
3022 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003023 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003024 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003025 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003026
3027 // X udiv C, where C >= signbit
3028 if (C->getValue().isNegative()) {
3029 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3030 I);
3031 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3032 ConstantInt::get(I.getType(), 1));
3033 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003034 }
3035
3036 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3037 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3038 if (RHSI->getOpcode() == Instruction::Shl &&
3039 isa<ConstantInt>(RHSI->getOperand(0))) {
3040 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3041 if (C1.isPowerOf2()) {
3042 Value *N = RHSI->getOperand(1);
3043 const Type *NTy = N->getType();
3044 if (uint32_t C2 = C1.logBase2()) {
3045 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003046 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003048 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003049 }
3050 }
3051 }
3052
3053 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3054 // where C1&C2 are powers of two.
3055 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3056 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3057 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3058 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3059 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3060 // Compute the shift amounts
3061 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3062 // Construct the "on true" case of the select
3063 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003064 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003065 Op0, TC, SI->getName()+".t");
3066 TSI = InsertNewInstBefore(TSI, I);
3067
3068 // Construct the "on false" case of the select
3069 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003070 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003071 Op0, FC, SI->getName()+".f");
3072 FSI = InsertNewInstBefore(FSI, I);
3073
3074 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003075 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003076 }
3077 }
3078 return 0;
3079}
3080
3081Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3082 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3083
3084 // Handle the integer div common cases
3085 if (Instruction *Common = commonIDivTransforms(I))
3086 return Common;
3087
3088 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3089 // sdiv X, -1 == -X
3090 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003091 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003092 }
3093
3094 // If the sign bits of both operands are zero (i.e. we can prove they are
3095 // unsigned inputs), turn this into a udiv.
3096 if (I.getType()->isInteger()) {
3097 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3098 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003099 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003100 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003101 }
3102 }
3103
3104 return 0;
3105}
3106
3107Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3108 return commonDivTransforms(I);
3109}
3110
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003111/// This function implements the transforms on rem instructions that work
3112/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3113/// is used by the visitors to those instructions.
3114/// @brief Transforms common to all three rem instructions
3115Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3117
Chris Lattner653ef3c2008-02-19 06:12:18 +00003118 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3119 if (I.getType()->isFPOrFPVector())
3120 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003122 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003123 if (isa<UndefValue>(Op1))
3124 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3125
3126 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003127 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3128 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003129
3130 return 0;
3131}
3132
3133/// This function implements the transforms common to both integer remainder
3134/// instructions (urem and srem). It is called by the visitors to those integer
3135/// remainder instructions.
3136/// @brief Common integer remainder transforms
3137Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140 if (Instruction *common = commonRemTransforms(I))
3141 return common;
3142
Dale Johannesena51f7372009-01-21 00:35:19 +00003143 // 0 % X == 0 for integer, we don't need to preserve faults!
3144 if (Constant *LHS = dyn_cast<Constant>(Op0))
3145 if (LHS->isNullValue())
3146 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3147
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3149 // X % 0 == undef, we don't need to preserve faults!
3150 if (RHS->equalsInt(0))
3151 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3152
3153 if (RHS->equalsInt(1)) // X % 1 == 0
3154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3155
3156 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159 return R;
3160 } else if (isa<PHINode>(Op0I)) {
3161 if (Instruction *NV = FoldOpIntoPhi(I))
3162 return NV;
3163 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003164
3165 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003166 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003167 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 }
3169 }
3170
3171 return 0;
3172}
3173
3174Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3176
3177 if (Instruction *common = commonIRemTransforms(I))
3178 return common;
3179
3180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3181 // X urem C^2 -> X and C
3182 // Check to see if this is an unsigned remainder with an exact power of 2,
3183 // if so, convert to a bitwise and.
3184 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3185 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003186 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003187 }
3188
3189 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3190 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3191 if (RHSI->getOpcode() == Instruction::Shl &&
3192 isa<ConstantInt>(RHSI->getOperand(0))) {
3193 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3194 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003195 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003196 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003197 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 }
3199 }
3200 }
3201
3202 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3203 // where C1&C2 are powers of two.
3204 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3205 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3206 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3207 // STO == 0 and SFO == 0 handled above.
3208 if ((STO->getValue().isPowerOf2()) &&
3209 (SFO->getValue().isPowerOf2())) {
3210 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003211 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003212 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003213 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003214 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 }
3216 }
3217 }
3218
3219 return 0;
3220}
3221
3222Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3223 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3224
Dan Gohmandb3dd962007-11-05 23:16:33 +00003225 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 if (Instruction *common = commonIRemTransforms(I))
3227 return common;
3228
3229 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003230 if (!isa<Constant>(RHSNeg) ||
3231 (isa<ConstantInt>(RHSNeg) &&
3232 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 // X % -Y -> X % Y
3234 AddUsesToWorkList(I);
3235 I.setOperand(1, RHSNeg);
3236 return &I;
3237 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003238
Dan Gohmandb3dd962007-11-05 23:16:33 +00003239 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003240 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003241 if (I.getType()->isInteger()) {
3242 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3243 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3244 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003245 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003246 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003247 }
3248
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003249 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003250 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3251 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003252
Nick Lewyckyfd746832008-12-20 16:48:00 +00003253 bool hasNegative = false;
3254 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3255 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3256 if (RHS->getValue().isNegative())
3257 hasNegative = true;
3258
3259 if (hasNegative) {
3260 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003261 for (unsigned i = 0; i != VWidth; ++i) {
3262 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3263 if (RHS->getValue().isNegative())
3264 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3265 else
3266 Elts[i] = RHS;
3267 }
3268 }
3269
3270 Constant *NewRHSV = ConstantVector::get(Elts);
3271 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003272 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003273 I.setOperand(1, NewRHSV);
3274 return &I;
3275 }
3276 }
3277 }
3278
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003279 return 0;
3280}
3281
3282Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3283 return commonRemTransforms(I);
3284}
3285
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286// isOneBitSet - Return true if there is exactly one bit set in the specified
3287// constant.
3288static bool isOneBitSet(const ConstantInt *CI) {
3289 return CI->getValue().isPowerOf2();
3290}
3291
3292// isHighOnes - Return true if the constant is of the form 1+0+.
3293// This is the same as lowones(~X).
3294static bool isHighOnes(const ConstantInt *CI) {
3295 return (~CI->getValue() + 1).isPowerOf2();
3296}
3297
3298/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3299/// are carefully arranged to allow folding of expressions such as:
3300///
3301/// (A < B) | (A > B) --> (A != B)
3302///
3303/// Note that this is only valid if the first and second predicates have the
3304/// same sign. Is illegal to do: (A u< B) | (A s> B)
3305///
3306/// Three bits are used to represent the condition, as follows:
3307/// 0 A > B
3308/// 1 A == B
3309/// 2 A < B
3310///
3311/// <=> Value Definition
3312/// 000 0 Always false
3313/// 001 1 A > B
3314/// 010 2 A == B
3315/// 011 3 A >= B
3316/// 100 4 A < B
3317/// 101 5 A != B
3318/// 110 6 A <= B
3319/// 111 7 Always true
3320///
3321static unsigned getICmpCode(const ICmpInst *ICI) {
3322 switch (ICI->getPredicate()) {
3323 // False -> 0
3324 case ICmpInst::ICMP_UGT: return 1; // 001
3325 case ICmpInst::ICMP_SGT: return 1; // 001
3326 case ICmpInst::ICMP_EQ: return 2; // 010
3327 case ICmpInst::ICMP_UGE: return 3; // 011
3328 case ICmpInst::ICMP_SGE: return 3; // 011
3329 case ICmpInst::ICMP_ULT: return 4; // 100
3330 case ICmpInst::ICMP_SLT: return 4; // 100
3331 case ICmpInst::ICMP_NE: return 5; // 101
3332 case ICmpInst::ICMP_ULE: return 6; // 110
3333 case ICmpInst::ICMP_SLE: return 6; // 110
3334 // True -> 7
3335 default:
3336 assert(0 && "Invalid ICmp predicate!");
3337 return 0;
3338 }
3339}
3340
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003341/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3342/// predicate into a three bit mask. It also returns whether it is an ordered
3343/// predicate by reference.
3344static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3345 isOrdered = false;
3346 switch (CC) {
3347 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3348 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003349 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3350 case FCmpInst::FCMP_UGT: return 1; // 001
3351 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3352 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003353 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3354 case FCmpInst::FCMP_UGE: return 3; // 011
3355 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3356 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003357 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3358 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003359 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3360 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003361 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003362 default:
3363 // Not expecting FCMP_FALSE and FCMP_TRUE;
3364 assert(0 && "Unexpected FCmp predicate!");
3365 return 0;
3366 }
3367}
3368
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369/// getICmpValue - This is the complement of getICmpCode, which turns an
3370/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003371/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003372/// of predicate to use in the new icmp instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003373static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3374 switch (code) {
3375 default: assert(0 && "Illegal ICmp code!");
3376 case 0: return ConstantInt::getFalse();
3377 case 1:
3378 if (sign)
3379 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3380 else
3381 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3382 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3383 case 3:
3384 if (sign)
3385 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3386 else
3387 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3388 case 4:
3389 if (sign)
3390 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3391 else
3392 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3393 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3394 case 6:
3395 if (sign)
3396 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3397 else
3398 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3399 case 7: return ConstantInt::getTrue();
3400 }
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,
3407 Value *LHS, Value *RHS) {
3408 switch (code) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00003409 default: assert(0 && "Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003410 case 0:
3411 if (isordered)
3412 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3413 else
3414 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3415 case 1:
3416 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003417 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3418 else
3419 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003420 case 2:
3421 if (isordered)
3422 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3423 else
3424 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003425 case 3:
3426 if (isordered)
3427 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3428 else
3429 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3430 case 4:
3431 if (isordered)
3432 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3433 else
3434 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3435 case 5:
3436 if (isordered)
Evan Chengf1f2cea2008-10-14 18:13:38 +00003437 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3438 else
3439 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3440 case 6:
3441 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003442 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3443 else
3444 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng72988052008-10-14 18:44:08 +00003445 case 7: return ConstantInt::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;
3488 default: assert(0 && "Illegal logical opcode!"); return 0;
3489 }
3490
3491 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3492 ICmpInst::isSignedPredicate(ICI->getPredicate());
3493
3494 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3495 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())
Dan Gohman8fd520a2009-06-15 22:12:54 +00003513 Together = ConstantExpr::getAnd(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));
3579 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3580
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));
3599 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3600
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));
3618 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3619 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) {
3643 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3644 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.
3649 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3650
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);
3655 return new ICmpInst(pred, V, Hi);
3656 }
3657
3658 // Emit V-Lo <u Hi-Lo
3659 Constant *NegLo = ConstantExpr::getNeg(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);
3662 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3663 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3664 }
3665
3666 if (Lo == Hi) // Trivially true.
3667 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3668
3669 // V < Min || V >= Hi -> V > Hi-1
3670 Hi = SubOne(cast<ConstantInt>(Hi));
3671 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3672 ICmpInst::Predicate pred = (isSigned ?
3673 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3674 return new ICmpInst(pred, V, Hi);
3675 }
3676
3677 // Emit V-Lo >u Hi-1-Lo
3678 // Note that Hi has already had one subtracted from it, above.
3679 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(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);
3682 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3683 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3684}
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:
Dan Gohman8fd520a2009-06-15 22:12:54 +00003724 if (ConstantExpr::getAnd(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()
Dan Gohman8fd520a2009-06-15 22:12:54 +00003748 && ConstantExpr::getAnd(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).
Chris Lattner0631ea72008-11-16 05:06:21 +00003769 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerf3803482008-11-16 05:10:52 +00003770 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003771 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003772
3773 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774 // where C is a power of 2
3775 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776 LHSCst->getValue().isPowerOf2()) {
3777 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778 InsertNewInstBefore(NewOr, I);
3779 return new ICmpInst(LHSCC, NewOr, LHSCst);
3780 }
3781
3782 // From here on, we only handle:
3783 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784 if (Val != Val2) return 0;
3785
Chris Lattner0631ea72008-11-16 05:06:21 +00003786 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791 return 0;
3792
3793 // We can't fold (ugt x, C) & (sgt x, C2).
3794 if (!PredicatesFoldable(LHSCC, RHSCC))
3795 return 0;
3796
3797 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003798 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003799 if (ICmpInst::isSignedPredicate(LHSCC) ||
3800 (ICmpInst::isEquality(LHSCC) &&
3801 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003802 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003803 else
Chris Lattner665298f2008-11-16 05:14:43 +00003804 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805
3806 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003807 std::swap(LHS, RHS);
3808 std::swap(LHSCst, RHSCst);
3809 std::swap(LHSCC, RHSCC);
3810 }
3811
3812 // At this point, we know we have have two icmp instructions
3813 // comparing a value against two constants and and'ing the result
3814 // together. Because of the above check, we know that we only have
3815 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3816 // (from the FoldICmpLogical check above), that the two constants
3817 // are not equal and that the larger constant is on the RHS
3818 assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820 switch (LHSCC) {
3821 default: assert(0 && "Unknown integer condition code!");
3822 case ICmpInst::ICMP_EQ:
3823 switch (RHSCC) {
3824 default: assert(0 && "Unknown integer condition code!");
3825 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3826 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3827 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3828 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3829 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3830 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3831 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3832 return ReplaceInstUsesWith(I, LHS);
3833 }
3834 case ICmpInst::ICMP_NE:
3835 switch (RHSCC) {
3836 default: assert(0 && "Unknown integer condition code!");
3837 case ICmpInst::ICMP_ULT:
3838 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3839 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3840 break; // (X != 13 & X u< 15) -> no change
3841 case ICmpInst::ICMP_SLT:
3842 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3843 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3844 break; // (X != 13 & X s< 15) -> no change
3845 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3846 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3847 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3848 return ReplaceInstUsesWith(I, RHS);
3849 case ICmpInst::ICMP_NE:
3850 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3851 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3852 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853 Val->getName()+".off");
3854 InsertNewInstBefore(Add, I);
3855 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3856 ConstantInt::get(Add->getType(), 1));
3857 }
3858 break; // (X != 13 & X != 15) -> no change
3859 }
3860 break;
3861 case ICmpInst::ICMP_ULT:
3862 switch (RHSCC) {
3863 default: assert(0 && "Unknown integer condition code!");
3864 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3865 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3866 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3867 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3868 break;
3869 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3870 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3871 return ReplaceInstUsesWith(I, LHS);
3872 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3873 break;
3874 }
3875 break;
3876 case ICmpInst::ICMP_SLT:
3877 switch (RHSCC) {
3878 default: assert(0 && "Unknown integer condition code!");
3879 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3880 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3881 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3882 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3883 break;
3884 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3885 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3886 return ReplaceInstUsesWith(I, LHS);
3887 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3888 break;
3889 }
3890 break;
3891 case ICmpInst::ICMP_UGT:
3892 switch (RHSCC) {
3893 default: assert(0 && "Unknown integer condition code!");
3894 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3895 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3896 return ReplaceInstUsesWith(I, RHS);
3897 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3898 break;
3899 case ICmpInst::ICMP_NE:
3900 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3901 return new ICmpInst(LHSCC, Val, RHSCst);
3902 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003903 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003904 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3905 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3906 break;
3907 }
3908 break;
3909 case ICmpInst::ICMP_SGT:
3910 switch (RHSCC) {
3911 default: assert(0 && "Unknown integer condition code!");
3912 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3913 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3914 return ReplaceInstUsesWith(I, RHS);
3915 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3916 break;
3917 case ICmpInst::ICMP_NE:
3918 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3919 return new ICmpInst(LHSCC, Val, RHSCst);
3920 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003921 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003922 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3923 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3924 break;
3925 }
3926 break;
3927 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003928
3929 return 0;
3930}
3931
3932
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003933Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3934 bool Changed = SimplifyCommutative(I);
3935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3936
3937 if (isa<UndefValue>(Op1)) // X & undef -> 0
3938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3939
3940 // and X, X = X
3941 if (Op0 == Op1)
3942 return ReplaceInstUsesWith(I, Op1);
3943
3944 // See if we can simplify any instructions used by the instruction whose sole
3945 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003946 if (SimplifyDemandedInstructionBits(I))
3947 return &I;
3948 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003949 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3950 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3951 return ReplaceInstUsesWith(I, I.getOperand(0));
3952 } else if (isa<ConstantAggregateZero>(Op1)) {
3953 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3954 }
3955 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00003956
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003957 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3958 const APInt& AndRHSMask = AndRHS->getValue();
3959 APInt NotAndRHS(~AndRHSMask);
3960
3961 // Optimize a variety of ((val OP C1) & C2) combinations...
3962 if (isa<BinaryOperator>(Op0)) {
3963 Instruction *Op0I = cast<Instruction>(Op0);
3964 Value *Op0LHS = Op0I->getOperand(0);
3965 Value *Op0RHS = Op0I->getOperand(1);
3966 switch (Op0I->getOpcode()) {
3967 case Instruction::Xor:
3968 case Instruction::Or:
3969 // If the mask is only needed on one incoming arm, push it up.
3970 if (Op0I->hasOneUse()) {
3971 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3972 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003973 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003974 Op0RHS->getName()+".masked");
3975 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003976 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003977 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3978 }
3979 if (!isa<Constant>(Op0RHS) &&
3980 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3981 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003982 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003983 Op0LHS->getName()+".masked");
3984 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003985 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003986 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3987 }
3988 }
3989
3990 break;
3991 case Instruction::Add:
3992 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3993 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3994 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3995 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003996 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003997 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003998 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003999 break;
4000
4001 case Instruction::Sub:
4002 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4003 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4004 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4005 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004006 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004007
Nick Lewyckya349ba42008-07-10 05:51:40 +00004008 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4009 // has 1's for all bits that the subtraction with A might affect.
4010 if (Op0I->hasOneUse()) {
4011 uint32_t BitWidth = AndRHSMask.getBitWidth();
4012 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4013 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4014
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004015 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004016 if (!(A && A->isZero()) && // avoid infinite recursion.
4017 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004018 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4019 InsertNewInstBefore(NewNeg, I);
4020 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4021 }
4022 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004023 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004024
4025 case Instruction::Shl:
4026 case Instruction::LShr:
4027 // (1 << x) & 1 --> zext(x == 0)
4028 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004029 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004030 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4031 Constant::getNullValue(I.getType()));
4032 InsertNewInstBefore(NewICmp, I);
4033 return new ZExtInst(NewICmp, I.getType());
4034 }
4035 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004036 }
4037
4038 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4039 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4040 return Res;
4041 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4042 // If this is an integer truncation or change from signed-to-unsigned, and
4043 // if the source is an and/or with immediate, transform it. This
4044 // frequently occurs for bitfield accesses.
4045 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4046 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4047 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004048 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004049 if (CastOp->getOpcode() == Instruction::And) {
4050 // Change: and (cast (and X, C1) to T), C2
4051 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4052 // This will fold the two constants together, which may allow
4053 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004054 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004055 CastOp->getOperand(0), I.getType(),
4056 CastOp->getName()+".shrunk");
4057 NewCast = InsertNewInstBefore(NewCast, I);
4058 // trunc_or_bitcast(C1)&C2
4059 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4060 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004061 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004062 } else if (CastOp->getOpcode() == Instruction::Or) {
4063 // Change: and (cast (or X, C1) to T), C2
4064 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4065 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4066 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4067 return ReplaceInstUsesWith(I, AndRHS);
4068 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004069 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004070 }
4071 }
4072
4073 // Try to fold constant and into select arguments.
4074 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4075 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4076 return R;
4077 if (isa<PHINode>(Op0))
4078 if (Instruction *NV = FoldOpIntoPhi(I))
4079 return NV;
4080 }
4081
4082 Value *Op0NotVal = dyn_castNotVal(Op0);
4083 Value *Op1NotVal = dyn_castNotVal(Op1);
4084
4085 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4086 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4087
4088 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4089 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004090 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004091 I.getName()+".demorgan");
4092 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004093 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004094 }
4095
4096 {
4097 Value *A = 0, *B = 0, *C = 0, *D = 0;
4098 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4099 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4100 return ReplaceInstUsesWith(I, Op1);
4101
4102 // (A|B) & ~(A&B) -> A^B
4103 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4104 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004105 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004106 }
4107 }
4108
4109 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4110 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4111 return ReplaceInstUsesWith(I, Op0);
4112
4113 // ~(A&B) & (A|B) -> A^B
4114 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4115 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004116 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004117 }
4118 }
4119
4120 if (Op0->hasOneUse() &&
4121 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4122 if (A == Op1) { // (A^B)&A -> A&(A^B)
4123 I.swapOperands(); // Simplify below
4124 std::swap(Op0, Op1);
4125 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4126 cast<BinaryOperator>(Op0)->swapOperands();
4127 I.swapOperands(); // Simplify below
4128 std::swap(Op0, Op1);
4129 }
4130 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004131
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004132 if (Op1->hasOneUse() &&
4133 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4134 if (B == Op0) { // B&(A^B) -> B&(B^A)
4135 cast<BinaryOperator>(Op1)->swapOperands();
4136 std::swap(A, B);
4137 }
4138 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00004139 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004140 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004141 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004142 }
4143 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004144
4145 // (A&((~A)|B)) -> A&B
Chris Lattner9db479f2008-12-01 05:16:26 +00004146 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4147 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4148 return BinaryOperator::CreateAnd(A, Op1);
4149 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4150 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4151 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 }
4153
4154 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4155 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4156 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4157 return R;
4158
Chris Lattner0631ea72008-11-16 05:06:21 +00004159 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4160 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4161 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004162 }
4163
4164 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4165 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4166 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4167 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4168 const Type *SrcTy = Op0C->getOperand(0)->getType();
4169 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4170 // Only do this if the casts both really cause code to be generated.
4171 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4172 I.getType(), TD) &&
4173 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4174 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004175 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004176 Op1C->getOperand(0),
4177 I.getName());
4178 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004179 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004180 }
4181 }
4182
4183 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4184 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4185 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4186 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4187 SI0->getOperand(1) == SI1->getOperand(1) &&
4188 (SI0->hasOneUse() || SI1->hasOneUse())) {
4189 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004190 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004191 SI1->getOperand(0),
4192 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004193 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004194 SI1->getOperand(1));
4195 }
4196 }
4197
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004198 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004199 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4200 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4201 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004202 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4203 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner91882432007-10-24 05:38:08 +00004204 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4205 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4206 // If either of the constants are nans, then the whole thing returns
4207 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004208 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004209 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4210 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4211 RHS->getOperand(0));
4212 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004213 } else {
4214 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4215 FCmpInst::Predicate Op0CC, Op1CC;
4216 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4217 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00004218 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4219 // Swap RHS operands to match LHS.
4220 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4221 std::swap(Op1LHS, Op1RHS);
4222 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004223 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4224 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4225 if (Op0CC == Op1CC)
4226 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4227 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4228 Op1CC == FCmpInst::FCMP_FALSE)
4229 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4230 else if (Op0CC == FCmpInst::FCMP_TRUE)
4231 return ReplaceInstUsesWith(I, Op1);
4232 else if (Op1CC == FCmpInst::FCMP_TRUE)
4233 return ReplaceInstUsesWith(I, Op0);
4234 bool Op0Ordered;
4235 bool Op1Ordered;
4236 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4237 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4238 if (Op1Pred == 0) {
4239 std::swap(Op0, Op1);
4240 std::swap(Op0Pred, Op1Pred);
4241 std::swap(Op0Ordered, Op1Ordered);
4242 }
4243 if (Op0Pred == 0) {
4244 // uno && ueq -> uno && (uno || eq) -> ueq
4245 // ord && olt -> ord && (ord && lt) -> olt
4246 if (Op0Ordered == Op1Ordered)
4247 return ReplaceInstUsesWith(I, Op1);
4248 // uno && oeq -> uno && (ord && eq) -> false
4249 // uno && ord -> false
4250 if (!Op0Ordered)
4251 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4252 // ord && ueq -> ord && (uno || eq) -> oeq
4253 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4254 Op0LHS, Op0RHS));
4255 }
4256 }
4257 }
4258 }
Chris Lattner91882432007-10-24 05:38:08 +00004259 }
4260 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004261
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004262 return Changed ? &I : 0;
4263}
4264
Chris Lattner567f5112008-10-05 02:13:19 +00004265/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4266/// capable of providing pieces of a bswap. The subexpression provides pieces
4267/// of a bswap if it is proven that each of the non-zero bytes in the output of
4268/// the expression came from the corresponding "byte swapped" byte in some other
4269/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4270/// we know that the expression deposits the low byte of %X into the high byte
4271/// of the bswap result and that all other bytes are zero. This expression is
4272/// accepted, the high byte of ByteValues is set to X to indicate a correct
4273/// match.
4274///
4275/// This function returns true if the match was unsuccessful and false if so.
4276/// On entry to the function the "OverallLeftShift" is a signed integer value
4277/// indicating the number of bytes that the subexpression is later shifted. For
4278/// example, if the expression is later right shifted by 16 bits, the
4279/// OverallLeftShift value would be -2 on entry. This is used to specify which
4280/// byte of ByteValues is actually being set.
4281///
4282/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4283/// byte is masked to zero by a user. For example, in (X & 255), X will be
4284/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4285/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4286/// always in the local (OverallLeftShift) coordinate space.
4287///
4288static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4289 SmallVector<Value*, 8> &ByteValues) {
4290 if (Instruction *I = dyn_cast<Instruction>(V)) {
4291 // If this is an or instruction, it may be an inner node of the bswap.
4292 if (I->getOpcode() == Instruction::Or) {
4293 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4294 ByteValues) ||
4295 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4296 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004297 }
Chris Lattner567f5112008-10-05 02:13:19 +00004298
4299 // If this is a logical shift by a constant multiple of 8, recurse with
4300 // OverallLeftShift and ByteMask adjusted.
4301 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4302 unsigned ShAmt =
4303 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4304 // Ensure the shift amount is defined and of a byte value.
4305 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4306 return true;
4307
4308 unsigned ByteShift = ShAmt >> 3;
4309 if (I->getOpcode() == Instruction::Shl) {
4310 // X << 2 -> collect(X, +2)
4311 OverallLeftShift += ByteShift;
4312 ByteMask >>= ByteShift;
4313 } else {
4314 // X >>u 2 -> collect(X, -2)
4315 OverallLeftShift -= ByteShift;
4316 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004317 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004318 }
4319
4320 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4321 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4322
4323 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4324 ByteValues);
4325 }
4326
4327 // If this is a logical 'and' with a mask that clears bytes, clear the
4328 // corresponding bytes in ByteMask.
4329 if (I->getOpcode() == Instruction::And &&
4330 isa<ConstantInt>(I->getOperand(1))) {
4331 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4332 unsigned NumBytes = ByteValues.size();
4333 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4334 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4335
4336 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4337 // If this byte is masked out by a later operation, we don't care what
4338 // the and mask is.
4339 if ((ByteMask & (1 << i)) == 0)
4340 continue;
4341
4342 // If the AndMask is all zeros for this byte, clear the bit.
4343 APInt MaskB = AndMask & Byte;
4344 if (MaskB == 0) {
4345 ByteMask &= ~(1U << i);
4346 continue;
4347 }
4348
4349 // If the AndMask is not all ones for this byte, it's not a bytezap.
4350 if (MaskB != Byte)
4351 return true;
4352
4353 // Otherwise, this byte is kept.
4354 }
4355
4356 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4357 ByteValues);
4358 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004359 }
4360
Chris Lattner567f5112008-10-05 02:13:19 +00004361 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4362 // the input value to the bswap. Some observations: 1) if more than one byte
4363 // is demanded from this input, then it could not be successfully assembled
4364 // into a byteswap. At least one of the two bytes would not be aligned with
4365 // their ultimate destination.
4366 if (!isPowerOf2_32(ByteMask)) return true;
4367 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004368
Chris Lattner567f5112008-10-05 02:13:19 +00004369 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4370 // is demanded, it needs to go into byte 0 of the result. This means that the
4371 // byte needs to be shifted until it lands in the right byte bucket. The
4372 // shift amount depends on the position: if the byte is coming from the high
4373 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4374 // low part, it must be shifted left.
4375 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4376 if (InputByteNo < ByteValues.size()/2) {
4377 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4378 return true;
4379 } else {
4380 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4381 return true;
4382 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004383
4384 // If the destination byte value is already defined, the values are or'd
4385 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004386 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004387 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004388 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004389 return false;
4390}
4391
4392/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4393/// If so, insert the new bswap intrinsic and return it.
4394Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4395 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004396 if (!ITy || ITy->getBitWidth() % 16 ||
4397 // ByteMask only allows up to 32-byte values.
4398 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004399 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4400
4401 /// ByteValues - For each byte of the result, we keep track of which value
4402 /// defines each byte.
4403 SmallVector<Value*, 8> ByteValues;
4404 ByteValues.resize(ITy->getBitWidth()/8);
4405
4406 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004407 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4408 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004409 return 0;
4410
4411 // Check to see if all of the bytes come from the same value.
4412 Value *V = ByteValues[0];
4413 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4414
4415 // Check to make sure that all of the bytes come from the same value.
4416 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4417 if (ByteValues[i] != V)
4418 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004419 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004420 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004421 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004422 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004423}
4424
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004425/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4426/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4427/// we can simplify this expression to "cond ? C : D or B".
4428static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4429 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004430 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004431 Value *Cond = 0;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004432 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004433 return 0;
4434
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004435 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004436 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004437 return SelectInst::Create(Cond, C, B);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004438 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004439 return SelectInst::Create(Cond, C, B);
4440 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004441 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004442 return SelectInst::Create(Cond, C, D);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004443 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004444 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004445 return 0;
4446}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447
Chris Lattner0c678e52008-11-16 05:20:07 +00004448/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4449Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4450 ICmpInst *LHS, ICmpInst *RHS) {
4451 Value *Val, *Val2;
4452 ConstantInt *LHSCst, *RHSCst;
4453 ICmpInst::Predicate LHSCC, RHSCC;
4454
4455 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4456 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4457 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4458 return 0;
4459
4460 // From here on, we only handle:
4461 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4462 if (Val != Val2) return 0;
4463
4464 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4465 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4466 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4467 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4468 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4469 return 0;
4470
4471 // We can't fold (ugt x, C) | (sgt x, C2).
4472 if (!PredicatesFoldable(LHSCC, RHSCC))
4473 return 0;
4474
4475 // Ensure that the larger constant is on the RHS.
4476 bool ShouldSwap;
4477 if (ICmpInst::isSignedPredicate(LHSCC) ||
4478 (ICmpInst::isEquality(LHSCC) &&
4479 ICmpInst::isSignedPredicate(RHSCC)))
4480 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4481 else
4482 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4483
4484 if (ShouldSwap) {
4485 std::swap(LHS, RHS);
4486 std::swap(LHSCst, RHSCst);
4487 std::swap(LHSCC, RHSCC);
4488 }
4489
4490 // At this point, we know we have have two icmp instructions
4491 // comparing a value against two constants and or'ing the result
4492 // together. Because of the above check, we know that we only have
4493 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4494 // FoldICmpLogical check above), that the two constants are not
4495 // equal.
4496 assert(LHSCst != RHSCst && "Compares not folded above?");
4497
4498 switch (LHSCC) {
4499 default: assert(0 && "Unknown integer condition code!");
4500 case ICmpInst::ICMP_EQ:
4501 switch (RHSCC) {
4502 default: assert(0 && "Unknown integer condition code!");
4503 case ICmpInst::ICMP_EQ:
4504 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4505 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4506 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4507 Val->getName()+".off");
4508 InsertNewInstBefore(Add, I);
Dan Gohman8fd520a2009-06-15 22:12:54 +00004509 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004510 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4511 }
4512 break; // (X == 13 | X == 15) -> no change
4513 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4514 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4515 break;
4516 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4517 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4518 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4519 return ReplaceInstUsesWith(I, RHS);
4520 }
4521 break;
4522 case ICmpInst::ICMP_NE:
4523 switch (RHSCC) {
4524 default: assert(0 && "Unknown integer condition code!");
4525 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4526 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4527 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4528 return ReplaceInstUsesWith(I, LHS);
4529 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4530 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4531 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4532 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4533 }
4534 break;
4535 case ICmpInst::ICMP_ULT:
4536 switch (RHSCC) {
4537 default: assert(0 && "Unknown integer condition code!");
4538 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4539 break;
4540 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4541 // If RHSCst is [us]MAXINT, it is always false. Not handling
4542 // this can cause overflow.
4543 if (RHSCst->isMaxValue(false))
4544 return ReplaceInstUsesWith(I, LHS);
4545 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4546 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4547 break;
4548 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4549 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4550 return ReplaceInstUsesWith(I, RHS);
4551 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4552 break;
4553 }
4554 break;
4555 case ICmpInst::ICMP_SLT:
4556 switch (RHSCC) {
4557 default: assert(0 && "Unknown integer condition code!");
4558 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4559 break;
4560 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4561 // If RHSCst is [us]MAXINT, it is always false. Not handling
4562 // this can cause overflow.
4563 if (RHSCst->isMaxValue(true))
4564 return ReplaceInstUsesWith(I, LHS);
4565 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4566 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4567 break;
4568 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4569 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4570 return ReplaceInstUsesWith(I, RHS);
4571 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4572 break;
4573 }
4574 break;
4575 case ICmpInst::ICMP_UGT:
4576 switch (RHSCC) {
4577 default: assert(0 && "Unknown integer condition code!");
4578 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4579 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4580 return ReplaceInstUsesWith(I, LHS);
4581 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4582 break;
4583 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4584 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4585 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4586 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4587 break;
4588 }
4589 break;
4590 case ICmpInst::ICMP_SGT:
4591 switch (RHSCC) {
4592 default: assert(0 && "Unknown integer condition code!");
4593 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4594 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4595 return ReplaceInstUsesWith(I, LHS);
4596 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4597 break;
4598 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4599 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4600 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4601 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4602 break;
4603 }
4604 break;
4605 }
4606 return 0;
4607}
4608
Bill Wendlingdae376a2008-12-01 08:23:25 +00004609/// FoldOrWithConstants - This helper function folds:
4610///
Bill Wendling236a1192008-12-02 05:09:00 +00004611/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004612///
4613/// into:
4614///
Bill Wendling236a1192008-12-02 05:09:00 +00004615/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004616///
Bill Wendling236a1192008-12-02 05:09:00 +00004617/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004618Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004619 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004620 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4621 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004622
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004623 Value *V1 = 0;
4624 ConstantInt *CI2 = 0;
4625 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004626
Bill Wendling86ee3162008-12-02 06:18:11 +00004627 APInt Xor = CI1->getValue() ^ CI2->getValue();
4628 if (!Xor.isAllOnesValue()) return 0;
4629
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004630 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004631 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004632 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4633 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004634 }
4635
4636 return 0;
4637}
4638
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004639Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4640 bool Changed = SimplifyCommutative(I);
4641 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4642
4643 if (isa<UndefValue>(Op1)) // X | undef -> -1
4644 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4645
4646 // or X, X = X
4647 if (Op0 == Op1)
4648 return ReplaceInstUsesWith(I, Op0);
4649
4650 // See if we can simplify any instructions used by the instruction whose sole
4651 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004652 if (SimplifyDemandedInstructionBits(I))
4653 return &I;
4654 if (isa<VectorType>(I.getType())) {
4655 if (isa<ConstantAggregateZero>(Op1)) {
4656 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4657 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4658 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4659 return ReplaceInstUsesWith(I, I.getOperand(1));
4660 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004661 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004663 // or X, -1 == -1
4664 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4665 ConstantInt *C1 = 0; Value *X = 0;
4666 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4667 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004668 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004669 InsertNewInstBefore(Or, I);
4670 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004671 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672 ConstantInt::get(RHS->getValue() | C1->getValue()));
4673 }
4674
4675 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4676 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004677 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004678 InsertNewInstBefore(Or, I);
4679 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004680 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004681 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4682 }
4683
4684 // Try to fold constant and into select arguments.
4685 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4686 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4687 return R;
4688 if (isa<PHINode>(Op0))
4689 if (Instruction *NV = FoldOpIntoPhi(I))
4690 return NV;
4691 }
4692
4693 Value *A = 0, *B = 0;
4694 ConstantInt *C1 = 0, *C2 = 0;
4695
4696 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4697 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4698 return ReplaceInstUsesWith(I, Op1);
4699 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4700 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4701 return ReplaceInstUsesWith(I, Op0);
4702
4703 // (A | B) | C and A | (B | C) -> bswap if possible.
4704 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4705 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4706 match(Op1, m_Or(m_Value(), m_Value())) ||
4707 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4708 match(Op1, m_Shift(m_Value(), m_Value())))) {
4709 if (Instruction *BSwap = MatchBSwap(I))
4710 return BSwap;
4711 }
4712
4713 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4714 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4715 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004716 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004717 InsertNewInstBefore(NOr, I);
4718 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004720 }
4721
4722 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4723 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4724 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004725 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004726 InsertNewInstBefore(NOr, I);
4727 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004728 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004729 }
4730
4731 // (A & C)|(B & D)
4732 Value *C = 0, *D = 0;
4733 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4734 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4735 Value *V1 = 0, *V2 = 0, *V3 = 0;
4736 C1 = dyn_cast<ConstantInt>(C);
4737 C2 = dyn_cast<ConstantInt>(D);
4738 if (C1 && C2) { // (A & C1)|(B & C2)
4739 // If we have: ((V + N) & C1) | (V & C2)
4740 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4741 // replace with V+N.
4742 if (C1->getValue() == ~C2->getValue()) {
4743 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4744 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4745 // Add commutes, try both ways.
4746 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4747 return ReplaceInstUsesWith(I, A);
4748 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4749 return ReplaceInstUsesWith(I, A);
4750 }
4751 // Or commutes, try both ways.
4752 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4753 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4754 // Add commutes, try both ways.
4755 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4756 return ReplaceInstUsesWith(I, B);
4757 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4758 return ReplaceInstUsesWith(I, B);
4759 }
4760 }
4761 V1 = 0; V2 = 0; V3 = 0;
4762 }
4763
4764 // Check to see if we have any common things being and'ed. If so, find the
4765 // terms for V1 & (V2|V3).
4766 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4767 if (A == B) // (A & C)|(A & D) == A & (C|D)
4768 V1 = A, V2 = C, V3 = D;
4769 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4770 V1 = A, V2 = B, V3 = C;
4771 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4772 V1 = C, V2 = A, V3 = D;
4773 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4774 V1 = C, V2 = A, V3 = B;
4775
4776 if (V1) {
4777 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004778 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4779 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004780 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004781 }
Dan Gohman279952c2008-10-28 22:38:57 +00004782
Dan Gohman35b76162008-10-30 20:40:10 +00004783 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004784 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4785 return Match;
4786 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4787 return Match;
4788 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4789 return Match;
4790 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4791 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004792
Bill Wendling22ca8352008-11-30 13:52:49 +00004793 // ((A&~B)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004794 if ((match(C, m_Not(m_Specific(D))) &&
4795 match(B, m_Not(m_Specific(A)))))
4796 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004797 // ((~B&A)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004798 if ((match(A, m_Not(m_Specific(D))) &&
4799 match(B, m_Not(m_Specific(C)))))
4800 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004801 // ((A&~B)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004802 if ((match(C, m_Not(m_Specific(B))) &&
4803 match(D, m_Not(m_Specific(A)))))
4804 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004805 // ((~B&A)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004806 if ((match(A, m_Not(m_Specific(B))) &&
4807 match(D, m_Not(m_Specific(C)))))
4808 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004809 }
4810
4811 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4812 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4813 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4814 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4815 SI0->getOperand(1) == SI1->getOperand(1) &&
4816 (SI0->hasOneUse() || SI1->hasOneUse())) {
4817 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004818 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004819 SI1->getOperand(0),
4820 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004821 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004822 SI1->getOperand(1));
4823 }
4824 }
4825
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004826 // ((A|B)&1)|(B&-2) -> (A&1) | B
4827 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4828 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004829 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004830 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004831 }
4832 // (B&-2)|((A|B)&1) -> (A&1) | B
4833 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4834 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004835 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004836 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004837 }
4838
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004839 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4840 if (A == Op1) // ~A | A == -1
4841 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4842 } else {
4843 A = 0;
4844 }
4845 // Note, A is still live here!
4846 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4847 if (Op0 == B)
4848 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4849
4850 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4851 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004852 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004853 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004854 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004855 }
4856 }
4857
4858 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4859 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4860 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4861 return R;
4862
Chris Lattner0c678e52008-11-16 05:20:07 +00004863 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4864 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4865 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004866 }
4867
4868 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004869 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004870 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4871 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004872 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4873 !isa<ICmpInst>(Op1C->getOperand(0))) {
4874 const Type *SrcTy = Op0C->getOperand(0)->getType();
4875 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4876 // Only do this if the casts both really cause code to be
4877 // generated.
4878 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4879 I.getType(), TD) &&
4880 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4881 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004882 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004883 Op1C->getOperand(0),
4884 I.getName());
4885 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004886 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004887 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004888 }
4889 }
Chris Lattner91882432007-10-24 05:38:08 +00004890 }
4891
4892
4893 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4894 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4895 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4896 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004897 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng72988052008-10-14 18:44:08 +00004898 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner91882432007-10-24 05:38:08 +00004899 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4900 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4901 // If either of the constants are nans, then the whole thing returns
4902 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004903 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004904 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4905
4906 // Otherwise, no need to compare the two constants, compare the
4907 // rest.
4908 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4909 RHS->getOperand(0));
4910 }
Evan Cheng72988052008-10-14 18:44:08 +00004911 } else {
4912 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4913 FCmpInst::Predicate Op0CC, Op1CC;
4914 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4915 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4916 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4917 // Swap RHS operands to match LHS.
4918 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4919 std::swap(Op1LHS, Op1RHS);
4920 }
4921 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4922 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4923 if (Op0CC == Op1CC)
4924 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4925 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4926 Op1CC == FCmpInst::FCMP_TRUE)
4927 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4928 else if (Op0CC == FCmpInst::FCMP_FALSE)
4929 return ReplaceInstUsesWith(I, Op1);
4930 else if (Op1CC == FCmpInst::FCMP_FALSE)
4931 return ReplaceInstUsesWith(I, Op0);
4932 bool Op0Ordered;
4933 bool Op1Ordered;
4934 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4935 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4936 if (Op0Ordered == Op1Ordered) {
4937 // If both are ordered or unordered, return a new fcmp with
4938 // or'ed predicates.
4939 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4940 Op0LHS, Op0RHS);
4941 if (Instruction *I = dyn_cast<Instruction>(RV))
4942 return I;
4943 // Otherwise, it's a constant boolean value...
4944 return ReplaceInstUsesWith(I, RV);
4945 }
4946 }
4947 }
4948 }
Chris Lattner91882432007-10-24 05:38:08 +00004949 }
4950 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004951
4952 return Changed ? &I : 0;
4953}
4954
Dan Gohman089efff2008-05-13 00:00:25 +00004955namespace {
4956
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004957// XorSelf - Implements: X ^ X --> 0
4958struct XorSelf {
4959 Value *RHS;
4960 XorSelf(Value *rhs) : RHS(rhs) {}
4961 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4962 Instruction *apply(BinaryOperator &Xor) const {
4963 return &Xor;
4964 }
4965};
4966
Dan Gohman089efff2008-05-13 00:00:25 +00004967}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004968
4969Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4970 bool Changed = SimplifyCommutative(I);
4971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4972
Evan Chenge5cd8032008-03-25 20:07:13 +00004973 if (isa<UndefValue>(Op1)) {
4974 if (isa<UndefValue>(Op0))
4975 // Handle undef ^ undef -> 0 special case. This is a common
4976 // idiom (misuse).
4977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004978 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004979 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004980
4981 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4982 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004983 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4985 }
4986
4987 // See if we can simplify any instructions used by the instruction whose sole
4988 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004989 if (SimplifyDemandedInstructionBits(I))
4990 return &I;
4991 if (isa<VectorType>(I.getType()))
4992 if (isa<ConstantAggregateZero>(Op1))
4993 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004994
4995 // Is this a ~ operation?
4996 if (Value *NotOp = dyn_castNotVal(&I)) {
4997 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4998 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5000 if (Op0I->getOpcode() == Instruction::And ||
5001 Op0I->getOpcode() == Instruction::Or) {
5002 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5003 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5004 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00005005 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005006 Op0I->getOperand(1)->getName()+".not");
5007 InsertNewInstBefore(NotY, I);
5008 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005009 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005010 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005011 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005012 }
5013 }
5014 }
5015 }
5016
5017
5018 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00005019 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005020 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005021 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005022 return new ICmpInst(ICI->getInversePredicate(),
5023 ICI->getOperand(0), ICI->getOperand(1));
5024
Nick Lewycky1405e922007-08-06 20:04:16 +00005025 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5026 return new FCmpInst(FCI->getInversePredicate(),
5027 FCI->getOperand(0), FCI->getOperand(1));
5028 }
5029
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005030 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5031 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5032 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5033 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5034 Instruction::CastOps Opcode = Op0C->getOpcode();
5035 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5036 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5037 Op0C->getDestTy())) {
5038 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5039 CI->getOpcode(), CI->getInversePredicate(),
5040 CI->getOperand(0), CI->getOperand(1)), I);
5041 NewCI->takeName(CI);
5042 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5043 }
5044 }
5045 }
5046 }
5047 }
5048
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005049 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5050 // ~(c-X) == X-c-1 == X+(-c-1)
5051 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5052 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5053 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5054 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5055 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005056 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005057 }
5058
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005059 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005060 if (Op0I->getOpcode() == Instruction::Add) {
5061 // ~(X-c) --> (-c-1)-X
5062 if (RHS->isAllOnesValue()) {
5063 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005064 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005065 ConstantExpr::getSub(NegOp0CI,
5066 ConstantInt::get(I.getType(), 1)),
5067 Op0I->getOperand(0));
5068 } else if (RHS->getValue().isSignBit()) {
5069 // (X + C) ^ signbit -> (X + C + signbit)
5070 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005071 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005072
5073 }
5074 } else if (Op0I->getOpcode() == Instruction::Or) {
5075 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5076 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5077 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5078 // Anything in both C1 and C2 is known to be zero, remove it from
5079 // NewRHS.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005080 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005081 NewRHS = ConstantExpr::getAnd(NewRHS,
5082 ConstantExpr::getNot(CommonBits));
5083 AddToWorkList(Op0I);
5084 I.setOperand(0, Op0I->getOperand(0));
5085 I.setOperand(1, NewRHS);
5086 return &I;
5087 }
5088 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005089 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005090 }
5091
5092 // Try to fold constant and into select arguments.
5093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5095 return R;
5096 if (isa<PHINode>(Op0))
5097 if (Instruction *NV = FoldOpIntoPhi(I))
5098 return NV;
5099 }
5100
5101 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5102 if (X == Op1)
5103 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5104
5105 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5106 if (X == Op0)
5107 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5108
5109
5110 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5111 if (Op1I) {
5112 Value *A, *B;
5113 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5114 if (A == Op0) { // B^(B|A) == (A|B)^B
5115 Op1I->swapOperands();
5116 I.swapOperands();
5117 std::swap(Op0, Op1);
5118 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5119 I.swapOperands(); // Simplified below.
5120 std::swap(Op0, Op1);
5121 }
Chris Lattner3b874082008-11-16 05:38:51 +00005122 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5123 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5124 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5125 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005126 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5127 if (A == Op0) { // A^(A&B) -> A^(B&A)
5128 Op1I->swapOperands();
5129 std::swap(A, B);
5130 }
5131 if (B == Op0) { // A^(B&A) -> (B&A)^A
5132 I.swapOperands(); // Simplified below.
5133 std::swap(Op0, Op1);
5134 }
5135 }
5136 }
5137
5138 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5139 if (Op0I) {
5140 Value *A, *B;
5141 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5142 if (A == Op1) // (B|A)^B == (A|B)^B
5143 std::swap(A, B);
5144 if (B == Op1) { // (A|B)^B == A & ~B
5145 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00005146 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5147 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005148 }
Chris Lattner3b874082008-11-16 05:38:51 +00005149 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5150 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5151 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5152 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005153 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5154 if (A == Op1) // (A&B)^A -> (B&A)^A
5155 std::swap(A, B);
5156 if (B == Op1 && // (B&A)^A == ~B & A
5157 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5158 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00005159 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5160 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005161 }
5162 }
5163 }
5164
5165 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5166 if (Op0I && Op1I && Op0I->isShift() &&
5167 Op0I->getOpcode() == Op1I->getOpcode() &&
5168 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5169 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5170 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005171 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005172 Op1I->getOperand(0),
5173 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005174 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005175 Op1I->getOperand(1));
5176 }
5177
5178 if (Op0I && Op1I) {
5179 Value *A, *B, *C, *D;
5180 // (A & B)^(A | B) -> A ^ B
5181 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5182 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5183 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005184 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005185 }
5186 // (A | B)^(A & B) -> A ^ B
5187 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5188 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5189 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005190 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005191 }
5192
5193 // (A & B)^(C & D)
5194 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5195 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5196 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5197 // (X & Y)^(X & Y) -> (Y^Z) & X
5198 Value *X = 0, *Y = 0, *Z = 0;
5199 if (A == C)
5200 X = A, Y = B, Z = D;
5201 else if (A == D)
5202 X = A, Y = B, Z = C;
5203 else if (B == C)
5204 X = B, Y = A, Z = D;
5205 else if (B == D)
5206 X = B, Y = A, Z = C;
5207
5208 if (X) {
5209 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005210 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5211 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005212 }
5213 }
5214 }
5215
5216 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5217 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5218 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5219 return R;
5220
5221 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005222 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005223 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5224 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5225 const Type *SrcTy = Op0C->getOperand(0)->getType();
5226 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5227 // Only do this if the casts both really cause code to be generated.
5228 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5229 I.getType(), TD) &&
5230 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5231 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005232 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005233 Op1C->getOperand(0),
5234 I.getName());
5235 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005236 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005237 }
5238 }
Chris Lattner91882432007-10-24 05:38:08 +00005239 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005240
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005241 return Changed ? &I : 0;
5242}
5243
Dan Gohman8fd520a2009-06-15 22:12:54 +00005244static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
5245 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5246}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005247
Dan Gohman8fd520a2009-06-15 22:12:54 +00005248static bool HasAddOverflow(ConstantInt *Result,
5249 ConstantInt *In1, ConstantInt *In2,
5250 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005251 if (IsSigned)
5252 if (In2->getValue().isNegative())
5253 return Result->getValue().sgt(In1->getValue());
5254 else
5255 return Result->getValue().slt(In1->getValue());
5256 else
5257 return Result->getValue().ult(In1->getValue());
5258}
5259
Dan Gohman8fd520a2009-06-15 22:12:54 +00005260/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005261/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005262static bool AddWithOverflow(Constant *&Result, Constant *In1,
5263 Constant *In2, bool IsSigned = false) {
5264 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005265
Dan Gohman8fd520a2009-06-15 22:12:54 +00005266 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5267 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5268 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5269 if (HasAddOverflow(ExtractElement(Result, Idx),
5270 ExtractElement(In1, Idx),
5271 ExtractElement(In2, Idx),
5272 IsSigned))
5273 return true;
5274 }
5275 return false;
5276 }
5277
5278 return HasAddOverflow(cast<ConstantInt>(Result),
5279 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5280 IsSigned);
5281}
5282
5283static bool HasSubOverflow(ConstantInt *Result,
5284 ConstantInt *In1, ConstantInt *In2,
5285 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005286 if (IsSigned)
5287 if (In2->getValue().isNegative())
5288 return Result->getValue().slt(In1->getValue());
5289 else
5290 return Result->getValue().sgt(In1->getValue());
5291 else
5292 return Result->getValue().ugt(In1->getValue());
5293}
5294
Dan Gohman8fd520a2009-06-15 22:12:54 +00005295/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5296/// overflowed for this type.
5297static bool SubWithOverflow(Constant *&Result, Constant *In1,
5298 Constant *In2, bool IsSigned = false) {
5299 Result = ConstantExpr::getSub(In1, In2);
5300
5301 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5302 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5303 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5304 if (HasSubOverflow(ExtractElement(Result, Idx),
5305 ExtractElement(In1, Idx),
5306 ExtractElement(In2, Idx),
5307 IsSigned))
5308 return true;
5309 }
5310 return false;
5311 }
5312
5313 return HasSubOverflow(cast<ConstantInt>(Result),
5314 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5315 IsSigned);
5316}
5317
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005318/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5319/// code necessary to compute the offset from the base pointer (without adding
5320/// in the base pointer). Return the result as a signed integer of intptr size.
5321static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5322 TargetData &TD = IC.getTargetData();
5323 gep_type_iterator GTI = gep_type_begin(GEP);
5324 const Type *IntPtrTy = TD.getIntPtrType();
5325 Value *Result = Constant::getNullValue(IntPtrTy);
5326
5327 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005328 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005329 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5330
Gabor Greif17396002008-06-12 21:37:33 +00005331 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5332 ++i, ++GTI) {
5333 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005334 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005335 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5336 if (OpC->isZero()) continue;
5337
5338 // Handle a struct index, which adds its field offset to the pointer.
5339 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5340 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5341
5342 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5343 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5344 else
5345 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005346 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005347 ConstantInt::get(IntPtrTy, Size),
5348 GEP->getName()+".offs"), I);
5349 continue;
5350 }
5351
5352 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5353 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5354 Scale = ConstantExpr::getMul(OC, Scale);
5355 if (Constant *RC = dyn_cast<Constant>(Result))
5356 Result = ConstantExpr::getAdd(RC, Scale);
5357 else {
5358 // Emit an add instruction.
5359 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005360 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005361 GEP->getName()+".offs"), I);
5362 }
5363 continue;
5364 }
5365 // Convert to correct type.
5366 if (Op->getType() != IntPtrTy) {
5367 if (Constant *OpC = dyn_cast<Constant>(Op))
Chris Lattner2941a652009-04-07 05:03:34 +00005368 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005369 else
Chris Lattner2941a652009-04-07 05:03:34 +00005370 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5371 true,
5372 Op->getName()+".c"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005373 }
5374 if (Size != 1) {
5375 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5376 if (Constant *OpC = dyn_cast<Constant>(Op))
5377 Op = ConstantExpr::getMul(OpC, Scale);
5378 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005379 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005380 GEP->getName()+".idx"), I);
5381 }
5382
5383 // Emit an add instruction.
5384 if (isa<Constant>(Op) && isa<Constant>(Result))
5385 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5386 cast<Constant>(Result));
5387 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005388 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005389 GEP->getName()+".offs"), I);
5390 }
5391 return Result;
5392}
5393
Chris Lattnereba75862008-04-22 02:53:33 +00005394
5395/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5396/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5397/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5398/// complex, and scales are involved. The above expression would also be legal
5399/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5400/// later form is less amenable to optimization though, and we are allowed to
5401/// generate the first by knowing that pointer arithmetic doesn't overflow.
5402///
5403/// If we can't emit an optimized form for this expression, this returns null.
5404///
5405static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5406 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005407 TargetData &TD = IC.getTargetData();
5408 gep_type_iterator GTI = gep_type_begin(GEP);
5409
5410 // Check to see if this gep only has a single variable index. If so, and if
5411 // any constant indices are a multiple of its scale, then we can compute this
5412 // in terms of the scale of the variable index. For example, if the GEP
5413 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5414 // because the expression will cross zero at the same point.
5415 unsigned i, e = GEP->getNumOperands();
5416 int64_t Offset = 0;
5417 for (i = 1; i != e; ++i, ++GTI) {
5418 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5419 // Compute the aggregate offset of constant indices.
5420 if (CI->isZero()) continue;
5421
5422 // Handle a struct index, which adds its field offset to the pointer.
5423 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5424 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5425 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005426 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005427 Offset += Size*CI->getSExtValue();
5428 }
5429 } else {
5430 // Found our variable index.
5431 break;
5432 }
5433 }
5434
5435 // If there are no variable indices, we must have a constant offset, just
5436 // evaluate it the general way.
5437 if (i == e) return 0;
5438
5439 Value *VariableIdx = GEP->getOperand(i);
5440 // Determine the scale factor of the variable element. For example, this is
5441 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005442 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005443
5444 // Verify that there are no other variable indices. If so, emit the hard way.
5445 for (++i, ++GTI; i != e; ++i, ++GTI) {
5446 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5447 if (!CI) return 0;
5448
5449 // Compute the aggregate offset of constant indices.
5450 if (CI->isZero()) continue;
5451
5452 // Handle a struct index, which adds its field offset to the pointer.
5453 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5454 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5455 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005456 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005457 Offset += Size*CI->getSExtValue();
5458 }
5459 }
5460
5461 // Okay, we know we have a single variable index, which must be a
5462 // pointer/array/vector index. If there is no offset, life is simple, return
5463 // the index.
5464 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5465 if (Offset == 0) {
5466 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5467 // we don't need to bother extending: the extension won't affect where the
5468 // computation crosses zero.
5469 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5470 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5471 VariableIdx->getNameStart(), &I);
5472 return VariableIdx;
5473 }
5474
5475 // Otherwise, there is an index. The computation we will do will be modulo
5476 // the pointer size, so get it.
5477 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5478
5479 Offset &= PtrSizeMask;
5480 VariableScale &= PtrSizeMask;
5481
5482 // To do this transformation, any constant index must be a multiple of the
5483 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5484 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5485 // multiple of the variable scale.
5486 int64_t NewOffs = Offset / (int64_t)VariableScale;
5487 if (Offset != NewOffs*(int64_t)VariableScale)
5488 return 0;
5489
5490 // Okay, we can do this evaluation. Start by converting the index to intptr.
5491 const Type *IntPtrTy = TD.getIntPtrType();
5492 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005493 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005494 true /*SExt*/,
5495 VariableIdx->getNameStart(), &I);
5496 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005497 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005498}
5499
5500
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005501/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5502/// else. At this point we know that the GEP is on the LHS of the comparison.
5503Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5504 ICmpInst::Predicate Cond,
5505 Instruction &I) {
5506 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5507
Chris Lattnereba75862008-04-22 02:53:33 +00005508 // Look through bitcasts.
5509 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5510 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005511
5512 Value *PtrBase = GEPLHS->getOperand(0);
5513 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005514 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005515 // This transformation (ignoring the base and scales) is valid because we
5516 // know pointers can't overflow. See if we can output an optimized form.
5517 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5518
5519 // If not, synthesize the offset the hard way.
5520 if (Offset == 0)
5521 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005522 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5523 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005524 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5525 // If the base pointers are different, but the indices are the same, just
5526 // compare the base pointer.
5527 if (PtrBase != GEPRHS->getOperand(0)) {
5528 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5529 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5530 GEPRHS->getOperand(0)->getType();
5531 if (IndicesTheSame)
5532 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5533 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5534 IndicesTheSame = false;
5535 break;
5536 }
5537
5538 // If all indices are the same, just compare the base pointers.
5539 if (IndicesTheSame)
5540 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5541 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5542
5543 // Otherwise, the base pointers are different and the indices are
5544 // different, bail out.
5545 return 0;
5546 }
5547
5548 // If one of the GEPs has all zero indices, recurse.
5549 bool AllZeros = true;
5550 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5551 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5552 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5553 AllZeros = false;
5554 break;
5555 }
5556 if (AllZeros)
5557 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5558 ICmpInst::getSwappedPredicate(Cond), I);
5559
5560 // If the other GEP has all zero indices, recurse.
5561 AllZeros = true;
5562 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5563 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5564 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5565 AllZeros = false;
5566 break;
5567 }
5568 if (AllZeros)
5569 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5570
5571 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5572 // If the GEPs only differ by one index, compare it.
5573 unsigned NumDifferences = 0; // Keep track of # differences.
5574 unsigned DiffOperand = 0; // The operand that differs.
5575 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5576 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5577 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5578 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5579 // Irreconcilable differences.
5580 NumDifferences = 2;
5581 break;
5582 } else {
5583 if (NumDifferences++) break;
5584 DiffOperand = i;
5585 }
5586 }
5587
5588 if (NumDifferences == 0) // SAME GEP?
5589 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005590 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005591 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005592
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005593 else if (NumDifferences == 1) {
5594 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5595 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5596 // Make sure we do a signed comparison here.
5597 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5598 }
5599 }
5600
5601 // Only lower this if the icmp is the only user of the GEP or if we expect
5602 // the result to fold to a constant!
5603 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5604 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5605 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5606 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5607 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5608 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5609 }
5610 }
5611 return 0;
5612}
5613
Chris Lattnere6b62d92008-05-19 20:18:56 +00005614/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5615///
5616Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5617 Instruction *LHSI,
5618 Constant *RHSC) {
5619 if (!isa<ConstantFP>(RHSC)) return 0;
5620 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5621
5622 // Get the width of the mantissa. We don't want to hack on conversions that
5623 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005624 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005625 if (MantissaWidth == -1) return 0; // Unknown.
5626
5627 // Check to see that the input is converted from an integer type that is small
5628 // enough that preserves all bits. TODO: check here for "known" sign bits.
5629 // 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 +00005630 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005631
5632 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005633 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5634 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005635 ++InputSize;
5636
5637 // If the conversion would lose info, don't hack on this.
5638 if ((int)InputSize > MantissaWidth)
5639 return 0;
5640
5641 // Otherwise, we can potentially simplify the comparison. We know that it
5642 // will always come through as an integer value and we know the constant is
5643 // not a NAN (it would have been previously simplified).
5644 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5645
5646 ICmpInst::Predicate Pred;
5647 switch (I.getPredicate()) {
5648 default: assert(0 && "Unexpected predicate!");
5649 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005650 case FCmpInst::FCMP_OEQ:
5651 Pred = ICmpInst::ICMP_EQ;
5652 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005653 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005654 case FCmpInst::FCMP_OGT:
5655 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5656 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005657 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005658 case FCmpInst::FCMP_OGE:
5659 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5660 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005661 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005662 case FCmpInst::FCMP_OLT:
5663 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5664 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005665 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005666 case FCmpInst::FCMP_OLE:
5667 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5668 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005669 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005670 case FCmpInst::FCMP_ONE:
5671 Pred = ICmpInst::ICMP_NE;
5672 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005673 case FCmpInst::FCMP_ORD:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005674 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005675 case FCmpInst::FCMP_UNO:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005676 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005677 }
5678
5679 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5680
5681 // Now we know that the APFloat is a normal number, zero or inf.
5682
Chris Lattnerf13ff492008-05-20 03:50:52 +00005683 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005684 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005685 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005686
Bill Wendling20636df2008-11-09 04:26:50 +00005687 if (!LHSUnsigned) {
5688 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5689 // and large values.
5690 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5691 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5692 APFloat::rmNearestTiesToEven);
5693 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5694 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5695 Pred == ICmpInst::ICMP_SLE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005696 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5697 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005698 }
5699 } else {
5700 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5701 // +INF and large values.
5702 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5703 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5704 APFloat::rmNearestTiesToEven);
5705 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5706 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5707 Pred == ICmpInst::ICMP_ULE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005708 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5709 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005710 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005711 }
5712
Bill Wendling20636df2008-11-09 04:26:50 +00005713 if (!LHSUnsigned) {
5714 // See if the RHS value is < SignedMin.
5715 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5716 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5717 APFloat::rmNearestTiesToEven);
5718 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5719 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5720 Pred == ICmpInst::ICMP_SGE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005721 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5722 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005723 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005724 }
5725
Bill Wendling20636df2008-11-09 04:26:50 +00005726 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5727 // [0, UMAX], but it may still be fractional. See if it is fractional by
5728 // casting the FP value to the integer value and back, checking for equality.
5729 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005730 Constant *RHSInt = LHSUnsigned
5731 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5732 : ConstantExpr::getFPToSI(RHSC, IntTy);
5733 if (!RHS.isZero()) {
5734 bool Equal = LHSUnsigned
5735 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5736 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5737 if (!Equal) {
5738 // If we had a comparison against a fractional value, we have to adjust
5739 // the compare predicate and sometimes the value. RHSC is rounded towards
5740 // zero at this point.
5741 switch (Pred) {
5742 default: assert(0 && "Unexpected integer comparison!");
5743 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedmanc9c96242008-11-30 22:48:49 +00005744 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005745 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5746 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5747 case ICmpInst::ICMP_ULE:
5748 // (float)int <= 4.4 --> int <= 4
5749 // (float)int <= -4.4 --> false
5750 if (RHS.isNegative())
5751 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5752 break;
5753 case ICmpInst::ICMP_SLE:
5754 // (float)int <= 4.4 --> int <= 4
5755 // (float)int <= -4.4 --> int < -4
5756 if (RHS.isNegative())
5757 Pred = ICmpInst::ICMP_SLT;
5758 break;
5759 case ICmpInst::ICMP_ULT:
5760 // (float)int < -4.4 --> false
5761 // (float)int < 4.4 --> int <= 4
5762 if (RHS.isNegative())
5763 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5764 Pred = ICmpInst::ICMP_ULE;
5765 break;
5766 case ICmpInst::ICMP_SLT:
5767 // (float)int < -4.4 --> int < -4
5768 // (float)int < 4.4 --> int <= 4
5769 if (!RHS.isNegative())
5770 Pred = ICmpInst::ICMP_SLE;
5771 break;
5772 case ICmpInst::ICMP_UGT:
5773 // (float)int > 4.4 --> int > 4
5774 // (float)int > -4.4 --> true
5775 if (RHS.isNegative())
5776 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5777 break;
5778 case ICmpInst::ICMP_SGT:
5779 // (float)int > 4.4 --> int > 4
5780 // (float)int > -4.4 --> int >= -4
5781 if (RHS.isNegative())
5782 Pred = ICmpInst::ICMP_SGE;
5783 break;
5784 case ICmpInst::ICMP_UGE:
5785 // (float)int >= -4.4 --> true
5786 // (float)int >= 4.4 --> int > 4
5787 if (!RHS.isNegative())
5788 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5789 Pred = ICmpInst::ICMP_UGT;
5790 break;
5791 case ICmpInst::ICMP_SGE:
5792 // (float)int >= -4.4 --> int >= -4
5793 // (float)int >= 4.4 --> int > 4
5794 if (!RHS.isNegative())
5795 Pred = ICmpInst::ICMP_SGT;
5796 break;
5797 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005798 }
5799 }
5800
5801 // Lower this FP comparison into an appropriate integer version of the
5802 // comparison.
5803 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5804}
5805
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005806Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5807 bool Changed = SimplifyCompare(I);
5808 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5809
5810 // Fold trivial predicates.
5811 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005812 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005813 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005814 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005815
5816 // Simplify 'fcmp pred X, X'
5817 if (Op0 == Op1) {
5818 switch (I.getPredicate()) {
5819 default: assert(0 && "Unknown predicate!");
5820 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5821 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5822 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005823 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005824 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5825 case FCmpInst::FCMP_OLT: // True if ordered and less than
5826 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005827 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005828
5829 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5830 case FCmpInst::FCMP_ULT: // True if unordered or less than
5831 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5832 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5833 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5834 I.setPredicate(FCmpInst::FCMP_UNO);
5835 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5836 return &I;
5837
5838 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5839 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5840 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5841 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5842 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5843 I.setPredicate(FCmpInst::FCMP_ORD);
5844 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5845 return &I;
5846 }
5847 }
5848
5849 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5850 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5851
5852 // Handle fcmp with constant RHS
5853 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005854 // If the constant is a nan, see if we can fold the comparison based on it.
5855 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5856 if (CFP->getValueAPF().isNaN()) {
5857 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedmanc9c96242008-11-30 22:48:49 +00005858 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerf13ff492008-05-20 03:50:52 +00005859 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5860 "Comparison must be either ordered or unordered!");
5861 // True if unordered.
Eli Friedmanc9c96242008-11-30 22:48:49 +00005862 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005863 }
5864 }
5865
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005866 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5867 switch (LHSI->getOpcode()) {
5868 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005869 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5870 // block. If in the same block, we're encouraging jump threading. If
5871 // not, we are just pessimizing the code by making an i1 phi.
5872 if (LHSI->getParent() == I.getParent())
5873 if (Instruction *NV = FoldOpIntoPhi(I))
5874 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005875 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005876 case Instruction::SIToFP:
5877 case Instruction::UIToFP:
5878 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5879 return NV;
5880 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005881 case Instruction::Select:
5882 // If either operand of the select is a constant, we can fold the
5883 // comparison into the select arms, which will cause one to be
5884 // constant folded and the select turned into a bitwise or.
5885 Value *Op1 = 0, *Op2 = 0;
5886 if (LHSI->hasOneUse()) {
5887 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5888 // Fold the known value into the constant operand.
5889 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5890 // Insert a new FCmp of the other select operand.
5891 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5892 LHSI->getOperand(2), RHSC,
5893 I.getName()), I);
5894 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5895 // Fold the known value into the constant operand.
5896 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5897 // Insert a new FCmp of the other select operand.
5898 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5899 LHSI->getOperand(1), RHSC,
5900 I.getName()), I);
5901 }
5902 }
5903
5904 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005905 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005906 break;
5907 }
5908 }
5909
5910 return Changed ? &I : 0;
5911}
5912
5913Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5914 bool Changed = SimplifyCompare(I);
5915 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5916 const Type *Ty = Op0->getType();
5917
5918 // icmp X, X
5919 if (Op0 == Op1)
5920 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005921 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005922
5923 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5924 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005925
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005926 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5927 // addresses never equal each other! We already know that Op0 != Op1.
5928 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5929 isa<ConstantPointerNull>(Op0)) &&
5930 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5931 isa<ConstantPointerNull>(Op1)))
5932 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005933 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005934
5935 // icmp's with boolean values can always be turned into bitwise operations
5936 if (Ty == Type::Int1Ty) {
5937 switch (I.getPredicate()) {
5938 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005939 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005940 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005941 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005942 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005943 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005944 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005945 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005946
5947 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005948 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005949 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005950 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00005951 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005952 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005953 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005954 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005955 case ICmpInst::ICMP_SGT:
5956 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005957 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005958 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5959 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5960 InsertNewInstBefore(Not, I);
5961 return BinaryOperator::CreateAnd(Not, Op0);
5962 }
5963 case ICmpInst::ICMP_UGE:
5964 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5965 // FALL THROUGH
5966 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005967 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005968 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005969 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005970 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005971 case ICmpInst::ICMP_SGE:
5972 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5973 // FALL THROUGH
5974 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5975 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5976 InsertNewInstBefore(Not, I);
5977 return BinaryOperator::CreateOr(Not, Op0);
5978 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005979 }
5980 }
5981
Dan Gohman7934d592009-04-25 17:12:48 +00005982 unsigned BitWidth = 0;
5983 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00005984 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5985 else if (Ty->isIntOrIntVector())
5986 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00005987
5988 bool isSignBit = false;
5989
Dan Gohman58c09632008-09-16 18:46:06 +00005990 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005991 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00005992 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005993
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005994 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5995 if (I.isEquality() && CI->isNullValue() &&
5996 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5997 // (icmp cond A B) if cond is equality
5998 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005999 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006000
Dan Gohman58c09632008-09-16 18:46:06 +00006001 // If we have an icmp le or icmp ge instruction, turn it into the
6002 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6003 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006004 switch (I.getPredicate()) {
6005 default: break;
6006 case ICmpInst::ICMP_ULE:
6007 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6008 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6009 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
6010 case ICmpInst::ICMP_SLE:
6011 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6012 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6013 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
6014 case ICmpInst::ICMP_UGE:
6015 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6016 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6017 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
6018 case ICmpInst::ICMP_SGE:
6019 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6020 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6021 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
6022 }
6023
Chris Lattnera1308652008-07-11 05:40:05 +00006024 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006025 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006026 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006027 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6028 }
6029
6030 // See if we can fold the comparison based on range information we can get
6031 // by checking whether bits are known to be zero or one in the input.
6032 if (BitWidth != 0) {
6033 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6034 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6035
6036 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006037 isSignBit ? APInt::getSignBit(BitWidth)
6038 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006039 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006040 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006041 if (SimplifyDemandedBits(I.getOperandUse(1),
6042 APInt::getAllOnesValue(BitWidth),
6043 Op1KnownZero, Op1KnownOne, 0))
6044 return &I;
6045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006046 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006047 // in. Compute the Min, Max and RHS values based on the known bits. For the
6048 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006049 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6050 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6051 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6052 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6053 Op0Min, Op0Max);
6054 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6055 Op1Min, Op1Max);
6056 } else {
6057 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6058 Op0Min, Op0Max);
6059 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6060 Op1Min, Op1Max);
6061 }
6062
Chris Lattnera1308652008-07-11 05:40:05 +00006063 // If Min and Max are known to be the same, then SimplifyDemandedBits
6064 // figured out that the LHS is a constant. Just constant fold this now so
6065 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006066 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6067 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6068 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6069 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6070
Chris Lattnera1308652008-07-11 05:40:05 +00006071 // Based on the range information we know about the LHS, see if we can
6072 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006073 switch (I.getPredicate()) {
Chris Lattner62d0f232008-07-11 05:08:55 +00006074 default: assert(0 && "Unknown icmp opcode!");
6075 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006076 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner62d0f232008-07-11 05:08:55 +00006077 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6078 break;
6079 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006080 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner62d0f232008-07-11 05:08:55 +00006081 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6082 break;
6083 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006084 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006085 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006086 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006087 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006088 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006089 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006090 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6091 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6092 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6093
6094 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6095 if (CI->isMinValue(true))
6096 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Chris Lattnera1308652008-07-11 05:40:05 +00006097 ConstantInt::getAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006098 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006099 break;
6100 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006101 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006102 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006103 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006104 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006105
6106 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006107 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006108 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6109 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6110 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6111
6112 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6113 if (CI->isMaxValue(true))
6114 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6115 ConstantInt::getNullValue(Op0->getType()));
6116 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006117 break;
6118 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006119 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner62d0f232008-07-11 05:08:55 +00006120 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006121 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner62d0f232008-07-11 05:08:55 +00006122 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006123 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006124 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006125 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6126 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6127 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6128 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006129 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006130 case ICmpInst::ICMP_SGT:
6131 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006132 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006133 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner62d0f232008-07-11 05:08:55 +00006134 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006135
6136 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Chris Lattnera1308652008-07-11 05:40:05 +00006137 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6139 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6140 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6141 }
6142 break;
6143 case ICmpInst::ICMP_SGE:
6144 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6145 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6146 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6147 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6148 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6149 break;
6150 case ICmpInst::ICMP_SLE:
6151 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6152 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6153 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6154 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6155 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6156 break;
6157 case ICmpInst::ICMP_UGE:
6158 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6159 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6160 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6161 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6162 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6163 break;
6164 case ICmpInst::ICMP_ULE:
6165 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6166 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6167 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6168 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6169 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner62d0f232008-07-11 05:08:55 +00006170 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006171 }
Dan Gohman7934d592009-04-25 17:12:48 +00006172
6173 // Turn a signed comparison into an unsigned one if both operands
6174 // are known to have the same sign.
6175 if (I.isSignedPredicate() &&
6176 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6177 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6178 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006179 }
6180
6181 // Test if the ICmpInst instruction is used exclusively by a select as
6182 // part of a minimum or maximum operation. If so, refrain from doing
6183 // any other folding. This helps out other analyses which understand
6184 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6185 // and CodeGen. And in this case, at least one of the comparison
6186 // operands has at least one user besides the compare (the select),
6187 // which would often largely negate the benefit of folding anyway.
6188 if (I.hasOneUse())
6189 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6190 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6191 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6192 return 0;
6193
6194 // See if we are doing a comparison between a constant and an instruction that
6195 // can be folded into the comparison.
6196 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006197 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6198 // instruction, see if that instruction also has constants so that the
6199 // instruction can be folded into the icmp
6200 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6201 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6202 return Res;
6203 }
6204
6205 // Handle icmp with constant (but not simple integer constant) RHS
6206 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6207 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6208 switch (LHSI->getOpcode()) {
6209 case Instruction::GetElementPtr:
6210 if (RHSC->isNullValue()) {
6211 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6212 bool isAllZeros = true;
6213 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6214 if (!isa<Constant>(LHSI->getOperand(i)) ||
6215 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6216 isAllZeros = false;
6217 break;
6218 }
6219 if (isAllZeros)
6220 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6221 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6222 }
6223 break;
6224
6225 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006226 // Only fold icmp into the PHI if the phi and fcmp are in the same
6227 // block. If in the same block, we're encouraging jump threading. If
6228 // not, we are just pessimizing the code by making an i1 phi.
6229 if (LHSI->getParent() == I.getParent())
6230 if (Instruction *NV = FoldOpIntoPhi(I))
6231 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006232 break;
6233 case Instruction::Select: {
6234 // If either operand of the select is a constant, we can fold the
6235 // comparison into the select arms, which will cause one to be
6236 // constant folded and the select turned into a bitwise or.
6237 Value *Op1 = 0, *Op2 = 0;
6238 if (LHSI->hasOneUse()) {
6239 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6240 // Fold the known value into the constant operand.
6241 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6242 // Insert a new ICmp of the other select operand.
6243 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6244 LHSI->getOperand(2), RHSC,
6245 I.getName()), I);
6246 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6247 // Fold the known value into the constant operand.
6248 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6249 // Insert a new ICmp of the other select operand.
6250 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6251 LHSI->getOperand(1), RHSC,
6252 I.getName()), I);
6253 }
6254 }
6255
6256 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006257 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006258 break;
6259 }
6260 case Instruction::Malloc:
6261 // If we have (malloc != null), and if the malloc has a single use, we
6262 // can assume it is successful and remove the malloc.
6263 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6264 AddToWorkList(LHSI);
6265 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006266 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006267 }
6268 break;
6269 }
6270 }
6271
6272 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6273 if (User *GEP = dyn_castGetElementPtr(Op0))
6274 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6275 return NI;
6276 if (User *GEP = dyn_castGetElementPtr(Op1))
6277 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6278 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6279 return NI;
6280
6281 // Test to see if the operands of the icmp are casted versions of other
6282 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6283 // now.
6284 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6285 if (isa<PointerType>(Op0->getType()) &&
6286 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6287 // We keep moving the cast from the left operand over to the right
6288 // operand, where it can often be eliminated completely.
6289 Op0 = CI->getOperand(0);
6290
6291 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6292 // so eliminate it as well.
6293 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6294 Op1 = CI2->getOperand(0);
6295
6296 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006297 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006298 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6299 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6300 } else {
6301 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006302 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006303 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006304 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006305 return new ICmpInst(I.getPredicate(), Op0, Op1);
6306 }
6307 }
6308
6309 if (isa<CastInst>(Op0)) {
6310 // Handle the special case of: icmp (cast bool to X), <cst>
6311 // This comes up when you have code like
6312 // int X = A < B;
6313 // if (X) ...
6314 // For generality, we handle any zero-extension of any operand comparison
6315 // with a constant or another cast from the same type.
6316 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6317 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6318 return R;
6319 }
6320
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006321 // See if it's the same type of instruction on the left and right.
6322 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6323 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006324 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006325 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006326 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006327 default: break;
6328 case Instruction::Add:
6329 case Instruction::Sub:
6330 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006331 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewyckydac84332009-01-31 21:30:05 +00006332 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6333 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006334 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6336 if (CI->getValue().isSignBit()) {
6337 ICmpInst::Predicate Pred = I.isSignedPredicate()
6338 ? I.getUnsignedPredicate()
6339 : I.getSignedPredicate();
6340 return new ICmpInst(Pred, Op0I->getOperand(0),
6341 Op1I->getOperand(0));
6342 }
6343
6344 if (CI->getValue().isMaxSignedValue()) {
6345 ICmpInst::Predicate Pred = I.isSignedPredicate()
6346 ? I.getUnsignedPredicate()
6347 : I.getSignedPredicate();
6348 Pred = I.getSwappedPredicate(Pred);
6349 return new ICmpInst(Pred, Op0I->getOperand(0),
6350 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006351 }
6352 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006353 break;
6354 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006355 if (!I.isEquality())
6356 break;
6357
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006358 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6359 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6360 // Mask = -1 >> count-trailing-zeros(Cst).
6361 if (!CI->isZero() && !CI->isOne()) {
6362 const APInt &AP = CI->getValue();
6363 ConstantInt *Mask = ConstantInt::get(
6364 APInt::getLowBitsSet(AP.getBitWidth(),
6365 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006366 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006367 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6368 Mask);
6369 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6370 Mask);
6371 InsertNewInstBefore(And1, I);
6372 InsertNewInstBefore(And2, I);
6373 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006374 }
6375 }
6376 break;
6377 }
6378 }
6379 }
6380 }
6381
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006382 // ~x < ~y --> y < x
6383 { Value *A, *B;
6384 if (match(Op0, m_Not(m_Value(A))) &&
6385 match(Op1, m_Not(m_Value(B))))
6386 return new ICmpInst(I.getPredicate(), B, A);
6387 }
6388
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006389 if (I.isEquality()) {
6390 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006391
6392 // -x == -y --> x == y
6393 if (match(Op0, m_Neg(m_Value(A))) &&
6394 match(Op1, m_Neg(m_Value(B))))
6395 return new ICmpInst(I.getPredicate(), A, B);
6396
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006397 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6398 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6399 Value *OtherVal = A == Op1 ? B : A;
6400 return new ICmpInst(I.getPredicate(), OtherVal,
6401 Constant::getNullValue(A->getType()));
6402 }
6403
6404 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6405 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006406 ConstantInt *C1, *C2;
6407 if (match(B, m_ConstantInt(C1)) &&
6408 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6409 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6410 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6411 return new ICmpInst(I.getPredicate(), A,
6412 InsertNewInstBefore(Xor, I));
6413 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006414
6415 // A^B == A^D -> B == D
6416 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6417 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6418 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6419 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6420 }
6421 }
6422
6423 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6424 (A == Op0 || B == Op0)) {
6425 // A == (A^B) -> B == 0
6426 Value *OtherVal = A == Op0 ? B : A;
6427 return new ICmpInst(I.getPredicate(), OtherVal,
6428 Constant::getNullValue(A->getType()));
6429 }
Chris Lattner3b874082008-11-16 05:38:51 +00006430
6431 // (A-B) == A -> B == 0
6432 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6433 return new ICmpInst(I.getPredicate(), B,
6434 Constant::getNullValue(B->getType()));
6435
6436 // A == (A-B) -> B == 0
6437 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006438 return new ICmpInst(I.getPredicate(), B,
6439 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006440
6441 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6442 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6443 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6444 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6445 Value *X = 0, *Y = 0, *Z = 0;
6446
6447 if (A == C) {
6448 X = B; Y = D; Z = A;
6449 } else if (A == D) {
6450 X = B; Y = C; Z = A;
6451 } else if (B == C) {
6452 X = A; Y = D; Z = B;
6453 } else if (B == D) {
6454 X = A; Y = C; Z = B;
6455 }
6456
6457 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006458 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6459 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006460 I.setOperand(0, Op1);
6461 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6462 return &I;
6463 }
6464 }
6465 }
6466 return Changed ? &I : 0;
6467}
6468
6469
6470/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6471/// and CmpRHS are both known to be integer constants.
6472Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6473 ConstantInt *DivRHS) {
6474 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6475 const APInt &CmpRHSV = CmpRHS->getValue();
6476
6477 // FIXME: If the operand types don't match the type of the divide
6478 // then don't attempt this transform. The code below doesn't have the
6479 // logic to deal with a signed divide and an unsigned compare (and
6480 // vice versa). This is because (x /s C1) <s C2 produces different
6481 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6482 // (x /u C1) <u C2. Simply casting the operands and result won't
6483 // work. :( The if statement below tests that condition and bails
6484 // if it finds it.
6485 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6486 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6487 return 0;
6488 if (DivRHS->isZero())
6489 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006490 if (DivIsSigned && DivRHS->isAllOnesValue())
6491 return 0; // The overflow computation also screws up here
6492 if (DivRHS->isOne())
6493 return 0; // Not worth bothering, and eliminates some funny cases
6494 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006495
6496 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6497 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6498 // C2 (CI). By solving for X we can turn this into a range check
6499 // instead of computing a divide.
Dan Gohman8fd520a2009-06-15 22:12:54 +00006500 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006501
6502 // Determine if the product overflows by seeing if the product is
6503 // not equal to the divide. Make sure we do the same kind of divide
6504 // as in the LHS instruction that we're folding.
6505 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6506 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6507
6508 // Get the ICmp opcode
6509 ICmpInst::Predicate Pred = ICI.getPredicate();
6510
6511 // Figure out the interval that is being checked. For example, a comparison
6512 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6513 // Compute this interval based on the constants involved and the signedness of
6514 // the compare/divide. This computes a half-open interval, keeping track of
6515 // whether either value in the interval overflows. After analysis each
6516 // overflow variable is set to 0 if it's corresponding bound variable is valid
6517 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6518 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006519 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006520
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006521 if (!DivIsSigned) { // udiv
6522 // e.g. X/5 op 3 --> [15, 20)
6523 LoBound = Prod;
6524 HiOverflow = LoOverflow = ProdOV;
6525 if (!HiOverflow)
6526 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006527 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006528 if (CmpRHSV == 0) { // (X / pos) op 0
6529 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6530 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6531 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006532 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006533 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6534 HiOverflow = LoOverflow = ProdOV;
6535 if (!HiOverflow)
6536 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6537 } else { // (X / pos) op neg
6538 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006539 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006540 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6541 if (!LoOverflow) {
6542 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6543 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6544 true) ? -1 : 0;
6545 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006546 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006547 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006548 if (CmpRHSV == 0) { // (X / neg) op 0
6549 // e.g. X/-5 op 0 --> [-4, 5)
6550 LoBound = AddOne(DivRHS);
6551 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6552 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6553 HiOverflow = 1; // [INTMIN+1, overflow)
6554 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6555 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006556 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006557 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006558 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006559 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6560 if (!LoOverflow)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006561 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006562 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006563 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6564 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006565 if (!HiOverflow)
6566 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006567 }
6568
6569 // Dividing by a negative swaps the condition. LT <-> GT
6570 Pred = ICmpInst::getSwappedPredicate(Pred);
6571 }
6572
6573 Value *X = DivI->getOperand(0);
6574 switch (Pred) {
6575 default: assert(0 && "Unhandled icmp opcode!");
6576 case ICmpInst::ICMP_EQ:
6577 if (LoOverflow && HiOverflow)
6578 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6579 else if (HiOverflow)
6580 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6581 ICmpInst::ICMP_UGE, X, LoBound);
6582 else if (LoOverflow)
6583 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6584 ICmpInst::ICMP_ULT, X, HiBound);
6585 else
6586 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6587 case ICmpInst::ICMP_NE:
6588 if (LoOverflow && HiOverflow)
6589 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6590 else if (HiOverflow)
6591 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6592 ICmpInst::ICMP_ULT, X, LoBound);
6593 else if (LoOverflow)
6594 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6595 ICmpInst::ICMP_UGE, X, HiBound);
6596 else
6597 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6598 case ICmpInst::ICMP_ULT:
6599 case ICmpInst::ICMP_SLT:
6600 if (LoOverflow == +1) // Low bound is greater than input range.
6601 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6602 if (LoOverflow == -1) // Low bound is less than input range.
6603 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6604 return new ICmpInst(Pred, X, LoBound);
6605 case ICmpInst::ICMP_UGT:
6606 case ICmpInst::ICMP_SGT:
6607 if (HiOverflow == +1) // High bound greater than input range.
6608 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6609 else if (HiOverflow == -1) // High bound less than input range.
6610 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6611 if (Pred == ICmpInst::ICMP_UGT)
6612 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6613 else
6614 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6615 }
6616}
6617
6618
6619/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6620///
6621Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6622 Instruction *LHSI,
6623 ConstantInt *RHS) {
6624 const APInt &RHSV = RHS->getValue();
6625
6626 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006627 case Instruction::Trunc:
6628 if (ICI.isEquality() && LHSI->hasOneUse()) {
6629 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6630 // of the high bits truncated out of x are known.
6631 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6632 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6633 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6634 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6635 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6636
6637 // If all the high bits are known, we can do this xform.
6638 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6639 // Pull in the high bits from known-ones set.
6640 APInt NewRHS(RHS->getValue());
6641 NewRHS.zext(SrcBits);
6642 NewRHS |= KnownOne;
6643 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6644 ConstantInt::get(NewRHS));
6645 }
6646 }
6647 break;
6648
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006649 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6650 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6651 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6652 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006653 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6654 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006655 Value *CompareVal = LHSI->getOperand(0);
6656
6657 // If the sign bit of the XorCST is not set, there is no change to
6658 // the operation, just stop using the Xor.
6659 if (!XorCST->getValue().isNegative()) {
6660 ICI.setOperand(0, CompareVal);
6661 AddToWorkList(LHSI);
6662 return &ICI;
6663 }
6664
6665 // Was the old condition true if the operand is positive?
6666 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6667
6668 // If so, the new one isn't.
6669 isTrueIfPositive ^= true;
6670
6671 if (isTrueIfPositive)
6672 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6673 else
6674 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6675 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006676
6677 if (LHSI->hasOneUse()) {
6678 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6679 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6680 const APInt &SignBit = XorCST->getValue();
6681 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6682 ? ICI.getUnsignedPredicate()
6683 : ICI.getSignedPredicate();
6684 return new ICmpInst(Pred, LHSI->getOperand(0),
6685 ConstantInt::get(RHSV ^ SignBit));
6686 }
6687
6688 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006689 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006690 const APInt &NotSignBit = XorCST->getValue();
6691 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6692 ? ICI.getUnsignedPredicate()
6693 : ICI.getSignedPredicate();
6694 Pred = ICI.getSwappedPredicate(Pred);
6695 return new ICmpInst(Pred, LHSI->getOperand(0),
6696 ConstantInt::get(RHSV ^ NotSignBit));
6697 }
6698 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006699 }
6700 break;
6701 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6702 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6703 LHSI->getOperand(0)->hasOneUse()) {
6704 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6705
6706 // If the LHS is an AND of a truncating cast, we can widen the
6707 // and/compare to be the input width without changing the value
6708 // produced, eliminating a cast.
6709 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6710 // We can do this transformation if either the AND constant does not
6711 // have its sign bit set or if it is an equality comparison.
6712 // Extending a relational comparison when we're checking the sign
6713 // bit would not work.
6714 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006715 (ICI.isEquality() ||
6716 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006717 uint32_t BitWidth =
6718 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6719 APInt NewCST = AndCST->getValue();
6720 NewCST.zext(BitWidth);
6721 APInt NewCI = RHSV;
6722 NewCI.zext(BitWidth);
6723 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006724 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006725 ConstantInt::get(NewCST),LHSI->getName());
6726 InsertNewInstBefore(NewAnd, ICI);
6727 return new ICmpInst(ICI.getPredicate(), NewAnd,
6728 ConstantInt::get(NewCI));
6729 }
6730 }
6731
6732 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6733 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6734 // happens a LOT in code produced by the C front-end, for bitfield
6735 // access.
6736 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6737 if (Shift && !Shift->isShift())
6738 Shift = 0;
6739
6740 ConstantInt *ShAmt;
6741 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6742 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6743 const Type *AndTy = AndCST->getType(); // Type of the and.
6744
6745 // We can fold this as long as we can't shift unknown bits
6746 // into the mask. This can only happen with signed shift
6747 // rights, as they sign-extend.
6748 if (ShAmt) {
6749 bool CanFold = Shift->isLogicalShift();
6750 if (!CanFold) {
6751 // To test for the bad case of the signed shr, see if any
6752 // of the bits shifted in could be tested after the mask.
6753 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6754 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6755
6756 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6757 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6758 AndCST->getValue()) == 0)
6759 CanFold = true;
6760 }
6761
6762 if (CanFold) {
6763 Constant *NewCst;
6764 if (Shift->getOpcode() == Instruction::Shl)
6765 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6766 else
6767 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6768
6769 // Check to see if we are shifting out any of the bits being
6770 // compared.
6771 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6772 // If we shifted bits out, the fold is not going to work out.
6773 // As a special case, check to see if this means that the
6774 // result is always true or false now.
6775 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6776 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6777 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6778 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6779 } else {
6780 ICI.setOperand(1, NewCst);
6781 Constant *NewAndCST;
6782 if (Shift->getOpcode() == Instruction::Shl)
6783 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6784 else
6785 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6786 LHSI->setOperand(1, NewAndCST);
6787 LHSI->setOperand(0, Shift->getOperand(0));
6788 AddToWorkList(Shift); // Shift is dead.
6789 AddUsesToWorkList(ICI);
6790 return &ICI;
6791 }
6792 }
6793 }
6794
6795 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6796 // preferable because it allows the C<<Y expression to be hoisted out
6797 // of a loop if Y is invariant and X is not.
6798 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006799 ICI.isEquality() && !Shift->isArithmeticShift() &&
6800 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006801 // Compute C << Y.
6802 Value *NS;
6803 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006804 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006805 Shift->getOperand(1), "tmp");
6806 } else {
6807 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006808 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 Shift->getOperand(1), "tmp");
6810 }
6811 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6812
6813 // Compute X & (C << Y).
6814 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006815 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006816 InsertNewInstBefore(NewAnd, ICI);
6817
6818 ICI.setOperand(0, NewAnd);
6819 return &ICI;
6820 }
6821 }
6822 break;
6823
6824 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6825 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6826 if (!ShAmt) break;
6827
6828 uint32_t TypeBits = RHSV.getBitWidth();
6829
6830 // Check that the shift amount is in range. If not, don't perform
6831 // undefined shifts. When the shift is visited it will be
6832 // simplified.
6833 if (ShAmt->uge(TypeBits))
6834 break;
6835
6836 if (ICI.isEquality()) {
6837 // If we are comparing against bits always shifted out, the
6838 // comparison cannot succeed.
6839 Constant *Comp =
6840 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6841 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6842 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6843 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6844 return ReplaceInstUsesWith(ICI, Cst);
6845 }
6846
6847 if (LHSI->hasOneUse()) {
6848 // Otherwise strength reduce the shift into an and.
6849 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6850 Constant *Mask =
6851 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6852
6853 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006854 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006855 Mask, LHSI->getName()+".mask");
6856 Value *And = InsertNewInstBefore(AndI, ICI);
6857 return new ICmpInst(ICI.getPredicate(), And,
6858 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6859 }
6860 }
6861
6862 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6863 bool TrueIfSigned = false;
6864 if (LHSI->hasOneUse() &&
6865 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6866 // (X << 31) <s 0 --> (X&1) != 0
6867 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6868 (TypeBits-ShAmt->getZExtValue()-1));
6869 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006870 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006871 Mask, LHSI->getName()+".mask");
6872 Value *And = InsertNewInstBefore(AndI, ICI);
6873
6874 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6875 And, Constant::getNullValue(And->getType()));
6876 }
6877 break;
6878 }
6879
6880 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6881 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006882 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006883 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006884 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885
Chris Lattner5ee84f82008-03-21 05:19:58 +00006886 // Check that the shift amount is in range. If not, don't perform
6887 // undefined shifts. When the shift is visited it will be
6888 // simplified.
6889 uint32_t TypeBits = RHSV.getBitWidth();
6890 if (ShAmt->uge(TypeBits))
6891 break;
6892
6893 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006894
Chris Lattner5ee84f82008-03-21 05:19:58 +00006895 // If we are comparing against bits always shifted out, the
6896 // comparison cannot succeed.
6897 APInt Comp = RHSV << ShAmtVal;
6898 if (LHSI->getOpcode() == Instruction::LShr)
6899 Comp = Comp.lshr(ShAmtVal);
6900 else
6901 Comp = Comp.ashr(ShAmtVal);
6902
6903 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6904 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6905 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6906 return ReplaceInstUsesWith(ICI, Cst);
6907 }
6908
6909 // Otherwise, check to see if the bits shifted out are known to be zero.
6910 // If so, we can compare against the unshifted value:
6911 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006912 if (LHSI->hasOneUse() &&
6913 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006914 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6915 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6916 ConstantExpr::getShl(RHS, ShAmt));
6917 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006918
Evan Chengfb9292a2008-04-23 00:38:06 +00006919 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006920 // Otherwise strength reduce the shift into an and.
6921 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6922 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006923
Chris Lattner5ee84f82008-03-21 05:19:58 +00006924 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006925 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006926 Mask, LHSI->getName()+".mask");
6927 Value *And = InsertNewInstBefore(AndI, ICI);
6928 return new ICmpInst(ICI.getPredicate(), And,
6929 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006930 }
6931 break;
6932 }
6933
6934 case Instruction::SDiv:
6935 case Instruction::UDiv:
6936 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6937 // Fold this div into the comparison, producing a range check.
6938 // Determine, based on the divide type, what the range is being
6939 // checked. If there is an overflow on the low or high side, remember
6940 // it, otherwise compute the range [low, hi) bounding the new value.
6941 // See: InsertRangeTest above for the kinds of replacements possible.
6942 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6943 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6944 DivRHS))
6945 return R;
6946 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006947
6948 case Instruction::Add:
6949 // Fold: icmp pred (add, X, C1), C2
6950
6951 if (!ICI.isEquality()) {
6952 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6953 if (!LHSC) break;
6954 const APInt &LHSV = LHSC->getValue();
6955
6956 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6957 .subtract(LHSV);
6958
6959 if (ICI.isSignedPredicate()) {
6960 if (CR.getLower().isSignBit()) {
6961 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6962 ConstantInt::get(CR.getUpper()));
6963 } else if (CR.getUpper().isSignBit()) {
6964 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6965 ConstantInt::get(CR.getLower()));
6966 }
6967 } else {
6968 if (CR.getLower().isMinValue()) {
6969 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6970 ConstantInt::get(CR.getUpper()));
6971 } else if (CR.getUpper().isMinValue()) {
6972 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6973 ConstantInt::get(CR.getLower()));
6974 }
6975 }
6976 }
6977 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006978 }
6979
6980 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6981 if (ICI.isEquality()) {
6982 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6983
6984 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6985 // the second operand is a constant, simplify a bit.
6986 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6987 switch (BO->getOpcode()) {
6988 case Instruction::SRem:
6989 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6990 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6991 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6992 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6993 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006994 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006995 BO->getName());
6996 InsertNewInstBefore(NewRem, ICI);
6997 return new ICmpInst(ICI.getPredicate(), NewRem,
6998 Constant::getNullValue(BO->getType()));
6999 }
7000 }
7001 break;
7002 case Instruction::Add:
7003 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7004 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7005 if (BO->hasOneUse())
7006 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohman8fd520a2009-06-15 22:12:54 +00007007 ConstantExpr::getSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007008 } else if (RHSV == 0) {
7009 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7010 // efficiently invertible, or if the add has just this one use.
7011 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7012
7013 if (Value *NegVal = dyn_castNegVal(BOp1))
7014 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7015 else if (Value *NegVal = dyn_castNegVal(BOp0))
7016 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7017 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007018 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007019 InsertNewInstBefore(Neg, ICI);
7020 Neg->takeName(BO);
7021 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7022 }
7023 }
7024 break;
7025 case Instruction::Xor:
7026 // For the xor case, we can xor two constants together, eliminating
7027 // the explicit xor.
7028 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7029 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7030 ConstantExpr::getXor(RHS, BOC));
7031
7032 // FALLTHROUGH
7033 case Instruction::Sub:
7034 // Replace (([sub|xor] A, B) != 0) with (A != B)
7035 if (RHSV == 0)
7036 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7037 BO->getOperand(1));
7038 break;
7039
7040 case Instruction::Or:
7041 // If bits are being or'd in that are not present in the constant we
7042 // are comparing against, then the comparison could never succeed!
7043 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7044 Constant *NotCI = ConstantExpr::getNot(RHS);
7045 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7046 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7047 isICMP_NE));
7048 }
7049 break;
7050
7051 case Instruction::And:
7052 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7053 // If bits are being compared against that are and'd out, then the
7054 // comparison can never succeed!
7055 if ((RHSV & ~BOC->getValue()) != 0)
7056 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7057 isICMP_NE));
7058
7059 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7060 if (RHS == BOC && RHSV.isPowerOf2())
7061 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7062 ICmpInst::ICMP_NE, LHSI,
7063 Constant::getNullValue(RHS->getType()));
7064
7065 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007066 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007067 Value *X = BO->getOperand(0);
7068 Constant *Zero = Constant::getNullValue(X->getType());
7069 ICmpInst::Predicate pred = isICMP_NE ?
7070 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7071 return new ICmpInst(pred, X, Zero);
7072 }
7073
7074 // ((X & ~7) == 0) --> X < 8
7075 if (RHSV == 0 && isHighOnes(BOC)) {
7076 Value *X = BO->getOperand(0);
7077 Constant *NegX = ConstantExpr::getNeg(BOC);
7078 ICmpInst::Predicate pred = isICMP_NE ?
7079 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7080 return new ICmpInst(pred, X, NegX);
7081 }
7082 }
7083 default: break;
7084 }
7085 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7086 // Handle icmp {eq|ne} <intrinsic>, intcst.
7087 if (II->getIntrinsicID() == Intrinsic::bswap) {
7088 AddToWorkList(II);
7089 ICI.setOperand(0, II->getOperand(1));
7090 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7091 return &ICI;
7092 }
7093 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007094 }
7095 return 0;
7096}
7097
7098/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7099/// We only handle extending casts so far.
7100///
7101Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7102 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7103 Value *LHSCIOp = LHSCI->getOperand(0);
7104 const Type *SrcTy = LHSCIOp->getType();
7105 const Type *DestTy = LHSCI->getType();
7106 Value *RHSCIOp;
7107
7108 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7109 // integer type is the same size as the pointer type.
7110 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7111 getTargetData().getPointerSizeInBits() ==
7112 cast<IntegerType>(DestTy)->getBitWidth()) {
7113 Value *RHSOp = 0;
7114 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7115 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7116 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7117 RHSOp = RHSC->getOperand(0);
7118 // If the pointer types don't match, insert a bitcast.
7119 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007120 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007121 }
7122
7123 if (RHSOp)
7124 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7125 }
7126
7127 // The code below only handles extension cast instructions, so far.
7128 // Enforce this.
7129 if (LHSCI->getOpcode() != Instruction::ZExt &&
7130 LHSCI->getOpcode() != Instruction::SExt)
7131 return 0;
7132
7133 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7134 bool isSignedCmp = ICI.isSignedPredicate();
7135
7136 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7137 // Not an extension from the same type?
7138 RHSCIOp = CI->getOperand(0);
7139 if (RHSCIOp->getType() != LHSCIOp->getType())
7140 return 0;
7141
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007142 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143 // and the other is a zext), then we can't handle this.
7144 if (CI->getOpcode() != LHSCI->getOpcode())
7145 return 0;
7146
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007147 // Deal with equality cases early.
7148 if (ICI.isEquality())
7149 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7150
7151 // A signed comparison of sign extended values simplifies into a
7152 // signed comparison.
7153 if (isSignedCmp && isSignedExt)
7154 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7155
7156 // The other three cases all fold into an unsigned comparison.
7157 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 }
7159
7160 // If we aren't dealing with a constant on the RHS, exit early
7161 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7162 if (!CI)
7163 return 0;
7164
7165 // Compute the constant that would happen if we truncated to SrcTy then
7166 // reextended to DestTy.
7167 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7168 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7169
7170 // If the re-extended constant didn't change...
7171 if (Res2 == CI) {
7172 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7173 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007174 // %A = sext i16 %X to i32
7175 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007176 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007177 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007178 // because %A may have negative value.
7179 //
Chris Lattner3d816532008-07-11 04:09:09 +00007180 // However, we allow this when the compare is EQ/NE, because they are
7181 // signless.
7182 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007183 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007184 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007185 }
7186
7187 // The re-extended constant changed so the constant cannot be represented
7188 // in the shorter type. Consequently, we cannot emit a simple comparison.
7189
7190 // First, handle some easy cases. We know the result cannot be equal at this
7191 // point so handle the ICI.isEquality() cases
7192 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7193 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7194 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7195 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7196
7197 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7198 // should have been folded away previously and not enter in here.
7199 Value *Result;
7200 if (isSignedCmp) {
7201 // We're performing a signed comparison.
7202 if (cast<ConstantInt>(CI)->getValue().isNegative())
7203 Result = ConstantInt::getFalse(); // X < (small) --> false
7204 else
7205 Result = ConstantInt::getTrue(); // X < (large) --> true
7206 } else {
7207 // We're performing an unsigned comparison.
7208 if (isSignedExt) {
7209 // We're performing an unsigned comp with a sign extended value.
7210 // This is true if the input is >= 0. [aka >s -1]
7211 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7212 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7213 NegOne, ICI.getName()), ICI);
7214 } else {
7215 // Unsigned extend & unsigned compare -> always true.
7216 Result = ConstantInt::getTrue();
7217 }
7218 }
7219
7220 // Finally, return the value computed.
7221 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007222 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007223 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007224
7225 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7226 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7227 "ICmp should be folded!");
7228 if (Constant *CI = dyn_cast<Constant>(Result))
7229 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7230 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007231}
7232
7233Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7234 return commonShiftTransforms(I);
7235}
7236
7237Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7238 return commonShiftTransforms(I);
7239}
7240
7241Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007242 if (Instruction *R = commonShiftTransforms(I))
7243 return R;
7244
7245 Value *Op0 = I.getOperand(0);
7246
7247 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7248 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7249 if (CSI->isAllOnesValue())
7250 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007251
Dan Gohman2526aea2009-06-16 19:55:29 +00007252 // See if we can turn a signed shr into an unsigned shr.
7253 if (MaskedValueIsZero(Op0,
7254 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7255 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7256
7257 // Arithmetic shifting an all-sign-bit value is a no-op.
7258 unsigned NumSignBits = ComputeNumSignBits(Op0);
7259 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7260 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007261
Chris Lattnere3c504f2007-12-06 01:59:46 +00007262 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007263}
7264
7265Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7266 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7268
7269 // shl X, 0 == X and shr X, 0 == X
7270 // shl 0, X == 0 and shr 0, X == 0
7271 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7272 Op0 == Constant::getNullValue(Op0->getType()))
7273 return ReplaceInstUsesWith(I, Op0);
7274
7275 if (isa<UndefValue>(Op0)) {
7276 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7277 return ReplaceInstUsesWith(I, Op0);
7278 else // undef << X -> 0, undef >>u X -> 0
7279 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7280 }
7281 if (isa<UndefValue>(Op1)) {
7282 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7283 return ReplaceInstUsesWith(I, Op0);
7284 else // X << undef, X >>u undef -> 0
7285 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7286 }
7287
Dan Gohman2bc21562009-05-21 02:28:33 +00007288 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007289 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007290 return &I;
7291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007292 // Try to fold constant and into select arguments.
7293 if (isa<Constant>(Op0))
7294 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7295 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7296 return R;
7297
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7299 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7300 return Res;
7301 return 0;
7302}
7303
7304Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7305 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007306 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007307
7308 // See if we can simplify any instructions used by the instruction whose sole
7309 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007310 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007311
Dan Gohman9e1657f2009-06-14 23:30:43 +00007312 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7313 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007314 //
7315 if (Op1->uge(TypeBits)) {
7316 if (I.getOpcode() != Instruction::AShr)
7317 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7318 else {
7319 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7320 return &I;
7321 }
7322 }
7323
7324 // ((X*C1) << C2) == (X * (C1 << C2))
7325 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7326 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7327 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007328 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007329 ConstantExpr::getShl(BOOp, Op1));
7330
7331 // Try to fold constant and into select arguments.
7332 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7333 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7334 return R;
7335 if (isa<PHINode>(Op0))
7336 if (Instruction *NV = FoldOpIntoPhi(I))
7337 return NV;
7338
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007339 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7340 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7341 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7342 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7343 // place. Don't try to do this transformation in this case. Also, we
7344 // require that the input operand is a shift-by-constant so that we have
7345 // confidence that the shifts will get folded together. We could do this
7346 // xform in more cases, but it is unlikely to be profitable.
7347 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7348 isa<ConstantInt>(TrOp->getOperand(1))) {
7349 // Okay, we'll do this xform. Make the shift of shift.
7350 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007351 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007352 I.getName());
7353 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7354
7355 // For logical shifts, the truncation has the effect of making the high
7356 // part of the register be zeros. Emulate this by inserting an AND to
7357 // clear the top bits as needed. This 'and' will usually be zapped by
7358 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007359 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7360 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007361 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7362
7363 // The mask we constructed says what the trunc would do if occurring
7364 // between the shifts. We want to know the effect *after* the second
7365 // shift. We know that it is a logical shift by a constant, so adjust the
7366 // mask as appropriate.
7367 if (I.getOpcode() == Instruction::Shl)
7368 MaskV <<= Op1->getZExtValue();
7369 else {
7370 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7371 MaskV = MaskV.lshr(Op1->getZExtValue());
7372 }
7373
Gabor Greifa645dd32008-05-16 19:29:10 +00007374 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007375 TI->getName());
7376 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7377
7378 // Return the value truncated to the interesting size.
7379 return new TruncInst(And, I.getType());
7380 }
7381 }
7382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007383 if (Op0->hasOneUse()) {
7384 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7385 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7386 Value *V1, *V2;
7387 ConstantInt *CC;
7388 switch (Op0BO->getOpcode()) {
7389 default: break;
7390 case Instruction::Add:
7391 case Instruction::And:
7392 case Instruction::Or:
7393 case Instruction::Xor: {
7394 // These operators commute.
7395 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7396 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007397 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007398 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007399 Op0BO->getOperand(0), Op1,
7400 Op0BO->getName());
7401 InsertNewInstBefore(YS, I); // (Y << C)
7402 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007403 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007404 Op0BO->getOperand(1)->getName());
7405 InsertNewInstBefore(X, I); // (X + (Y << C))
7406 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007407 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007408 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7409 }
7410
7411 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7412 Value *Op0BOOp1 = Op0BO->getOperand(1);
7413 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7414 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007415 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7416 m_ConstantInt(CC))) &&
7417 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007418 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007419 Op0BO->getOperand(0), Op1,
7420 Op0BO->getName());
7421 InsertNewInstBefore(YS, I); // (Y << C)
7422 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007423 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007424 V1->getName()+".mask");
7425 InsertNewInstBefore(XM, I); // X & (CC << C)
7426
Gabor Greifa645dd32008-05-16 19:29:10 +00007427 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007428 }
7429 }
7430
7431 // FALL THROUGH.
7432 case Instruction::Sub: {
7433 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7434 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007435 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007436 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007437 Op0BO->getOperand(1), Op1,
7438 Op0BO->getName());
7439 InsertNewInstBefore(YS, I); // (Y << C)
7440 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007441 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007442 Op0BO->getOperand(0)->getName());
7443 InsertNewInstBefore(X, I); // (X + (Y << C))
7444 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007445 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007446 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7447 }
7448
7449 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7450 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7451 match(Op0BO->getOperand(0),
7452 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7453 m_ConstantInt(CC))) && V2 == Op1 &&
7454 cast<BinaryOperator>(Op0BO->getOperand(0))
7455 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007456 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007457 Op0BO->getOperand(1), Op1,
7458 Op0BO->getName());
7459 InsertNewInstBefore(YS, I); // (Y << C)
7460 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007461 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007462 V1->getName()+".mask");
7463 InsertNewInstBefore(XM, I); // X & (CC << C)
7464
Gabor Greifa645dd32008-05-16 19:29:10 +00007465 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007466 }
7467
7468 break;
7469 }
7470 }
7471
7472
7473 // If the operand is an bitwise operator with a constant RHS, and the
7474 // shift is the only use, we can pull it out of the shift.
7475 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7476 bool isValid = true; // Valid only for And, Or, Xor
7477 bool highBitSet = false; // Transform if high bit of constant set?
7478
7479 switch (Op0BO->getOpcode()) {
7480 default: isValid = false; break; // Do not perform transform!
7481 case Instruction::Add:
7482 isValid = isLeftShift;
7483 break;
7484 case Instruction::Or:
7485 case Instruction::Xor:
7486 highBitSet = false;
7487 break;
7488 case Instruction::And:
7489 highBitSet = true;
7490 break;
7491 }
7492
7493 // If this is a signed shift right, and the high bit is modified
7494 // by the logical operation, do not perform the transformation.
7495 // The highBitSet boolean indicates the value of the high bit of
7496 // the constant which would cause it to be modified for this
7497 // operation.
7498 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007499 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007500 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007501
7502 if (isValid) {
7503 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7504
7505 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007506 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007507 InsertNewInstBefore(NewShift, I);
7508 NewShift->takeName(Op0BO);
7509
Gabor Greifa645dd32008-05-16 19:29:10 +00007510 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007511 NewRHS);
7512 }
7513 }
7514 }
7515 }
7516
7517 // Find out if this is a shift of a shift by a constant.
7518 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7519 if (ShiftOp && !ShiftOp->isShift())
7520 ShiftOp = 0;
7521
7522 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7523 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7524 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7525 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7526 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7527 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7528 Value *X = ShiftOp->getOperand(0);
7529
7530 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007531
7532 const IntegerType *Ty = cast<IntegerType>(I.getType());
7533
7534 // Check for (X << c1) << c2 and (X >> c1) >> c2
7535 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007536 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7537 // saturates.
7538 if (AmtSum >= TypeBits) {
7539 if (I.getOpcode() != Instruction::AShr)
7540 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7541 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7542 }
7543
Gabor Greifa645dd32008-05-16 19:29:10 +00007544 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007545 ConstantInt::get(Ty, AmtSum));
7546 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7547 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007548 if (AmtSum >= TypeBits)
7549 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7550
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007551 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00007552 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007553 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7554 I.getOpcode() == Instruction::LShr) {
7555 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007556 if (AmtSum >= TypeBits)
7557 AmtSum = TypeBits-1;
7558
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007559 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007560 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007561 InsertNewInstBefore(Shift, I);
7562
7563 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007564 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007565 }
7566
7567 // Okay, if we get here, one shift must be left, and the other shift must be
7568 // right. See if the amounts are equal.
7569 if (ShiftAmt1 == ShiftAmt2) {
7570 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7571 if (I.getOpcode() == Instruction::Shl) {
7572 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007573 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007574 }
7575 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7576 if (I.getOpcode() == Instruction::LShr) {
7577 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007578 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007579 }
7580 // We can simplify ((X << C) >>s C) into a trunc + sext.
7581 // NOTE: we could do this for any C, but that would make 'unusual' integer
7582 // types. For now, just stick to ones well-supported by the code
7583 // generators.
7584 const Type *SExtType = 0;
7585 switch (Ty->getBitWidth() - ShiftAmt1) {
7586 case 1 :
7587 case 8 :
7588 case 16 :
7589 case 32 :
7590 case 64 :
7591 case 128:
7592 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7593 break;
7594 default: break;
7595 }
7596 if (SExtType) {
7597 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7598 InsertNewInstBefore(NewTrunc, I);
7599 return new SExtInst(NewTrunc, Ty);
7600 }
7601 // Otherwise, we can't handle it yet.
7602 } else if (ShiftAmt1 < ShiftAmt2) {
7603 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7604
7605 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7606 if (I.getOpcode() == Instruction::Shl) {
7607 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7608 ShiftOp->getOpcode() == Instruction::AShr);
7609 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007610 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007611 InsertNewInstBefore(Shift, I);
7612
7613 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007614 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007615 }
7616
7617 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7618 if (I.getOpcode() == Instruction::LShr) {
7619 assert(ShiftOp->getOpcode() == Instruction::Shl);
7620 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007621 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007622 InsertNewInstBefore(Shift, I);
7623
7624 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007625 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007626 }
7627
7628 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7629 } else {
7630 assert(ShiftAmt2 < ShiftAmt1);
7631 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7632
7633 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7634 if (I.getOpcode() == Instruction::Shl) {
7635 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7636 ShiftOp->getOpcode() == Instruction::AShr);
7637 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007638 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007639 ConstantInt::get(Ty, ShiftDiff));
7640 InsertNewInstBefore(Shift, I);
7641
7642 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007643 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007644 }
7645
7646 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7647 if (I.getOpcode() == Instruction::LShr) {
7648 assert(ShiftOp->getOpcode() == Instruction::Shl);
7649 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007650 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007651 InsertNewInstBefore(Shift, I);
7652
7653 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007654 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655 }
7656
7657 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7658 }
7659 }
7660 return 0;
7661}
7662
7663
7664/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7665/// expression. If so, decompose it, returning some value X, such that Val is
7666/// X*Scale+Offset.
7667///
7668static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7669 int &Offset) {
7670 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7671 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7672 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007673 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007674 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007675 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7676 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7677 if (I->getOpcode() == Instruction::Shl) {
7678 // This is a value scaled by '1 << the shift amt'.
7679 Scale = 1U << RHS->getZExtValue();
7680 Offset = 0;
7681 return I->getOperand(0);
7682 } else if (I->getOpcode() == Instruction::Mul) {
7683 // This value is scaled by 'RHS'.
7684 Scale = RHS->getZExtValue();
7685 Offset = 0;
7686 return I->getOperand(0);
7687 } else if (I->getOpcode() == Instruction::Add) {
7688 // We have X+C. Check to see if we really have (X*C2)+C1,
7689 // where C1 is divisible by C2.
7690 unsigned SubScale;
7691 Value *SubVal =
7692 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7693 Offset += RHS->getZExtValue();
7694 Scale = SubScale;
7695 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007696 }
7697 }
7698 }
7699
7700 // Otherwise, we can't look past this.
7701 Scale = 1;
7702 Offset = 0;
7703 return Val;
7704}
7705
7706
7707/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7708/// try to eliminate the cast by moving the type information into the alloc.
7709Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7710 AllocationInst &AI) {
7711 const PointerType *PTy = cast<PointerType>(CI.getType());
7712
7713 // Remove any uses of AI that are dead.
7714 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7715
7716 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7717 Instruction *User = cast<Instruction>(*UI++);
7718 if (isInstructionTriviallyDead(User)) {
7719 while (UI != E && *UI == User)
7720 ++UI; // If this instruction uses AI more than once, don't break UI.
7721
7722 ++NumDeadInst;
7723 DOUT << "IC: DCE: " << *User;
7724 EraseInstFromFunction(*User);
7725 }
7726 }
7727
7728 // Get the type really allocated and the type casted to.
7729 const Type *AllocElTy = AI.getAllocatedType();
7730 const Type *CastElTy = PTy->getElementType();
7731 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7732
7733 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7734 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7735 if (CastElTyAlign < AllocElTyAlign) return 0;
7736
7737 // If the allocation has multiple uses, only promote it if we are strictly
7738 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007739 // same, we open the door to infinite loops of various kinds. (A reference
7740 // from a dbg.declare doesn't count as a use for this purpose.)
7741 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7742 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007743
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007744 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7745 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007746 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7747
7748 // See if we can satisfy the modulus by pulling a scale out of the array
7749 // size argument.
7750 unsigned ArraySizeScale;
7751 int ArrayOffset;
7752 Value *NumElements = // See if the array size is a decomposable linear expr.
7753 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7754
7755 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7756 // do the xform.
7757 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7758 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7759
7760 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7761 Value *Amt = 0;
7762 if (Scale == 1) {
7763 Amt = NumElements;
7764 } else {
7765 // If the allocation size is constant, form a constant mul expression
7766 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7767 if (isa<ConstantInt>(NumElements))
Dan Gohman8fd520a2009-06-15 22:12:54 +00007768 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7769 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007770 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007771 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007772 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007773 Amt = InsertNewInstBefore(Tmp, AI);
7774 }
7775 }
7776
7777 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7778 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007779 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007780 Amt = InsertNewInstBefore(Tmp, AI);
7781 }
7782
7783 AllocationInst *New;
7784 if (isa<MallocInst>(AI))
7785 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7786 else
7787 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7788 InsertNewInstBefore(New, AI);
7789 New->takeName(&AI);
7790
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007791 // If the allocation has one real use plus a dbg.declare, just remove the
7792 // declare.
7793 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7794 EraseInstFromFunction(*DI);
7795 }
7796 // If the allocation has multiple real uses, insert a cast and change all
7797 // things that used it to use the new cast. This will also hack on CI, but it
7798 // will die soon.
7799 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007800 AddUsesToWorkList(AI);
7801 // New is the allocation instruction, pointer typed. AI is the original
7802 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7803 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7804 InsertNewInstBefore(NewCast, AI);
7805 AI.replaceAllUsesWith(NewCast);
7806 }
7807 return ReplaceInstUsesWith(CI, New);
7808}
7809
7810/// CanEvaluateInDifferentType - Return true if we can take the specified value
7811/// and return it as type Ty without inserting any new casts and without
7812/// changing the computed value. This is used by code that tries to decide
7813/// whether promoting or shrinking integer operations to wider or smaller types
7814/// will allow us to eliminate a truncate or extend.
7815///
7816/// This is a truncation operation if Ty is smaller than V->getType(), or an
7817/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007818///
7819/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7820/// should return true if trunc(V) can be computed by computing V in the smaller
7821/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7822/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7823/// efficiently truncated.
7824///
7825/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7826/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7827/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007828bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007829 unsigned CastOpc,
7830 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007831 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007832 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007833 return true;
7834
7835 Instruction *I = dyn_cast<Instruction>(V);
7836 if (!I) return false;
7837
Dan Gohman8fd520a2009-06-15 22:12:54 +00007838 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007839
Chris Lattneref70bb82007-08-02 06:11:14 +00007840 // If this is an extension or truncate, we can often eliminate it.
7841 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7842 // If this is a cast from the destination type, we can trivially eliminate
7843 // it, and this will remove a cast overall.
7844 if (I->getOperand(0)->getType() == Ty) {
7845 // If the first operand is itself a cast, and is eliminable, do not count
7846 // this as an eliminable cast. We would prefer to eliminate those two
7847 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007848 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007849 ++NumCastsRemoved;
7850 return true;
7851 }
7852 }
7853
7854 // We can't extend or shrink something that has multiple uses: doing so would
7855 // require duplicating the instruction in general, which isn't profitable.
7856 if (!I->hasOneUse()) return false;
7857
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007858 unsigned Opc = I->getOpcode();
7859 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007860 case Instruction::Add:
7861 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007862 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007863 case Instruction::And:
7864 case Instruction::Or:
7865 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007866 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007867 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007868 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007869 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007870 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007871
7872 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007873 // If we are truncating the result of this SHL, and if it's a shift of a
7874 // constant amount, we can always perform a SHL in a smaller type.
7875 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007876 uint32_t BitWidth = Ty->getScalarSizeInBits();
7877 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007878 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007879 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007880 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007881 }
7882 break;
7883 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007884 // If this is a truncate of a logical shr, we can truncate it to a smaller
7885 // lshr iff we know that the bits we would otherwise be shifting in are
7886 // already zeros.
7887 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007888 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7889 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007890 if (BitWidth < OrigBitWidth &&
7891 MaskedValueIsZero(I->getOperand(0),
7892 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7893 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007894 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007895 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007896 }
7897 }
7898 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007899 case Instruction::ZExt:
7900 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007901 case Instruction::Trunc:
7902 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007903 // can safely replace it. Note that replacing it does not reduce the number
7904 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007905 if (Opc == CastOpc)
7906 return true;
7907
7908 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007909 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007910 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007911 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007912 case Instruction::Select: {
7913 SelectInst *SI = cast<SelectInst>(I);
7914 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007915 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007916 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007917 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007918 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007919 case Instruction::PHI: {
7920 // We can change a phi if we can change all operands.
7921 PHINode *PN = cast<PHINode>(I);
7922 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7923 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007924 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007925 return false;
7926 return true;
7927 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928 default:
7929 // TODO: Can handle more cases here.
7930 break;
7931 }
7932
7933 return false;
7934}
7935
7936/// EvaluateInDifferentType - Given an expression that
7937/// CanEvaluateInDifferentType returns true for, actually insert the code to
7938/// evaluate the expression.
7939Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7940 bool isSigned) {
7941 if (Constant *C = dyn_cast<Constant>(V))
7942 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7943
7944 // Otherwise, it must be an instruction.
7945 Instruction *I = cast<Instruction>(V);
7946 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007947 unsigned Opc = I->getOpcode();
7948 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007949 case Instruction::Add:
7950 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007951 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007952 case Instruction::And:
7953 case Instruction::Or:
7954 case Instruction::Xor:
7955 case Instruction::AShr:
7956 case Instruction::LShr:
7957 case Instruction::Shl: {
7958 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7959 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007960 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007961 break;
7962 }
7963 case Instruction::Trunc:
7964 case Instruction::ZExt:
7965 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007966 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007967 // just return the source. There's no need to insert it because it is not
7968 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007969 if (I->getOperand(0)->getType() == Ty)
7970 return I->getOperand(0);
7971
Chris Lattner4200c2062008-06-18 04:00:49 +00007972 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007973 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007974 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007975 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007976 case Instruction::Select: {
7977 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7978 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7979 Res = SelectInst::Create(I->getOperand(0), True, False);
7980 break;
7981 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007982 case Instruction::PHI: {
7983 PHINode *OPN = cast<PHINode>(I);
7984 PHINode *NPN = PHINode::Create(Ty);
7985 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7986 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7987 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7988 }
7989 Res = NPN;
7990 break;
7991 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992 default:
7993 // TODO: Can handle more cases here.
7994 assert(0 && "Unreachable!");
7995 break;
7996 }
7997
Chris Lattner4200c2062008-06-18 04:00:49 +00007998 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007999 return InsertNewInstBefore(Res, *I);
8000}
8001
8002/// @brief Implement the transforms common to all CastInst visitors.
8003Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8004 Value *Src = CI.getOperand(0);
8005
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008006 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8007 // eliminate it now.
8008 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8009 if (Instruction::CastOps opc =
8010 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8011 // The first cast (CSrc) is eliminable so we need to fix up or replace
8012 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008013 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008014 }
8015 }
8016
8017 // If we are casting a select then fold the cast into the select
8018 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8019 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8020 return NV;
8021
8022 // If we are casting a PHI then fold the cast into the PHI
8023 if (isa<PHINode>(Src))
8024 if (Instruction *NV = FoldOpIntoPhi(CI))
8025 return NV;
8026
8027 return 0;
8028}
8029
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008030/// FindElementAtOffset - Given a type and a constant offset, determine whether
8031/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008032/// the specified offset. If so, fill them into NewIndices and return the
8033/// resultant element type, otherwise return null.
8034static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8035 SmallVectorImpl<Value*> &NewIndices,
8036 const TargetData *TD) {
8037 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008038
8039 // Start with the index over the outer type. Note that the type size
8040 // might be zero (even if the offset isn't zero) if the indexed type
8041 // is something like [0 x {int, int}]
8042 const Type *IntPtrTy = TD->getIntPtrType();
8043 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008044 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008045 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008046 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008047
Chris Lattnerce48c462009-01-11 20:15:20 +00008048 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008049 if (Offset < 0) {
8050 --FirstIdx;
8051 Offset += TySize;
8052 assert(Offset >= 0);
8053 }
8054 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8055 }
8056
8057 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8058
8059 // Index into the types. If we fail, set OrigBase to null.
8060 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008061 // Indexing into tail padding between struct/array elements.
8062 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008063 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008064
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008065 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8066 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008067 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8068 "Offset must stay within the indexed type");
8069
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008070 unsigned Elt = SL->getElementContainingOffset(Offset);
8071 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8072
8073 Offset -= SL->getElementOffset(Elt);
8074 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008075 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008076 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008077 assert(EltSize && "Cannot index into a zero-sized array");
8078 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8079 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008080 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008081 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008082 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008083 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008084 }
8085 }
8086
Chris Lattner54dddc72009-01-24 01:00:13 +00008087 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008088}
8089
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008090/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8091Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8092 Value *Src = CI.getOperand(0);
8093
8094 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8095 // If casting the result of a getelementptr instruction with no offset, turn
8096 // this into a cast of the original pointer!
8097 if (GEP->hasAllZeroIndices()) {
8098 // Changing the cast operand is usually not a good idea but it is safe
8099 // here because the pointer operand is being replaced with another
8100 // pointer operand so the opcode doesn't need to change.
8101 AddToWorkList(GEP);
8102 CI.setOperand(0, GEP->getOperand(0));
8103 return &CI;
8104 }
8105
8106 // If the GEP has a single use, and the base pointer is a bitcast, and the
8107 // GEP computes a constant offset, see if we can convert these three
8108 // instructions into fewer. This typically happens with unions and other
8109 // non-type-safe code.
8110 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8111 if (GEP->hasAllConstantIndices()) {
8112 // We are guaranteed to get a constant from EmitGEPOffset.
8113 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8114 int64_t Offset = OffsetV->getSExtValue();
8115
8116 // Get the base pointer input of the bitcast, and the type it points to.
8117 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8118 const Type *GEPIdxTy =
8119 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008120 SmallVector<Value*, 8> NewIndices;
8121 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8122 // If we were able to index down into an element, create the GEP
8123 // and bitcast the result. This eliminates one bitcast, potentially
8124 // two.
8125 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8126 NewIndices.begin(),
8127 NewIndices.end(), "");
8128 InsertNewInstBefore(NGEP, CI);
8129 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008130
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008131 if (isa<BitCastInst>(CI))
8132 return new BitCastInst(NGEP, CI.getType());
8133 assert(isa<PtrToIntInst>(CI));
8134 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008135 }
8136 }
8137 }
8138 }
8139
8140 return commonCastTransforms(CI);
8141}
8142
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008143/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8144/// type like i42. We don't want to introduce operations on random non-legal
8145/// integer types where they don't already exist in the code. In the future,
8146/// we should consider making this based off target-data, so that 32-bit targets
8147/// won't get i64 operations etc.
8148static bool isSafeIntegerType(const Type *Ty) {
8149 switch (Ty->getPrimitiveSizeInBits()) {
8150 case 8:
8151 case 16:
8152 case 32:
8153 case 64:
8154 return true;
8155 default:
8156 return false;
8157 }
8158}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008159
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008160/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8161/// integer types. This function implements the common transforms for all those
8162/// cases.
8163/// @brief Implement the transforms common to CastInst with integer operands
8164Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8165 if (Instruction *Result = commonCastTransforms(CI))
8166 return Result;
8167
8168 Value *Src = CI.getOperand(0);
8169 const Type *SrcTy = Src->getType();
8170 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008171 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8172 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008173
8174 // See if we can simplify any instructions used by the LHS whose sole
8175 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008176 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008177 return &CI;
8178
8179 // If the source isn't an instruction or has more than one use then we
8180 // can't do anything more.
8181 Instruction *SrcI = dyn_cast<Instruction>(Src);
8182 if (!SrcI || !Src->hasOneUse())
8183 return 0;
8184
8185 // Attempt to propagate the cast into the instruction for int->int casts.
8186 int NumCastsRemoved = 0;
8187 if (!isa<BitCastInst>(CI) &&
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008188 // Only do this if the dest type is a simple type, don't convert the
8189 // expression tree to something weird like i93 unless the source is also
8190 // strange.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008191 (isSafeIntegerType(DestTy->getScalarType()) ||
8192 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8193 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008194 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008195 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008196 // eliminates the cast, so it is always a win. If this is a zero-extension,
8197 // we need to do an AND to maintain the clear top-part of the computation,
8198 // so we require that the input have eliminated at least one cast. If this
8199 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008200 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008201 bool DoXForm = false;
8202 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008203 switch (CI.getOpcode()) {
8204 default:
8205 // All the others use floating point so we shouldn't actually
8206 // get here because of the check above.
8207 assert(0 && "Unknown cast type");
8208 case Instruction::Trunc:
8209 DoXForm = true;
8210 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008211 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008212 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008213 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008214 // If it's unnecessary to issue an AND to clear the high bits, it's
8215 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008216 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008217 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8218 if (MaskedValueIsZero(TryRes, Mask))
8219 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008220
8221 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008222 if (TryI->use_empty())
8223 EraseInstFromFunction(*TryI);
8224 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008225 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008226 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008227 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008228 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008229 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008230 // If we do not have to emit the truncate + sext pair, then it's always
8231 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008232 //
8233 // It's not safe to eliminate the trunc + sext pair if one of the
8234 // eliminated cast is a truncate. e.g.
8235 // t2 = trunc i32 t1 to i16
8236 // t3 = sext i16 t2 to i32
8237 // !=
8238 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008239 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008240 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8241 if (NumSignBits > (DestBitSize - SrcBitSize))
8242 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008243
8244 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008245 if (TryI->use_empty())
8246 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008247 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008248 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008249 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008250 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008251
8252 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008253 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8254 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008255 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8256 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008257 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008258 // Just replace this cast with the result.
8259 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008260
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008261 assert(Res->getType() == DestTy);
8262 switch (CI.getOpcode()) {
8263 default: assert(0 && "Unknown cast type!");
8264 case Instruction::Trunc:
8265 case Instruction::BitCast:
8266 // Just replace this cast with the result.
8267 return ReplaceInstUsesWith(CI, Res);
8268 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008269 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008270
8271 // If the high bits are already zero, just replace this cast with the
8272 // result.
8273 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8274 if (MaskedValueIsZero(Res, Mask))
8275 return ReplaceInstUsesWith(CI, Res);
8276
8277 // We need to emit an AND to clear the high bits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008278 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8279 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008280 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008281 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008282 case Instruction::SExt: {
8283 // If the high bits are already filled with sign bit, just replace this
8284 // cast with the result.
8285 unsigned NumSignBits = ComputeNumSignBits(Res);
8286 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008287 return ReplaceInstUsesWith(CI, Res);
8288
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008289 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008290 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008291 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8292 CI), DestTy);
8293 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008294 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008295 }
8296 }
8297
8298 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8299 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8300
8301 switch (SrcI->getOpcode()) {
8302 case Instruction::Add:
8303 case Instruction::Mul:
8304 case Instruction::And:
8305 case Instruction::Or:
8306 case Instruction::Xor:
8307 // If we are discarding information, rewrite.
8308 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8309 // Don't insert two casts if they cannot be eliminated. We allow
8310 // two casts to be inserted if the sizes are the same. This could
8311 // only be converting signedness, which is a noop.
8312 if (DestBitSize == SrcBitSize ||
8313 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8314 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8315 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman722b4792008-11-30 21:09:11 +00008316 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8317 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008318 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008319 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8320 }
8321 }
8322
8323 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8324 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8325 SrcI->getOpcode() == Instruction::Xor &&
8326 Op1 == ConstantInt::getTrue() &&
8327 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008328 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008329 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008330 }
8331 break;
8332 case Instruction::SDiv:
8333 case Instruction::UDiv:
8334 case Instruction::SRem:
8335 case Instruction::URem:
8336 // If we are just changing the sign, rewrite.
8337 if (DestBitSize == SrcBitSize) {
8338 // Don't insert two casts if they cannot be eliminated. We allow
8339 // two casts to be inserted if the sizes are the same. This could
8340 // only be converting signedness, which is a noop.
8341 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8342 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008343 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8344 Op0, DestTy, *SrcI);
8345 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8346 Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008347 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008348 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8349 }
8350 }
8351 break;
8352
8353 case Instruction::Shl:
8354 // Allow changing the sign of the source operand. Do not allow
8355 // changing the size of the shift, UNLESS the shift amount is a
8356 // constant. We must not change variable sized shifts to a smaller
8357 // size, because it is undefined to shift more bits out than exist
8358 // in the value.
8359 if (DestBitSize == SrcBitSize ||
8360 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8361 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8362 Instruction::BitCast : Instruction::Trunc);
Eli Friedman722b4792008-11-30 21:09:11 +00008363 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8364 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008365 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008366 }
8367 break;
8368 case Instruction::AShr:
8369 // If this is a signed shr, and if all bits shifted in are about to be
8370 // truncated off, turn it into an unsigned shr to allow greater
8371 // simplifications.
8372 if (DestBitSize < SrcBitSize &&
8373 isa<ConstantInt>(Op1)) {
8374 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8375 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8376 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00008377 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008378 }
8379 }
8380 break;
8381 }
8382 return 0;
8383}
8384
8385Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8386 if (Instruction *Result = commonIntCastTransforms(CI))
8387 return Result;
8388
8389 Value *Src = CI.getOperand(0);
8390 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008391 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8392 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008393
8394 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohman2526aea2009-06-16 19:55:29 +00008395 if (DestBitWidth == 1 &&
8396 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Chris Lattner32177f82009-03-24 18:15:30 +00008397 Constant *One = ConstantInt::get(Src->getType(), 1);
8398 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8399 Value *Zero = Constant::getNullValue(Src->getType());
8400 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8401 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008402
Chris Lattner32177f82009-03-24 18:15:30 +00008403 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8404 ConstantInt *ShAmtV = 0;
8405 Value *ShiftOp = 0;
8406 if (Src->hasOneUse() &&
8407 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8408 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8409
8410 // Get a mask for the bits shifting in.
8411 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8412 if (MaskedValueIsZero(ShiftOp, Mask)) {
8413 if (ShAmt >= DestBitWidth) // All zeros.
8414 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8415
8416 // Okay, we can shrink this. Truncate the input, then return a new
8417 // shift.
8418 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8419 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8420 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008421 }
8422 }
8423
8424 return 0;
8425}
8426
Evan Chenge3779cf2008-03-24 00:21:34 +00008427/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8428/// in order to eliminate the icmp.
8429Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8430 bool DoXform) {
8431 // If we are just checking for a icmp eq of a single bit and zext'ing it
8432 // to an integer, then shift the bit to the appropriate place and then
8433 // cast to integer to avoid the comparison.
8434 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8435 const APInt &Op1CV = Op1C->getValue();
8436
8437 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8438 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8439 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8440 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8441 if (!DoXform) return ICI;
8442
8443 Value *In = ICI->getOperand(0);
8444 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008445 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008446 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008447 In->getName()+".lobit"),
8448 CI);
8449 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008450 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008451 false/*ZExt*/, "tmp", &CI);
8452
8453 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8454 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008455 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008456 In->getName()+".not"),
8457 CI);
8458 }
8459
8460 return ReplaceInstUsesWith(CI, In);
8461 }
8462
8463
8464
8465 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8466 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8467 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8468 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8469 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8470 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8471 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8472 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8473 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8474 // This only works for EQ and NE
8475 ICI->isEquality()) {
8476 // If Op1C some other power of two, convert:
8477 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8478 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8479 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8480 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8481
8482 APInt KnownZeroMask(~KnownZero);
8483 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8484 if (!DoXform) return ICI;
8485
8486 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8487 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8488 // (X&4) == 2 --> false
8489 // (X&4) != 2 --> true
8490 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8491 Res = ConstantExpr::getZExt(Res, CI.getType());
8492 return ReplaceInstUsesWith(CI, Res);
8493 }
8494
8495 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8496 Value *In = ICI->getOperand(0);
8497 if (ShiftAmt) {
8498 // Perform a logical shr by shiftamt.
8499 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008500 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00008501 ConstantInt::get(In->getType(), ShiftAmt),
8502 In->getName()+".lobit"), CI);
8503 }
8504
8505 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8506 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008507 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008508 InsertNewInstBefore(cast<Instruction>(In), CI);
8509 }
8510
8511 if (CI.getType() == In->getType())
8512 return ReplaceInstUsesWith(CI, In);
8513 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008514 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008515 }
8516 }
8517 }
8518
8519 return 0;
8520}
8521
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008522Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8523 // If one of the common conversion will work ..
8524 if (Instruction *Result = commonIntCastTransforms(CI))
8525 return Result;
8526
8527 Value *Src = CI.getOperand(0);
8528
Chris Lattner215d56e2009-02-17 20:47:23 +00008529 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8530 // types and if the sizes are just right we can convert this into a logical
8531 // 'and' which will be much cheaper than the pair of casts.
8532 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8533 // Get the sizes of the types involved. We know that the intermediate type
8534 // will be smaller than A or C, but don't know the relation between A and C.
8535 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008536 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8537 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8538 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008539 // If we're actually extending zero bits, then if
8540 // SrcSize < DstSize: zext(a & mask)
8541 // SrcSize == DstSize: a & mask
8542 // SrcSize > DstSize: trunc(a) & mask
8543 if (SrcSize < DstSize) {
8544 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman8fd520a2009-06-15 22:12:54 +00008545 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008546 Instruction *And =
8547 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8548 InsertNewInstBefore(And, CI);
8549 return new ZExtInst(And, CI.getType());
8550 } else if (SrcSize == DstSize) {
8551 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman8fd520a2009-06-15 22:12:54 +00008552 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8553 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008554 } else if (SrcSize > DstSize) {
8555 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8556 InsertNewInstBefore(Trunc, CI);
8557 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Dan Gohman8fd520a2009-06-15 22:12:54 +00008558 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Trunc->getType(),
8559 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008560 }
8561 }
8562
Evan Chenge3779cf2008-03-24 00:21:34 +00008563 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8564 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008565
Evan Chenge3779cf2008-03-24 00:21:34 +00008566 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8567 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8568 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8569 // of the (zext icmp) will be transformed.
8570 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8571 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8572 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8573 (transformZExtICmp(LHS, CI, false) ||
8574 transformZExtICmp(RHS, CI, false))) {
8575 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8576 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008577 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008578 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008579 }
8580
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008581 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008582 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8583 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8584 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8585 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008586 if (TI0->getType() == CI.getType())
8587 return
8588 BinaryOperator::CreateAnd(TI0,
8589 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008590 }
8591
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008592 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8593 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8594 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8595 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8596 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8597 And->getOperand(1) == C)
8598 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8599 Value *TI0 = TI->getOperand(0);
8600 if (TI0->getType() == CI.getType()) {
8601 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8602 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8603 InsertNewInstBefore(NewAnd, *And);
8604 return BinaryOperator::CreateXor(NewAnd, ZC);
8605 }
8606 }
8607
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008608 return 0;
8609}
8610
8611Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8612 if (Instruction *I = commonIntCastTransforms(CI))
8613 return I;
8614
8615 Value *Src = CI.getOperand(0);
8616
Dan Gohman35b76162008-10-30 20:40:10 +00008617 // Canonicalize sign-extend from i1 to a select.
8618 if (Src->getType() == Type::Int1Ty)
8619 return SelectInst::Create(Src,
8620 ConstantInt::getAllOnesValue(CI.getType()),
8621 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008622
8623 // See if the value being truncated is already sign extended. If so, just
8624 // eliminate the trunc/sext pair.
8625 if (getOpcode(Src) == Instruction::Trunc) {
8626 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008627 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8628 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8629 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008630 unsigned NumSignBits = ComputeNumSignBits(Op);
8631
8632 if (OpBits == DestBits) {
8633 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8634 // bits, it is already ready.
8635 if (NumSignBits > DestBits-MidBits)
8636 return ReplaceInstUsesWith(CI, Op);
8637 } else if (OpBits < DestBits) {
8638 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8639 // bits, just sext from i32.
8640 if (NumSignBits > OpBits-MidBits)
8641 return new SExtInst(Op, CI.getType(), "tmp");
8642 } else {
8643 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8644 // bits, just truncate to i32.
8645 if (NumSignBits > OpBits-MidBits)
8646 return new TruncInst(Op, CI.getType(), "tmp");
8647 }
8648 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008649
8650 // If the input is a shl/ashr pair of a same constant, then this is a sign
8651 // extension from a smaller value. If we could trust arbitrary bitwidth
8652 // integers, we could turn this into a truncate to the smaller bit and then
8653 // use a sext for the whole extension. Since we don't, look deeper and check
8654 // for a truncate. If the source and dest are the same type, eliminate the
8655 // trunc and extend and just do shifts. For example, turn:
8656 // %a = trunc i32 %i to i8
8657 // %b = shl i8 %a, 6
8658 // %c = ashr i8 %b, 6
8659 // %d = sext i8 %c to i32
8660 // into:
8661 // %a = shl i32 %i, 30
8662 // %d = ashr i32 %a, 30
8663 Value *A = 0;
8664 ConstantInt *BA = 0, *CA = 0;
8665 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8666 m_ConstantInt(CA))) &&
8667 BA == CA && isa<TruncInst>(A)) {
8668 Value *I = cast<TruncInst>(A)->getOperand(0);
8669 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008670 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8671 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008672 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8673 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8674 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8675 CI.getName()), CI);
8676 return BinaryOperator::CreateAShr(I, ShAmtV);
8677 }
8678 }
8679
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008680 return 0;
8681}
8682
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008683/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8684/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008685static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008686 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008687 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008688 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8689 if (!losesInfo)
Chris Lattner5e0610f2008-04-20 00:41:09 +00008690 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008691 return 0;
8692}
8693
8694/// LookThroughFPExtensions - If this is an fp extension instruction, look
8695/// through it until we get the source value.
8696static Value *LookThroughFPExtensions(Value *V) {
8697 if (Instruction *I = dyn_cast<Instruction>(V))
8698 if (I->getOpcode() == Instruction::FPExt)
8699 return LookThroughFPExtensions(I->getOperand(0));
8700
8701 // If this value is a constant, return the constant in the smallest FP type
8702 // that can accurately represent it. This allows us to turn
8703 // (float)((double)X+2.0) into x+2.0f.
8704 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8705 if (CFP->getType() == Type::PPC_FP128Ty)
8706 return V; // No constant folding of this.
8707 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008708 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008709 return V;
8710 if (CFP->getType() == Type::DoubleTy)
8711 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008712 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008713 return V;
8714 // Don't try to shrink to various long double types.
8715 }
8716
8717 return V;
8718}
8719
8720Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8721 if (Instruction *I = commonCastTransforms(CI))
8722 return I;
8723
Dan Gohman7ce405e2009-06-04 22:49:04 +00008724 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008725 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008726 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008727 // many builtins (sqrt, etc).
8728 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8729 if (OpI && OpI->hasOneUse()) {
8730 switch (OpI->getOpcode()) {
8731 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008732 case Instruction::FAdd:
8733 case Instruction::FSub:
8734 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008735 case Instruction::FDiv:
8736 case Instruction::FRem:
8737 const Type *SrcTy = OpI->getType();
8738 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8739 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8740 if (LHSTrunc->getType() != SrcTy &&
8741 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008742 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008743 // If the source types were both smaller than the destination type of
8744 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008745 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8746 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008747 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8748 CI.getType(), CI);
8749 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8750 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008751 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008752 }
8753 }
8754 break;
8755 }
8756 }
8757 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008758}
8759
8760Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8761 return commonCastTransforms(CI);
8762}
8763
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008764Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008765 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8766 if (OpI == 0)
8767 return commonCastTransforms(FI);
8768
8769 // fptoui(uitofp(X)) --> X
8770 // fptoui(sitofp(X)) --> X
8771 // This is safe if the intermediate type has enough bits in its mantissa to
8772 // accurately represent all values of X. For example, do not do this with
8773 // i64->float->i64. This is also safe for sitofp case, because any negative
8774 // 'X' value would cause an undefined result for the fptoui.
8775 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8776 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008777 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008778 OpI->getType()->getFPMantissaWidth())
8779 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008780
8781 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008782}
8783
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008784Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008785 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8786 if (OpI == 0)
8787 return commonCastTransforms(FI);
8788
8789 // fptosi(sitofp(X)) --> X
8790 // fptosi(uitofp(X)) --> X
8791 // This is safe if the intermediate type has enough bits in its mantissa to
8792 // accurately represent all values of X. For example, do not do this with
8793 // i64->float->i64. This is also safe for sitofp case, because any negative
8794 // 'X' value would cause an undefined result for the fptoui.
8795 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8796 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008797 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008798 OpI->getType()->getFPMantissaWidth())
8799 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008800
8801 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008802}
8803
8804Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8805 return commonCastTransforms(CI);
8806}
8807
8808Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8809 return commonCastTransforms(CI);
8810}
8811
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008812Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8813 // If the destination integer type is smaller than the intptr_t type for
8814 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8815 // trunc to be exposed to other transforms. Don't do this for extending
8816 // ptrtoint's, because we don't know if the target sign or zero extends its
8817 // pointers.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008818 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008819 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8820 TD->getIntPtrType(),
8821 "tmp"), CI);
8822 return new TruncInst(P, CI.getType());
8823 }
8824
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008825 return commonPointerCastTransforms(CI);
8826}
8827
Chris Lattner7c1626482008-01-08 07:23:51 +00008828Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008829 // If the source integer type is larger than the intptr_t type for
8830 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8831 // allows the trunc to be exposed to other transforms. Don't do this for
8832 // extending inttoptr's, because we don't know if the target sign or zero
8833 // extends to pointers.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008834 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008835 TD->getPointerSizeInBits()) {
8836 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8837 TD->getIntPtrType(),
8838 "tmp"), CI);
8839 return new IntToPtrInst(P, CI.getType());
8840 }
8841
Chris Lattner7c1626482008-01-08 07:23:51 +00008842 if (Instruction *I = commonCastTransforms(CI))
8843 return I;
8844
8845 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8846 if (!DestPointee->isSized()) return 0;
8847
8848 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8849 ConstantInt *Cst;
8850 Value *X;
8851 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8852 m_ConstantInt(Cst)))) {
8853 // If the source and destination operands have the same type, see if this
8854 // is a single-index GEP.
8855 if (X->getType() == CI.getType()) {
8856 // Get the size of the pointee type.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008857 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008858
8859 // Convert the constant to intptr type.
8860 APInt Offset = Cst->getValue();
8861 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8862
8863 // If Offset is evenly divisible by Size, we can do this xform.
8864 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8865 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008866 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008867 }
8868 }
8869 // TODO: Could handle other cases, e.g. where add is indexing into field of
8870 // struct etc.
8871 } else if (CI.getOperand(0)->hasOneUse() &&
8872 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8873 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8874 // "inttoptr+GEP" instead of "add+intptr".
8875
8876 // Get the size of the pointee type.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008877 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008878
8879 // Convert the constant to intptr type.
8880 APInt Offset = Cst->getValue();
8881 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8882
8883 // If Offset is evenly divisible by Size, we can do this xform.
8884 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8885 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8886
8887 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8888 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008889 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008890 }
8891 }
8892 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008893}
8894
8895Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8896 // If the operands are integer typed then apply the integer transforms,
8897 // otherwise just apply the common ones.
8898 Value *Src = CI.getOperand(0);
8899 const Type *SrcTy = Src->getType();
8900 const Type *DestTy = CI.getType();
8901
8902 if (SrcTy->isInteger() && DestTy->isInteger()) {
8903 if (Instruction *Result = commonIntCastTransforms(CI))
8904 return Result;
8905 } else if (isa<PointerType>(SrcTy)) {
8906 if (Instruction *I = commonPointerCastTransforms(CI))
8907 return I;
8908 } else {
8909 if (Instruction *Result = commonCastTransforms(CI))
8910 return Result;
8911 }
8912
8913
8914 // Get rid of casts from one type to the same type. These are useless and can
8915 // be replaced by the operand.
8916 if (DestTy == Src->getType())
8917 return ReplaceInstUsesWith(CI, Src);
8918
8919 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8920 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8921 const Type *DstElTy = DstPTy->getElementType();
8922 const Type *SrcElTy = SrcPTy->getElementType();
8923
Nate Begemandf5b3612008-03-31 00:22:16 +00008924 // If the address spaces don't match, don't eliminate the bitcast, which is
8925 // required for changing types.
8926 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8927 return 0;
8928
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008929 // If we are casting a malloc or alloca to a pointer to a type of the same
8930 // size, rewrite the allocation instruction to allocate the "right" type.
8931 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8932 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8933 return V;
8934
8935 // If the source and destination are pointers, and this cast is equivalent
8936 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8937 // This can enhance SROA and other transforms that want type-safe pointers.
8938 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8939 unsigned NumZeros = 0;
8940 while (SrcElTy != DstElTy &&
8941 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8942 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8943 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8944 ++NumZeros;
8945 }
8946
8947 // If we found a path from the src to dest, create the getelementptr now.
8948 if (SrcElTy == DstElTy) {
8949 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008950 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8951 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008952 }
8953 }
8954
8955 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8956 if (SVI->hasOneUse()) {
8957 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8958 // a bitconvert to a vector with the same # elts.
8959 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008960 cast<VectorType>(DestTy)->getNumElements() ==
8961 SVI->getType()->getNumElements() &&
8962 SVI->getType()->getNumElements() ==
8963 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008964 CastInst *Tmp;
8965 // If either of the operands is a cast from CI.getType(), then
8966 // evaluating the shuffle in the casted destination's type will allow
8967 // us to eliminate at least one cast.
8968 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8969 Tmp->getOperand(0)->getType() == DestTy) ||
8970 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8971 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008972 Value *LHS = InsertCastBefore(Instruction::BitCast,
8973 SVI->getOperand(0), DestTy, CI);
8974 Value *RHS = InsertCastBefore(Instruction::BitCast,
8975 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008976 // Return a new shuffle vector. Use the same element ID's, as we
8977 // know the vector types match #elts.
8978 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8979 }
8980 }
8981 }
8982 }
8983 return 0;
8984}
8985
8986/// GetSelectFoldableOperands - We want to turn code that looks like this:
8987/// %C = or %A, %B
8988/// %D = select %cond, %C, %A
8989/// into:
8990/// %C = select %cond, %B, 0
8991/// %D = or %A, %C
8992///
8993/// Assuming that the specified instruction is an operand to the select, return
8994/// a bitmask indicating which operands of this instruction are foldable if they
8995/// equal the other incoming value of the select.
8996///
8997static unsigned GetSelectFoldableOperands(Instruction *I) {
8998 switch (I->getOpcode()) {
8999 case Instruction::Add:
9000 case Instruction::Mul:
9001 case Instruction::And:
9002 case Instruction::Or:
9003 case Instruction::Xor:
9004 return 3; // Can fold through either operand.
9005 case Instruction::Sub: // Can only fold on the amount subtracted.
9006 case Instruction::Shl: // Can only fold on the shift amount.
9007 case Instruction::LShr:
9008 case Instruction::AShr:
9009 return 1;
9010 default:
9011 return 0; // Cannot fold
9012 }
9013}
9014
9015/// GetSelectFoldableConstant - For the same transformation as the previous
9016/// function, return the identity constant that goes into the select.
9017static Constant *GetSelectFoldableConstant(Instruction *I) {
9018 switch (I->getOpcode()) {
9019 default: assert(0 && "This cannot happen!"); abort();
9020 case Instruction::Add:
9021 case Instruction::Sub:
9022 case Instruction::Or:
9023 case Instruction::Xor:
9024 case Instruction::Shl:
9025 case Instruction::LShr:
9026 case Instruction::AShr:
9027 return Constant::getNullValue(I->getType());
9028 case Instruction::And:
9029 return Constant::getAllOnesValue(I->getType());
9030 case Instruction::Mul:
9031 return ConstantInt::get(I->getType(), 1);
9032 }
9033}
9034
9035/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9036/// have the same opcode and only one use each. Try to simplify this.
9037Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9038 Instruction *FI) {
9039 if (TI->getNumOperands() == 1) {
9040 // If this is a non-volatile load or a cast from the same type,
9041 // merge.
9042 if (TI->isCast()) {
9043 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9044 return 0;
9045 } else {
9046 return 0; // unknown unary op.
9047 }
9048
9049 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009050 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9051 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009052 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009053 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009054 TI->getType());
9055 }
9056
9057 // Only handle binary operators here.
9058 if (!isa<BinaryOperator>(TI))
9059 return 0;
9060
9061 // Figure out if the operations have any operands in common.
9062 Value *MatchOp, *OtherOpT, *OtherOpF;
9063 bool MatchIsOpZero;
9064 if (TI->getOperand(0) == FI->getOperand(0)) {
9065 MatchOp = TI->getOperand(0);
9066 OtherOpT = TI->getOperand(1);
9067 OtherOpF = FI->getOperand(1);
9068 MatchIsOpZero = true;
9069 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9070 MatchOp = TI->getOperand(1);
9071 OtherOpT = TI->getOperand(0);
9072 OtherOpF = FI->getOperand(0);
9073 MatchIsOpZero = false;
9074 } else if (!TI->isCommutative()) {
9075 return 0;
9076 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9077 MatchOp = TI->getOperand(0);
9078 OtherOpT = TI->getOperand(1);
9079 OtherOpF = FI->getOperand(0);
9080 MatchIsOpZero = true;
9081 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9082 MatchOp = TI->getOperand(1);
9083 OtherOpT = TI->getOperand(0);
9084 OtherOpF = FI->getOperand(1);
9085 MatchIsOpZero = true;
9086 } else {
9087 return 0;
9088 }
9089
9090 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009091 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9092 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009093 InsertNewInstBefore(NewSI, SI);
9094
9095 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9096 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009097 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009098 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009099 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009100 }
9101 assert(0 && "Shouldn't get here");
9102 return 0;
9103}
9104
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009105static bool isSelect01(Constant *C1, Constant *C2) {
9106 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9107 if (!C1I)
9108 return false;
9109 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9110 if (!C2I)
9111 return false;
9112 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9113}
9114
9115/// FoldSelectIntoOp - Try fold the select into one of the operands to
9116/// facilitate further optimization.
9117Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9118 Value *FalseVal) {
9119 // See the comment above GetSelectFoldableOperands for a description of the
9120 // transformation we are doing here.
9121 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9122 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9123 !isa<Constant>(FalseVal)) {
9124 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9125 unsigned OpToFold = 0;
9126 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9127 OpToFold = 1;
9128 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9129 OpToFold = 2;
9130 }
9131
9132 if (OpToFold) {
9133 Constant *C = GetSelectFoldableConstant(TVI);
9134 Value *OOp = TVI->getOperand(2-OpToFold);
9135 // Avoid creating select between 2 constants unless it's selecting
9136 // between 0 and 1.
9137 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9138 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9139 InsertNewInstBefore(NewSel, SI);
9140 NewSel->takeName(TVI);
9141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9142 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9143 assert(0 && "Unknown instruction!!");
9144 }
9145 }
9146 }
9147 }
9148 }
9149
9150 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9151 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9152 !isa<Constant>(TrueVal)) {
9153 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9154 unsigned OpToFold = 0;
9155 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9156 OpToFold = 1;
9157 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9158 OpToFold = 2;
9159 }
9160
9161 if (OpToFold) {
9162 Constant *C = GetSelectFoldableConstant(FVI);
9163 Value *OOp = FVI->getOperand(2-OpToFold);
9164 // Avoid creating select between 2 constants unless it's selecting
9165 // between 0 and 1.
9166 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9167 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9168 InsertNewInstBefore(NewSel, SI);
9169 NewSel->takeName(FVI);
9170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9171 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9172 assert(0 && "Unknown instruction!!");
9173 }
9174 }
9175 }
9176 }
9177 }
9178
9179 return 0;
9180}
9181
Dan Gohman58c09632008-09-16 18:46:06 +00009182/// visitSelectInstWithICmp - Visit a SelectInst that has an
9183/// ICmpInst as its first operand.
9184///
9185Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9186 ICmpInst *ICI) {
9187 bool Changed = false;
9188 ICmpInst::Predicate Pred = ICI->getPredicate();
9189 Value *CmpLHS = ICI->getOperand(0);
9190 Value *CmpRHS = ICI->getOperand(1);
9191 Value *TrueVal = SI.getTrueValue();
9192 Value *FalseVal = SI.getFalseValue();
9193
9194 // Check cases where the comparison is with a constant that
9195 // can be adjusted to fit the min/max idiom. We may edit ICI in
9196 // place here, so make sure the select is the only user.
9197 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009198 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009199 switch (Pred) {
9200 default: break;
9201 case ICmpInst::ICMP_ULT:
9202 case ICmpInst::ICMP_SLT: {
9203 // X < MIN ? T : F --> F
9204 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9205 return ReplaceInstUsesWith(SI, FalseVal);
9206 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9207 Constant *AdjustedRHS = SubOne(CI);
9208 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9209 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9210 Pred = ICmpInst::getSwappedPredicate(Pred);
9211 CmpRHS = AdjustedRHS;
9212 std::swap(FalseVal, TrueVal);
9213 ICI->setPredicate(Pred);
9214 ICI->setOperand(1, CmpRHS);
9215 SI.setOperand(1, TrueVal);
9216 SI.setOperand(2, FalseVal);
9217 Changed = true;
9218 }
9219 break;
9220 }
9221 case ICmpInst::ICMP_UGT:
9222 case ICmpInst::ICMP_SGT: {
9223 // X > MAX ? T : F --> F
9224 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9225 return ReplaceInstUsesWith(SI, FalseVal);
9226 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9227 Constant *AdjustedRHS = AddOne(CI);
9228 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9229 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9230 Pred = ICmpInst::getSwappedPredicate(Pred);
9231 CmpRHS = AdjustedRHS;
9232 std::swap(FalseVal, TrueVal);
9233 ICI->setPredicate(Pred);
9234 ICI->setOperand(1, CmpRHS);
9235 SI.setOperand(1, TrueVal);
9236 SI.setOperand(2, FalseVal);
9237 Changed = true;
9238 }
9239 break;
9240 }
9241 }
9242
Dan Gohman35b76162008-10-30 20:40:10 +00009243 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9244 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009245 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00009246 if (match(TrueVal, m_ConstantInt<-1>()) &&
9247 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009248 Pred = ICI->getPredicate();
Chris Lattner73c1ddb2009-01-05 23:53:12 +00009249 else if (match(TrueVal, m_ConstantInt<0>()) &&
9250 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00009251 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9252
Dan Gohman35b76162008-10-30 20:40:10 +00009253 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9254 // If we are just checking for a icmp eq of a single bit and zext'ing it
9255 // to an integer, then shift the bit to the appropriate place and then
9256 // cast to integer to avoid the comparison.
9257 const APInt &Op1CV = CI->getValue();
9258
9259 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9260 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9261 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009262 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009263 Value *In = ICI->getOperand(0);
9264 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009265 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009266 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9267 In->getName()+".lobit"),
9268 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009269 if (In->getType() != SI.getType())
9270 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009271 true/*SExt*/, "tmp", ICI);
9272
9273 if (Pred == ICmpInst::ICMP_SGT)
9274 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9275 In->getName()+".not"), *ICI);
9276
9277 return ReplaceInstUsesWith(SI, In);
9278 }
9279 }
9280 }
9281
Dan Gohman58c09632008-09-16 18:46:06 +00009282 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9283 // Transform (X == Y) ? X : Y -> Y
9284 if (Pred == ICmpInst::ICMP_EQ)
9285 return ReplaceInstUsesWith(SI, FalseVal);
9286 // Transform (X != Y) ? X : Y -> X
9287 if (Pred == ICmpInst::ICMP_NE)
9288 return ReplaceInstUsesWith(SI, TrueVal);
9289 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9290
9291 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9292 // Transform (X == Y) ? Y : X -> X
9293 if (Pred == ICmpInst::ICMP_EQ)
9294 return ReplaceInstUsesWith(SI, FalseVal);
9295 // Transform (X != Y) ? Y : X -> Y
9296 if (Pred == ICmpInst::ICMP_NE)
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9299 }
9300
9301 /// NOTE: if we wanted to, this is where to detect integer ABS
9302
9303 return Changed ? &SI : 0;
9304}
9305
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009306Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9307 Value *CondVal = SI.getCondition();
9308 Value *TrueVal = SI.getTrueValue();
9309 Value *FalseVal = SI.getFalseValue();
9310
9311 // select true, X, Y -> X
9312 // select false, X, Y -> Y
9313 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9314 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9315
9316 // select C, X, X -> X
9317 if (TrueVal == FalseVal)
9318 return ReplaceInstUsesWith(SI, TrueVal);
9319
9320 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9321 return ReplaceInstUsesWith(SI, FalseVal);
9322 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9323 return ReplaceInstUsesWith(SI, TrueVal);
9324 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9325 if (isa<Constant>(TrueVal))
9326 return ReplaceInstUsesWith(SI, TrueVal);
9327 else
9328 return ReplaceInstUsesWith(SI, FalseVal);
9329 }
9330
9331 if (SI.getType() == Type::Int1Ty) {
9332 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9333 if (C->getZExtValue()) {
9334 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009335 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009336 } else {
9337 // Change: A = select B, false, C --> A = and !B, C
9338 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009339 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009340 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009341 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009342 }
9343 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9344 if (C->getZExtValue() == false) {
9345 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009346 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009347 } else {
9348 // Change: A = select B, C, true --> A = or !B, C
9349 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009350 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009351 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009352 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009353 }
9354 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009355
9356 // select a, b, a -> a&b
9357 // select a, a, b -> a|b
9358 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009359 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009360 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009361 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009362 }
9363
9364 // Selecting between two integer constants?
9365 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9366 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9367 // select C, 1, 0 -> zext C to int
9368 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009369 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009370 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9371 // select C, 0, 1 -> zext !C to int
9372 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009373 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009374 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009375 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009376 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009377
9378 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9379
9380 // (x <s 0) ? -1 : 0 -> ashr x, 31
9381 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9382 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9383 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9384 // The comparison constant and the result are not neccessarily the
9385 // same width. Make an all-ones value by inserting a AShr.
9386 Value *X = IC->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00009387 uint32_t Bits = X->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009388 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00009389 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009390 ShAmt, "ones");
9391 InsertNewInstBefore(SRA, SI);
Eli Friedman722b4792008-11-30 21:09:11 +00009392
9393 // Then cast to the appropriate width.
9394 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009395 }
9396 }
9397
9398
9399 // If one of the constants is zero (we know they can't both be) and we
9400 // have an icmp instruction with zero, and we have an 'and' with the
9401 // non-constant value, eliminate this whole mess. This corresponds to
9402 // cases like this: ((X & 27) ? 27 : 0)
9403 if (TrueValC->isZero() || FalseValC->isZero())
9404 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9405 cast<Constant>(IC->getOperand(1))->isNullValue())
9406 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9407 if (ICA->getOpcode() == Instruction::And &&
9408 isa<ConstantInt>(ICA->getOperand(1)) &&
9409 (ICA->getOperand(1) == TrueValC ||
9410 ICA->getOperand(1) == FalseValC) &&
9411 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9412 // Okay, now we know that everything is set up, we just don't
9413 // know whether we have a icmp_ne or icmp_eq and whether the
9414 // true or false val is the zero.
9415 bool ShouldNotVal = !TrueValC->isZero();
9416 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9417 Value *V = ICA;
9418 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009419 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009420 Instruction::Xor, V, ICA->getOperand(1)), SI);
9421 return ReplaceInstUsesWith(SI, V);
9422 }
9423 }
9424 }
9425
9426 // See if we are selecting two values based on a comparison of the two values.
9427 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9428 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9429 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009430 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9431 // This is not safe in general for floating point:
9432 // consider X== -0, Y== +0.
9433 // It becomes safe if either operand is a nonzero constant.
9434 ConstantFP *CFPt, *CFPf;
9435 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9436 !CFPt->getValueAPF().isZero()) ||
9437 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9438 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009439 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009440 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009441 // Transform (X != Y) ? X : Y -> X
9442 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9443 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009444 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009445
9446 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9447 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009448 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9449 // This is not safe in general for floating point:
9450 // consider X== -0, Y== +0.
9451 // It becomes safe if either operand is a nonzero constant.
9452 ConstantFP *CFPt, *CFPf;
9453 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9454 !CFPt->getValueAPF().isZero()) ||
9455 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9456 !CFPf->getValueAPF().isZero()))
9457 return ReplaceInstUsesWith(SI, FalseVal);
9458 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009459 // Transform (X != Y) ? Y : X -> Y
9460 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9461 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009462 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009463 }
Dan Gohman58c09632008-09-16 18:46:06 +00009464 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009465 }
9466
9467 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009468 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9469 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9470 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009471
9472 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9473 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9474 if (TI->hasOneUse() && FI->hasOneUse()) {
9475 Instruction *AddOp = 0, *SubOp = 0;
9476
9477 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9478 if (TI->getOpcode() == FI->getOpcode())
9479 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9480 return IV;
9481
9482 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9483 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009484 if ((TI->getOpcode() == Instruction::Sub &&
9485 FI->getOpcode() == Instruction::Add) ||
9486 (TI->getOpcode() == Instruction::FSub &&
9487 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009488 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009489 } else if ((FI->getOpcode() == Instruction::Sub &&
9490 TI->getOpcode() == Instruction::Add) ||
9491 (FI->getOpcode() == Instruction::FSub &&
9492 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009493 AddOp = TI; SubOp = FI;
9494 }
9495
9496 if (AddOp) {
9497 Value *OtherAddOp = 0;
9498 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9499 OtherAddOp = AddOp->getOperand(1);
9500 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9501 OtherAddOp = AddOp->getOperand(0);
9502 }
9503
9504 if (OtherAddOp) {
9505 // So at this point we know we have (Y -> OtherAddOp):
9506 // select C, (add X, Y), (sub X, Z)
9507 Value *NegVal; // Compute -Z
9508 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9509 NegVal = ConstantExpr::getNeg(C);
9510 } else {
9511 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00009512 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009513 }
9514
9515 Value *NewTrueOp = OtherAddOp;
9516 Value *NewFalseOp = NegVal;
9517 if (AddOp != TI)
9518 std::swap(NewTrueOp, NewFalseOp);
9519 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009520 SelectInst::Create(CondVal, NewTrueOp,
9521 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009522
9523 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009524 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009525 }
9526 }
9527 }
9528
9529 // See if we can fold the select into one of our operands.
9530 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009531 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9532 if (FoldI)
9533 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009534 }
9535
9536 if (BinaryOperator::isNot(CondVal)) {
9537 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9538 SI.setOperand(1, FalseVal);
9539 SI.setOperand(2, TrueVal);
9540 return &SI;
9541 }
9542
9543 return 0;
9544}
9545
Dan Gohman2d648bb2008-04-10 18:43:06 +00009546/// EnforceKnownAlignment - If the specified pointer points to an object that
9547/// we control, modify the object's alignment to PrefAlign. This isn't
9548/// often possible though. If alignment is important, a more reliable approach
9549/// is to simply align all global variables and allocation instructions to
9550/// their preferred alignment from the beginning.
9551///
9552static unsigned EnforceKnownAlignment(Value *V,
9553 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009554
Dan Gohman2d648bb2008-04-10 18:43:06 +00009555 User *U = dyn_cast<User>(V);
9556 if (!U) return Align;
9557
9558 switch (getOpcode(U)) {
9559 default: break;
9560 case Instruction::BitCast:
9561 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9562 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009563 // If all indexes are zero, it is just the alignment of the base pointer.
9564 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009565 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009566 if (!isa<Constant>(*i) ||
9567 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009568 AllZeroOperands = false;
9569 break;
9570 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009571
9572 if (AllZeroOperands) {
9573 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009574 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009575 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009576 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009577 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009578 }
9579
9580 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9581 // If there is a large requested alignment and we can, bump up the alignment
9582 // of the global.
9583 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009584 if (GV->getAlignment() >= PrefAlign)
9585 Align = GV->getAlignment();
9586 else {
9587 GV->setAlignment(PrefAlign);
9588 Align = PrefAlign;
9589 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009590 }
9591 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9592 // If there is a requested alignment and if this is an alloca, round up. We
9593 // don't do this for malloc, because some systems can't respect the request.
9594 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009595 if (AI->getAlignment() >= PrefAlign)
9596 Align = AI->getAlignment();
9597 else {
9598 AI->setAlignment(PrefAlign);
9599 Align = PrefAlign;
9600 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009601 }
9602 }
9603
9604 return Align;
9605}
9606
9607/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9608/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9609/// and it is more than the alignment of the ultimate object, see if we can
9610/// increase the alignment of the ultimate object, making this check succeed.
9611unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9612 unsigned PrefAlign) {
9613 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9614 sizeof(PrefAlign) * CHAR_BIT;
9615 APInt Mask = APInt::getAllOnesValue(BitWidth);
9616 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9617 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9618 unsigned TrailZ = KnownZero.countTrailingOnes();
9619 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9620
9621 if (PrefAlign > Align)
9622 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9623
9624 // We don't need to make any adjustment.
9625 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009626}
9627
Chris Lattner00ae5132008-01-13 23:50:23 +00009628Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009629 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009630 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009631 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009632 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009633
9634 if (CopyAlign < MinAlign) {
Chris Lattner3947da72009-03-08 03:59:00 +00009635 MI->setAlignment(MinAlign);
Chris Lattner00ae5132008-01-13 23:50:23 +00009636 return MI;
9637 }
9638
9639 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9640 // load/store.
9641 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9642 if (MemOpLength == 0) return 0;
9643
Chris Lattnerc669fb62008-01-14 00:28:35 +00009644 // Source and destination pointer types are always "i8*" for intrinsic. See
9645 // if the size is something we can handle with a single primitive load/store.
9646 // A single load+store correctly handles overlapping memory in the memmove
9647 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009648 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009649 if (Size == 0) return MI; // Delete this mem transfer.
9650
9651 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009652 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009653
Chris Lattnerc669fb62008-01-14 00:28:35 +00009654 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00009655 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009656
9657 // Memcpy forces the use of i8* for the source and destination. That means
9658 // that if you're using memcpy to move one double around, you'll get a cast
9659 // from double* to i8*. We'd much rather use a double load+store rather than
9660 // an i64 load+store, here because this improves the odds that the source or
9661 // dest address will be promotable. See if we can find a better type than the
9662 // integer datatype.
9663 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9664 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9665 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9666 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9667 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009668 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009669 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9670 if (STy->getNumElements() == 1)
9671 SrcETy = STy->getElementType(0);
9672 else
9673 break;
9674 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9675 if (ATy->getNumElements() == 1)
9676 SrcETy = ATy->getElementType();
9677 else
9678 break;
9679 } else
9680 break;
9681 }
9682
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009683 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00009684 NewPtrTy = PointerType::getUnqual(SrcETy);
9685 }
9686 }
9687
9688
Chris Lattner00ae5132008-01-13 23:50:23 +00009689 // If the memcpy/memmove provides better alignment info than we can
9690 // infer, use it.
9691 SrcAlign = std::max(SrcAlign, CopyAlign);
9692 DstAlign = std::max(DstAlign, CopyAlign);
9693
9694 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9695 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009696 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9697 InsertNewInstBefore(L, *MI);
9698 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9699
9700 // Set the size of the copy to 0, it will be deleted on the next iteration.
9701 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9702 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009703}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009704
Chris Lattner5af8a912008-04-30 06:39:11 +00009705Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9706 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009707 if (MI->getAlignment() < Alignment) {
9708 MI->setAlignment(Alignment);
Chris Lattner5af8a912008-04-30 06:39:11 +00009709 return MI;
9710 }
9711
9712 // Extract the length and alignment and fill if they are constant.
9713 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9714 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9715 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9716 return 0;
9717 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009718 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009719
9720 // If the length is zero, this is a no-op
9721 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9722
9723 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9724 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9725 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9726
9727 Value *Dest = MI->getDest();
9728 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9729
9730 // Alignment 0 is identity for alignment 1 for memset, but not store.
9731 if (Alignment == 0) Alignment = 1;
9732
9733 // Extract the fill value and store.
9734 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9735 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9736 Alignment), *MI);
9737
9738 // Set the size of the copy to 0, it will be deleted on the next iteration.
9739 MI->setLength(Constant::getNullValue(LenC->getType()));
9740 return MI;
9741 }
9742
9743 return 0;
9744}
9745
9746
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009747/// visitCallInst - CallInst simplification. This mostly only handles folding
9748/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9749/// the heavy lifting.
9750///
9751Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009752 // If the caller function is nounwind, mark the call as nounwind, even if the
9753 // callee isn't.
9754 if (CI.getParent()->getParent()->doesNotThrow() &&
9755 !CI.doesNotThrow()) {
9756 CI.setDoesNotThrow();
9757 return &CI;
9758 }
9759
9760
9761
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009762 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9763 if (!II) return visitCallSite(&CI);
9764
9765 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9766 // visitCallSite.
9767 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9768 bool Changed = false;
9769
9770 // memmove/cpy/set of zero bytes is a noop.
9771 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9772 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9773
9774 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9775 if (CI->getZExtValue() == 1) {
9776 // Replace the instruction with just byte operations. We would
9777 // transform other cases to loads/stores, but we don't know if
9778 // alignment is sufficient.
9779 }
9780 }
9781
9782 // If we have a memmove and the source operation is a constant global,
9783 // then the source and dest pointers can't alias, so we can change this
9784 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009785 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009786 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9787 if (GVSrc->isConstant()) {
9788 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009789 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9790 const Type *Tys[1];
9791 Tys[0] = CI.getOperand(3)->getType();
9792 CI.setOperand(0,
9793 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009794 Changed = true;
9795 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009796
9797 // memmove(x,x,size) -> noop.
9798 if (MMI->getSource() == MMI->getDest())
9799 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009800 }
9801
9802 // If we can determine a pointer alignment that is bigger than currently
9803 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009804 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009805 if (Instruction *I = SimplifyMemTransfer(MI))
9806 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009807 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9808 if (Instruction *I = SimplifyMemSet(MSI))
9809 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009810 }
9811
9812 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009813 }
9814
9815 switch (II->getIntrinsicID()) {
9816 default: break;
9817 case Intrinsic::bswap:
9818 // bswap(bswap(x)) -> x
9819 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9820 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9821 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9822 break;
9823 case Intrinsic::ppc_altivec_lvx:
9824 case Intrinsic::ppc_altivec_lvxl:
9825 case Intrinsic::x86_sse_loadu_ps:
9826 case Intrinsic::x86_sse2_loadu_pd:
9827 case Intrinsic::x86_sse2_loadu_dq:
9828 // Turn PPC lvx -> load if the pointer is known aligned.
9829 // Turn X86 loadups -> load if the pointer is known aligned.
9830 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9831 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9832 PointerType::getUnqual(II->getType()),
9833 CI);
9834 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009835 }
Chris Lattner989ba312008-06-18 04:33:20 +00009836 break;
9837 case Intrinsic::ppc_altivec_stvx:
9838 case Intrinsic::ppc_altivec_stvxl:
9839 // Turn stvx -> store if the pointer is known aligned.
9840 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9841 const Type *OpPtrTy =
9842 PointerType::getUnqual(II->getOperand(1)->getType());
9843 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9844 return new StoreInst(II->getOperand(1), Ptr);
9845 }
9846 break;
9847 case Intrinsic::x86_sse_storeu_ps:
9848 case Intrinsic::x86_sse2_storeu_pd:
9849 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009850 // Turn X86 storeu -> store if the pointer is known aligned.
9851 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9852 const Type *OpPtrTy =
9853 PointerType::getUnqual(II->getOperand(2)->getType());
9854 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9855 return new StoreInst(II->getOperand(2), Ptr);
9856 }
9857 break;
9858
9859 case Intrinsic::x86_sse_cvttss2si: {
9860 // These intrinsics only demands the 0th element of its input vector. If
9861 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009862 unsigned VWidth =
9863 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9864 APInt DemandedElts(VWidth, 1);
9865 APInt UndefElts(VWidth, 0);
9866 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009867 UndefElts)) {
9868 II->setOperand(1, V);
9869 return II;
9870 }
9871 break;
9872 }
9873
9874 case Intrinsic::ppc_altivec_vperm:
9875 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9876 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9877 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009878
Chris Lattner989ba312008-06-18 04:33:20 +00009879 // Check that all of the elements are integer constants or undefs.
9880 bool AllEltsOk = true;
9881 for (unsigned i = 0; i != 16; ++i) {
9882 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9883 !isa<UndefValue>(Mask->getOperand(i))) {
9884 AllEltsOk = false;
9885 break;
9886 }
9887 }
9888
9889 if (AllEltsOk) {
9890 // Cast the input vectors to byte vectors.
9891 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9892 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9893 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009894
Chris Lattner989ba312008-06-18 04:33:20 +00009895 // Only extract each element once.
9896 Value *ExtractedElts[32];
9897 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9898
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009899 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009900 if (isa<UndefValue>(Mask->getOperand(i)))
9901 continue;
9902 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9903 Idx &= 31; // Match the hardware behavior.
9904
9905 if (ExtractedElts[Idx] == 0) {
9906 Instruction *Elt =
9907 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9908 InsertNewInstBefore(Elt, CI);
9909 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009910 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009911
Chris Lattner989ba312008-06-18 04:33:20 +00009912 // Insert this value into the result vector.
9913 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9914 i, "tmp");
9915 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009916 }
Chris Lattner989ba312008-06-18 04:33:20 +00009917 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009918 }
Chris Lattner989ba312008-06-18 04:33:20 +00009919 }
9920 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009921
Chris Lattner989ba312008-06-18 04:33:20 +00009922 case Intrinsic::stackrestore: {
9923 // If the save is right next to the restore, remove the restore. This can
9924 // happen when variable allocas are DCE'd.
9925 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9926 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9927 BasicBlock::iterator BI = SS;
9928 if (&*++BI == II)
9929 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009930 }
Chris Lattner989ba312008-06-18 04:33:20 +00009931 }
9932
9933 // Scan down this block to see if there is another stack restore in the
9934 // same block without an intervening call/alloca.
9935 BasicBlock::iterator BI = II;
9936 TerminatorInst *TI = II->getParent()->getTerminator();
9937 bool CannotRemove = false;
9938 for (++BI; &*BI != TI; ++BI) {
9939 if (isa<AllocaInst>(BI)) {
9940 CannotRemove = true;
9941 break;
9942 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009943 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9944 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9945 // If there is a stackrestore below this one, remove this one.
9946 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9947 return EraseInstFromFunction(CI);
9948 // Otherwise, ignore the intrinsic.
9949 } else {
9950 // If we found a non-intrinsic call, we can't remove the stack
9951 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009952 CannotRemove = true;
9953 break;
9954 }
Chris Lattner989ba312008-06-18 04:33:20 +00009955 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009956 }
Chris Lattner989ba312008-06-18 04:33:20 +00009957
9958 // If the stack restore is in a return/unwind block and if there are no
9959 // allocas or calls between the restore and the return, nuke the restore.
9960 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9961 return EraseInstFromFunction(CI);
9962 break;
9963 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009964 }
9965
9966 return visitCallSite(II);
9967}
9968
9969// InvokeInst simplification
9970//
9971Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9972 return visitCallSite(&II);
9973}
9974
Dale Johannesen96021832008-04-25 21:16:07 +00009975/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9976/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009977static bool isSafeToEliminateVarargsCast(const CallSite CS,
9978 const CastInst * const CI,
9979 const TargetData * const TD,
9980 const int ix) {
9981 if (!CI->isLosslessCast())
9982 return false;
9983
9984 // The size of ByVal arguments is derived from the type, so we
9985 // can't change to a type with a different size. If the size were
9986 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009987 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009988 return true;
9989
9990 const Type* SrcTy =
9991 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9992 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9993 if (!SrcTy->isSized() || !DstTy->isSized())
9994 return false;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00009995 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009996 return false;
9997 return true;
9998}
9999
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010000// visitCallSite - Improvements for call and invoke instructions.
10001//
10002Instruction *InstCombiner::visitCallSite(CallSite CS) {
10003 bool Changed = false;
10004
10005 // If the callee is a constexpr cast of a function, attempt to move the cast
10006 // to the arguments of the call/invoke.
10007 if (transformConstExprCastCall(CS)) return 0;
10008
10009 Value *Callee = CS.getCalledValue();
10010
10011 if (Function *CalleeF = dyn_cast<Function>(Callee))
10012 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10013 Instruction *OldCall = CS.getInstruction();
10014 // If the call and callee calling conventions don't match, this call must
10015 // be unreachable, as the call is undefined.
10016 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010017 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10018 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010019 if (!OldCall->use_empty())
10020 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10021 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10022 return EraseInstFromFunction(*OldCall);
10023 return 0;
10024 }
10025
10026 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10027 // This instruction is not reachable, just remove it. We insert a store to
10028 // undef so that we know that this code is not reachable, despite the fact
10029 // that we can't modify the CFG here.
10030 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010031 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010032 CS.getInstruction());
10033
10034 if (!CS.getInstruction()->use_empty())
10035 CS.getInstruction()->
10036 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10037
10038 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10039 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010040 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10041 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010042 }
10043 return EraseInstFromFunction(*CS.getInstruction());
10044 }
10045
Duncan Sands74833f22007-09-17 10:26:40 +000010046 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10047 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10048 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10049 return transformCallThroughTrampoline(CS);
10050
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010051 const PointerType *PTy = cast<PointerType>(Callee->getType());
10052 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10053 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010054 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010055 // See if we can optimize any arguments passed through the varargs area of
10056 // the call.
10057 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010058 E = CS.arg_end(); I != E; ++I, ++ix) {
10059 CastInst *CI = dyn_cast<CastInst>(*I);
10060 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10061 *I = CI->getOperand(0);
10062 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010063 }
Dale Johannesen35615462008-04-23 18:34:37 +000010064 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010065 }
10066
Duncan Sands2937e352007-12-19 21:13:37 +000010067 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010068 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010069 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010070 Changed = true;
10071 }
10072
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010073 return Changed ? CS.getInstruction() : 0;
10074}
10075
10076// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10077// attempt to move the cast to the arguments of the call/invoke.
10078//
10079bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10080 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10081 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10082 if (CE->getOpcode() != Instruction::BitCast ||
10083 !isa<Function>(CE->getOperand(0)))
10084 return false;
10085 Function *Callee = cast<Function>(CE->getOperand(0));
10086 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010087 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010088
10089 // Okay, this is a cast from a function to a different type. Unless doing so
10090 // would cause a type conversion of one of our arguments, change this call to
10091 // be a direct call with arguments casted to the appropriate types.
10092 //
10093 const FunctionType *FT = Callee->getFunctionType();
10094 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010095 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010096
Duncan Sands7901ce12008-06-01 07:38:42 +000010097 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010098 return false; // TODO: Handle multiple return values.
10099
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010100 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010101 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010102 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010103 // Conversion is ok if changing from one pointer type to another or from
10104 // a pointer to an integer of the same size.
10105 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +000010106 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010107 return false; // Cannot transform this return value.
10108
Duncan Sands5c489582008-01-06 10:12:28 +000010109 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010110 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +000010111 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010112 return false; // Cannot transform this return value.
10113
Chris Lattner1c8733e2008-03-12 17:45:29 +000010114 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010115 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010116 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010117 return false; // Attribute not compatible with transformed value.
10118 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010119
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010120 // If the callsite is an invoke instruction, and the return value is used by
10121 // a PHI node in a successor, we cannot change the return type of the call
10122 // because there is no place to put the cast instruction (without breaking
10123 // the critical edge). Bail out in this case.
10124 if (!Caller->use_empty())
10125 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10126 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10127 UI != E; ++UI)
10128 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10129 if (PN->getParent() == II->getNormalDest() ||
10130 PN->getParent() == II->getUnwindDest())
10131 return false;
10132 }
10133
10134 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10135 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10136
10137 CallSite::arg_iterator AI = CS.arg_begin();
10138 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10139 const Type *ParamTy = FT->getParamType(i);
10140 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010141
10142 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010143 return false; // Cannot transform this parameter value.
10144
Devang Patelf2a4a922008-09-26 22:53:05 +000010145 if (CallerPAL.getParamAttributes(i + 1)
10146 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010147 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010148
Duncan Sands7901ce12008-06-01 07:38:42 +000010149 // Converting from one pointer type to another or between a pointer and an
10150 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010151 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +000010152 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10153 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010154 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010155 }
10156
10157 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10158 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010159 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010160
Chris Lattner1c8733e2008-03-12 17:45:29 +000010161 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10162 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010163 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010164 // won't be dropping them. Check that these extra arguments have attributes
10165 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010166 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10167 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010168 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010169 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010170 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010171 return false;
10172 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010173
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010174 // Okay, we decided that this is a safe thing to do: go ahead and start
10175 // inserting cast instructions as necessary...
10176 std::vector<Value*> Args;
10177 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010178 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010179 attrVec.reserve(NumCommonArgs);
10180
10181 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010182 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010183
10184 // If the return value is not being used, the type may not be compatible
10185 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010186 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010187
10188 // Add the new return attributes.
10189 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010190 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010191
10192 AI = CS.arg_begin();
10193 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10194 const Type *ParamTy = FT->getParamType(i);
10195 if ((*AI)->getType() == ParamTy) {
10196 Args.push_back(*AI);
10197 } else {
10198 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10199 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010200 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010201 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10202 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010203
10204 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010205 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010206 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010207 }
10208
10209 // If the function takes more arguments than the call was taking, add them
10210 // now...
10211 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10212 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10213
10214 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010215 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010216 if (!FT->isVarArg()) {
10217 cerr << "WARNING: While resolving call to function '"
10218 << Callee->getName() << "' arguments were dropped!\n";
10219 } else {
10220 // Add all of the arguments in their promoted form to the arg list...
10221 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10222 const Type *PTy = getPromotedType((*AI)->getType());
10223 if (PTy != (*AI)->getType()) {
10224 // Must promote to pass through va_arg area!
10225 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10226 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010227 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010228 InsertNewInstBefore(Cast, *Caller);
10229 Args.push_back(Cast);
10230 } else {
10231 Args.push_back(*AI);
10232 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010233
Duncan Sands4ced1f82008-01-13 08:02:44 +000010234 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010235 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010236 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010237 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010238 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010239 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010240
Devang Patelf2a4a922008-09-26 22:53:05 +000010241 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10242 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10243
Duncan Sands7901ce12008-06-01 07:38:42 +000010244 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010245 Caller->setName(""); // Void type should not have a name.
10246
Devang Pateld222f862008-09-25 21:00:45 +000010247 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010248
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010249 Instruction *NC;
10250 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010251 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010252 Args.begin(), Args.end(),
10253 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010254 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010255 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010256 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010257 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10258 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010259 CallInst *CI = cast<CallInst>(Caller);
10260 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010261 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010262 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010263 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010264 }
10265
10266 // Insert a cast of the return type as necessary.
10267 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010268 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010269 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010270 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010271 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010272 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010273
10274 // If this is an invoke instruction, we should insert it after the first
10275 // non-phi, instruction in the normal successor block.
10276 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010277 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010278 InsertNewInstBefore(NC, *I);
10279 } else {
10280 // Otherwise, it's a call, just insert cast right after the call instr
10281 InsertNewInstBefore(NC, *Caller);
10282 }
10283 AddUsersToWorkList(*Caller);
10284 } else {
10285 NV = UndefValue::get(Caller->getType());
10286 }
10287 }
10288
10289 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10290 Caller->replaceAllUsesWith(NV);
10291 Caller->eraseFromParent();
10292 RemoveFromWorkList(Caller);
10293 return true;
10294}
10295
Duncan Sands74833f22007-09-17 10:26:40 +000010296// transformCallThroughTrampoline - Turn a call to a function created by the
10297// init_trampoline intrinsic into a direct call to the underlying function.
10298//
10299Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10300 Value *Callee = CS.getCalledValue();
10301 const PointerType *PTy = cast<PointerType>(Callee->getType());
10302 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010303 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010304
10305 // If the call already has the 'nest' attribute somewhere then give up -
10306 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010307 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010308 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010309
10310 IntrinsicInst *Tramp =
10311 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10312
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010313 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010314 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10315 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10316
Devang Pateld222f862008-09-25 21:00:45 +000010317 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010318 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010319 unsigned NestIdx = 1;
10320 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010321 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010322
10323 // Look for a parameter marked with the 'nest' attribute.
10324 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10325 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010326 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010327 // Record the parameter type and any other attributes.
10328 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010329 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010330 break;
10331 }
10332
10333 if (NestTy) {
10334 Instruction *Caller = CS.getInstruction();
10335 std::vector<Value*> NewArgs;
10336 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10337
Devang Pateld222f862008-09-25 21:00:45 +000010338 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010339 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010340
Duncan Sands74833f22007-09-17 10:26:40 +000010341 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010342 // mean appending it. Likewise for attributes.
10343
Devang Patelf2a4a922008-09-26 22:53:05 +000010344 // Add any result attributes.
10345 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010346 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010347
Duncan Sands74833f22007-09-17 10:26:40 +000010348 {
10349 unsigned Idx = 1;
10350 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10351 do {
10352 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010353 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010354 Value *NestVal = Tramp->getOperand(3);
10355 if (NestVal->getType() != NestTy)
10356 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10357 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010358 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010359 }
10360
10361 if (I == E)
10362 break;
10363
Duncan Sands48b81112008-01-14 19:52:09 +000010364 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010365 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010366 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010367 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010368 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010369
10370 ++Idx, ++I;
10371 } while (1);
10372 }
10373
Devang Patelf2a4a922008-09-26 22:53:05 +000010374 // Add any function attributes.
10375 if (Attributes Attr = Attrs.getFnAttributes())
10376 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10377
Duncan Sands74833f22007-09-17 10:26:40 +000010378 // The trampoline may have been bitcast to a bogus type (FTy).
10379 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010380 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010381
Duncan Sands74833f22007-09-17 10:26:40 +000010382 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010383 NewTypes.reserve(FTy->getNumParams()+1);
10384
Duncan Sands74833f22007-09-17 10:26:40 +000010385 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010386 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010387 {
10388 unsigned Idx = 1;
10389 FunctionType::param_iterator I = FTy->param_begin(),
10390 E = FTy->param_end();
10391
10392 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010393 if (Idx == NestIdx)
10394 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010395 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010396
10397 if (I == E)
10398 break;
10399
Duncan Sands48b81112008-01-14 19:52:09 +000010400 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010401 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010402
10403 ++Idx, ++I;
10404 } while (1);
10405 }
10406
10407 // Replace the trampoline call with a direct call. Let the generic
10408 // code sort out any function type mismatches.
10409 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010410 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +000010411 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10412 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +000010413 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010414
10415 Instruction *NewCaller;
10416 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010417 NewCaller = InvokeInst::Create(NewCallee,
10418 II->getNormalDest(), II->getUnwindDest(),
10419 NewArgs.begin(), NewArgs.end(),
10420 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010421 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010422 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010423 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010424 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10425 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010426 if (cast<CallInst>(Caller)->isTailCall())
10427 cast<CallInst>(NewCaller)->setTailCall();
10428 cast<CallInst>(NewCaller)->
10429 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010430 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010431 }
10432 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10433 Caller->replaceAllUsesWith(NewCaller);
10434 Caller->eraseFromParent();
10435 RemoveFromWorkList(Caller);
10436 return 0;
10437 }
10438 }
10439
10440 // Replace the trampoline call with a direct call. Since there is no 'nest'
10441 // parameter, there is no need to adjust the argument list. Let the generic
10442 // code sort out any function type mismatches.
10443 Constant *NewCallee =
10444 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10445 CS.setCalledFunction(NewCallee);
10446 return CS.getInstruction();
10447}
10448
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010449/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10450/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10451/// and a single binop.
10452Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10453 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010454 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010455 unsigned Opc = FirstInst->getOpcode();
10456 Value *LHSVal = FirstInst->getOperand(0);
10457 Value *RHSVal = FirstInst->getOperand(1);
10458
10459 const Type *LHSType = LHSVal->getType();
10460 const Type *RHSType = RHSVal->getType();
10461
10462 // Scan to see if all operands are the same opcode, all have one use, and all
10463 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010464 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010465 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10466 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10467 // Verify type of the LHS matches so we don't fold cmp's of different
10468 // types or GEP's with different index types.
10469 I->getOperand(0)->getType() != LHSType ||
10470 I->getOperand(1)->getType() != RHSType)
10471 return 0;
10472
10473 // If they are CmpInst instructions, check their predicates
10474 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10475 if (cast<CmpInst>(I)->getPredicate() !=
10476 cast<CmpInst>(FirstInst)->getPredicate())
10477 return 0;
10478
10479 // Keep track of which operand needs a phi node.
10480 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10481 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10482 }
10483
Chris Lattner30078012008-12-01 03:42:51 +000010484 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010485
10486 Value *InLHS = FirstInst->getOperand(0);
10487 Value *InRHS = FirstInst->getOperand(1);
10488 PHINode *NewLHS = 0, *NewRHS = 0;
10489 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010490 NewLHS = PHINode::Create(LHSType,
10491 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010492 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10493 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10494 InsertNewInstBefore(NewLHS, PN);
10495 LHSVal = NewLHS;
10496 }
10497
10498 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010499 NewRHS = PHINode::Create(RHSType,
10500 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010501 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10502 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10503 InsertNewInstBefore(NewRHS, PN);
10504 RHSVal = NewRHS;
10505 }
10506
10507 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010508 if (NewLHS || NewRHS) {
10509 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10510 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10511 if (NewLHS) {
10512 Value *NewInLHS = InInst->getOperand(0);
10513 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10514 }
10515 if (NewRHS) {
10516 Value *NewInRHS = InInst->getOperand(1);
10517 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10518 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010519 }
10520 }
10521
10522 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010523 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010524 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10525 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10526 RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010527}
10528
Chris Lattner9e1916e2008-12-01 02:34:36 +000010529Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10530 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10531
10532 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10533 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010534 // This is true if all GEP bases are allocas and if all indices into them are
10535 // constants.
10536 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010537
10538 // Scan to see if all operands are the same opcode, all have one use, and all
10539 // kill their operands (i.e. the operands have one use).
10540 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10541 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10542 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10543 GEP->getNumOperands() != FirstInst->getNumOperands())
10544 return 0;
10545
Chris Lattneradf354b2009-02-21 00:46:50 +000010546 // Keep track of whether or not all GEPs are of alloca pointers.
10547 if (AllBasePointersAreAllocas &&
10548 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10549 !GEP->hasAllConstantIndices()))
10550 AllBasePointersAreAllocas = false;
10551
Chris Lattner9e1916e2008-12-01 02:34:36 +000010552 // Compare the operand lists.
10553 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10554 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10555 continue;
10556
10557 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10558 // if one of the PHIs has a constant for the index. The index may be
10559 // substantially cheaper to compute for the constants, so making it a
10560 // variable index could pessimize the path. This also handles the case
10561 // for struct indices, which must always be constant.
10562 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10563 isa<ConstantInt>(GEP->getOperand(op)))
10564 return 0;
10565
10566 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10567 return 0;
10568 FixedOperands[op] = 0; // Needs a PHI.
10569 }
10570 }
10571
Chris Lattneradf354b2009-02-21 00:46:50 +000010572 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010573 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010574 // offset calculation, but all the predecessors will have to materialize the
10575 // stack address into a register anyway. We'd actually rather *clone* the
10576 // load up into the predecessors so that we have a load of a gep of an alloca,
10577 // which can usually all be folded into the load.
10578 if (AllBasePointersAreAllocas)
10579 return 0;
10580
Chris Lattner9e1916e2008-12-01 02:34:36 +000010581 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10582 // that is variable.
10583 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10584
10585 bool HasAnyPHIs = false;
10586 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10587 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10588 Value *FirstOp = FirstInst->getOperand(i);
10589 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10590 FirstOp->getName()+".pn");
10591 InsertNewInstBefore(NewPN, PN);
10592
10593 NewPN->reserveOperandSpace(e);
10594 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10595 OperandPhis[i] = NewPN;
10596 FixedOperands[i] = NewPN;
10597 HasAnyPHIs = true;
10598 }
10599
10600
10601 // Add all operands to the new PHIs.
10602 if (HasAnyPHIs) {
10603 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10604 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10605 BasicBlock *InBB = PN.getIncomingBlock(i);
10606
10607 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10608 if (PHINode *OpPhi = OperandPhis[op])
10609 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10610 }
10611 }
10612
10613 Value *Base = FixedOperands[0];
10614 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10615 FixedOperands.end());
10616}
10617
10618
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010619/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10620/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010621/// obvious the value of the load is not changed from the point of the load to
10622/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010623///
10624/// Finally, it is safe, but not profitable, to sink a load targetting a
10625/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10626/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010627static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010628 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10629
10630 for (++BBI; BBI != E; ++BBI)
10631 if (BBI->mayWriteToMemory())
10632 return false;
10633
10634 // Check for non-address taken alloca. If not address-taken already, it isn't
10635 // profitable to do this xform.
10636 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10637 bool isAddressTaken = false;
10638 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10639 UI != E; ++UI) {
10640 if (isa<LoadInst>(UI)) continue;
10641 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10642 // If storing TO the alloca, then the address isn't taken.
10643 if (SI->getOperand(1) == AI) continue;
10644 }
10645 isAddressTaken = true;
10646 break;
10647 }
10648
Chris Lattneradf354b2009-02-21 00:46:50 +000010649 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010650 return false;
10651 }
10652
Chris Lattneradf354b2009-02-21 00:46:50 +000010653 // If this load is a load from a GEP with a constant offset from an alloca,
10654 // then we don't want to sink it. In its present form, it will be
10655 // load [constant stack offset]. Sinking it will cause us to have to
10656 // materialize the stack addresses in each predecessor in a register only to
10657 // do a shared load from register in the successor.
10658 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10659 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10660 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10661 return false;
10662
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010663 return true;
10664}
10665
10666
10667// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10668// operator and they all are only used by the PHI, PHI together their
10669// inputs, and do the operation once, to the result of the PHI.
10670Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10671 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10672
10673 // Scan the instruction, looking for input operations that can be folded away.
10674 // If all input operands to the phi are the same instruction (e.g. a cast from
10675 // the same type or "+42") we can pull the operation through the PHI, reducing
10676 // code size and simplifying code.
10677 Constant *ConstantOp = 0;
10678 const Type *CastSrcTy = 0;
10679 bool isVolatile = false;
10680 if (isa<CastInst>(FirstInst)) {
10681 CastSrcTy = FirstInst->getOperand(0)->getType();
10682 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10683 // Can fold binop, compare or shift here if the RHS is a constant,
10684 // otherwise call FoldPHIArgBinOpIntoPHI.
10685 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10686 if (ConstantOp == 0)
10687 return FoldPHIArgBinOpIntoPHI(PN);
10688 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10689 isVolatile = LI->isVolatile();
10690 // We can't sink the load if the loaded value could be modified between the
10691 // load and the PHI.
10692 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010693 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010694 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010695
10696 // If the PHI is of volatile loads and the load block has multiple
10697 // successors, sinking it would remove a load of the volatile value from
10698 // the path through the other successor.
10699 if (isVolatile &&
10700 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10701 return 0;
10702
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010703 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010704 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010705 } else {
10706 return 0; // Cannot fold this operation.
10707 }
10708
10709 // Check to see if all arguments are the same operation.
10710 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10711 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10712 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10713 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10714 return 0;
10715 if (CastSrcTy) {
10716 if (I->getOperand(0)->getType() != CastSrcTy)
10717 return 0; // Cast operation must match.
10718 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10719 // We can't sink the load if the loaded value could be modified between
10720 // the load and the PHI.
10721 if (LI->isVolatile() != isVolatile ||
10722 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010723 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010724 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010725
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010726 // If the PHI is of volatile loads and the load block has multiple
10727 // successors, sinking it would remove a load of the volatile value from
10728 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010729 if (isVolatile &&
10730 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10731 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010732
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010733 } else if (I->getOperand(1) != ConstantOp) {
10734 return 0;
10735 }
10736 }
10737
10738 // Okay, they are all the same operation. Create a new PHI node of the
10739 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010740 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10741 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010742 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10743
10744 Value *InVal = FirstInst->getOperand(0);
10745 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10746
10747 // Add all operands to the new PHI.
10748 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10749 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10750 if (NewInVal != InVal)
10751 InVal = 0;
10752 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10753 }
10754
10755 Value *PhiVal;
10756 if (InVal) {
10757 // The new PHI unions all of the same values together. This is really
10758 // common, so we handle it intelligently here for compile-time speed.
10759 PhiVal = InVal;
10760 delete NewPN;
10761 } else {
10762 InsertNewInstBefore(NewPN, PN);
10763 PhiVal = NewPN;
10764 }
10765
10766 // Insert and return the new operation.
10767 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010768 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010769 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010770 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010771 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010772 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010773 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010774 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10775
10776 // If this was a volatile load that we are merging, make sure to loop through
10777 // and mark all the input loads as non-volatile. If we don't do this, we will
10778 // insert a new volatile load and the old ones will not be deletable.
10779 if (isVolatile)
10780 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10781 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10782
10783 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010784}
10785
10786/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10787/// that is dead.
10788static bool DeadPHICycle(PHINode *PN,
10789 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10790 if (PN->use_empty()) return true;
10791 if (!PN->hasOneUse()) return false;
10792
10793 // Remember this node, and if we find the cycle, return.
10794 if (!PotentiallyDeadPHIs.insert(PN))
10795 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010796
10797 // Don't scan crazily complex things.
10798 if (PotentiallyDeadPHIs.size() == 16)
10799 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010800
10801 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10802 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10803
10804 return false;
10805}
10806
Chris Lattner27b695d2007-11-06 21:52:06 +000010807/// PHIsEqualValue - Return true if this phi node is always equal to
10808/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10809/// z = some value; x = phi (y, z); y = phi (x, z)
10810static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10811 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10812 // See if we already saw this PHI node.
10813 if (!ValueEqualPHIs.insert(PN))
10814 return true;
10815
10816 // Don't scan crazily complex things.
10817 if (ValueEqualPHIs.size() == 16)
10818 return false;
10819
10820 // Scan the operands to see if they are either phi nodes or are equal to
10821 // the value.
10822 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10823 Value *Op = PN->getIncomingValue(i);
10824 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10825 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10826 return false;
10827 } else if (Op != NonPhiInVal)
10828 return false;
10829 }
10830
10831 return true;
10832}
10833
10834
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010835// PHINode simplification
10836//
10837Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10838 // If LCSSA is around, don't mess with Phi nodes
10839 if (MustPreserveLCSSA) return 0;
10840
10841 if (Value *V = PN.hasConstantValue())
10842 return ReplaceInstUsesWith(PN, V);
10843
10844 // If all PHI operands are the same operation, pull them through the PHI,
10845 // reducing code size.
10846 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010847 isa<Instruction>(PN.getIncomingValue(1)) &&
10848 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10849 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10850 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10851 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010852 PN.getIncomingValue(0)->hasOneUse())
10853 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10854 return Result;
10855
10856 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10857 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10858 // PHI)... break the cycle.
10859 if (PN.hasOneUse()) {
10860 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10861 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10862 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10863 PotentiallyDeadPHIs.insert(&PN);
10864 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10865 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10866 }
10867
10868 // If this phi has a single use, and if that use just computes a value for
10869 // the next iteration of a loop, delete the phi. This occurs with unused
10870 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10871 // common case here is good because the only other things that catch this
10872 // are induction variable analysis (sometimes) and ADCE, which is only run
10873 // late.
10874 if (PHIUser->hasOneUse() &&
10875 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10876 PHIUser->use_back() == &PN) {
10877 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10878 }
10879 }
10880
Chris Lattner27b695d2007-11-06 21:52:06 +000010881 // We sometimes end up with phi cycles that non-obviously end up being the
10882 // same value, for example:
10883 // z = some value; x = phi (y, z); y = phi (x, z)
10884 // where the phi nodes don't necessarily need to be in the same block. Do a
10885 // quick check to see if the PHI node only contains a single non-phi value, if
10886 // so, scan to see if the phi cycle is actually equal to that value.
10887 {
10888 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10889 // Scan for the first non-phi operand.
10890 while (InValNo != NumOperandVals &&
10891 isa<PHINode>(PN.getIncomingValue(InValNo)))
10892 ++InValNo;
10893
10894 if (InValNo != NumOperandVals) {
10895 Value *NonPhiInVal = PN.getOperand(InValNo);
10896
10897 // Scan the rest of the operands to see if there are any conflicts, if so
10898 // there is no need to recursively scan other phis.
10899 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10900 Value *OpVal = PN.getIncomingValue(InValNo);
10901 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10902 break;
10903 }
10904
10905 // If we scanned over all operands, then we have one unique value plus
10906 // phi values. Scan PHI nodes to see if they all merge in each other or
10907 // the value.
10908 if (InValNo == NumOperandVals) {
10909 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10910 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10911 return ReplaceInstUsesWith(PN, NonPhiInVal);
10912 }
10913 }
10914 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010915 return 0;
10916}
10917
10918static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10919 Instruction *InsertPoint,
10920 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000010921 unsigned PtrSize = DTy->getScalarSizeInBits();
10922 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010923 // We must cast correctly to the pointer type. Ensure that we
10924 // sign extend the integer value if it is smaller as this is
10925 // used for address computation.
10926 Instruction::CastOps opcode =
10927 (VTySize < PtrSize ? Instruction::SExt :
10928 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10929 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10930}
10931
10932
10933Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10934 Value *PtrOp = GEP.getOperand(0);
10935 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10936 // If so, eliminate the noop.
10937 if (GEP.getNumOperands() == 1)
10938 return ReplaceInstUsesWith(GEP, PtrOp);
10939
10940 if (isa<UndefValue>(GEP.getOperand(0)))
10941 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10942
10943 bool HasZeroPointerIndex = false;
10944 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10945 HasZeroPointerIndex = C->isNullValue();
10946
10947 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10948 return ReplaceInstUsesWith(GEP, PtrOp);
10949
10950 // Eliminate unneeded casts for indices.
10951 bool MadeChange = false;
10952
10953 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010954 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10955 i != e; ++i, ++GTI) {
Sanjiv Gupta7f712d82009-04-24 02:37:54 +000010956 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000010957 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010958 if (CI->getOpcode() == Instruction::ZExt ||
10959 CI->getOpcode() == Instruction::SExt) {
10960 const Type *SrcTy = CI->getOperand(0)->getType();
10961 // We can eliminate a cast from i32 to i64 iff the target
10962 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000010963 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010964 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000010965 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010966 }
10967 }
10968 }
10969 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000010970 // to what we need. If narrower, sign-extend it to what we need.
10971 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010972 // insert it. This explicit cast can make subsequent optimizations more
10973 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000010974 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010975 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010976 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +000010977 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010978 MadeChange = true;
10979 } else {
10980 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10981 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010982 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010983 MadeChange = true;
10984 }
Dan Gohman5d639ed2008-09-11 23:06:38 +000010985 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10986 if (Constant *C = dyn_cast<Constant>(Op)) {
10987 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10988 MadeChange = true;
10989 } else {
10990 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10991 GEP);
10992 *i = Op;
10993 MadeChange = true;
10994 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010995 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010996 }
10997 }
10998 if (MadeChange) return &GEP;
10999
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011000 // Combine Indices - If the source pointer to this getelementptr instruction
11001 // is a getelementptr instruction, combine the indices of the two
11002 // getelementptr instructions into a single instruction.
11003 //
11004 SmallVector<Value*, 8> SrcGEPOperands;
11005 if (User *Src = dyn_castGetElementPtr(PtrOp))
11006 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11007
11008 if (!SrcGEPOperands.empty()) {
11009 // Note that if our source is a gep chain itself that we wait for that
11010 // chain to be resolved before we perform this transformation. This
11011 // avoids us creating a TON of code in some cases.
11012 //
11013 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11014 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11015 return 0; // Wait until our source is folded to completion.
11016
11017 SmallVector<Value*, 8> Indices;
11018
11019 // Find out whether the last index in the source GEP is a sequential idx.
11020 bool EndsWithSequential = false;
11021 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11022 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11023 EndsWithSequential = !isa<StructType>(*I);
11024
11025 // Can we combine the two pointer arithmetics offsets?
11026 if (EndsWithSequential) {
11027 // Replace: gep (gep %P, long B), long A, ...
11028 // With: T = long A+B; gep %P, T, ...
11029 //
11030 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11031 if (SO1 == Constant::getNullValue(SO1->getType())) {
11032 Sum = GO1;
11033 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11034 Sum = SO1;
11035 } else {
11036 // If they aren't the same type, convert both to an integer of the
11037 // target's pointer size.
11038 if (SO1->getType() != GO1->getType()) {
11039 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11040 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11041 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11042 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11043 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011044 unsigned PS = TD->getPointerSizeInBits();
11045 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011046 // Convert GO1 to SO1's type.
11047 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11048
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011049 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011050 // Convert SO1 to GO1's type.
11051 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11052 } else {
11053 const Type *PT = TD->getIntPtrType();
11054 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11055 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11056 }
11057 }
11058 }
11059 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11060 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11061 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011062 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011063 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11064 }
11065 }
11066
11067 // Recycle the GEP we already have if possible.
11068 if (SrcGEPOperands.size() == 2) {
11069 GEP.setOperand(0, SrcGEPOperands[0]);
11070 GEP.setOperand(1, Sum);
11071 return &GEP;
11072 } else {
11073 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11074 SrcGEPOperands.end()-1);
11075 Indices.push_back(Sum);
11076 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11077 }
11078 } else if (isa<Constant>(*GEP.idx_begin()) &&
11079 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11080 SrcGEPOperands.size() != 1) {
11081 // Otherwise we can do the fold if the first index of the GEP is a zero
11082 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11083 SrcGEPOperands.end());
11084 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11085 }
11086
11087 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000011088 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11089 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011090
11091 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11092 // GEP of global variable. If all of the indices for this GEP are
11093 // constants, we can promote this to a constexpr instead of an instruction.
11094
11095 // Scan for nonconstants...
11096 SmallVector<Constant*, 8> Indices;
11097 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11098 for (; I != E && isa<Constant>(*I); ++I)
11099 Indices.push_back(cast<Constant>(*I));
11100
11101 if (I == E) { // If they are all constants...
11102 Constant *CE = ConstantExpr::getGetElementPtr(GV,
11103 &Indices[0],Indices.size());
11104
11105 // Replace all uses of the GEP with the new constexpr...
11106 return ReplaceInstUsesWith(GEP, CE);
11107 }
11108 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11109 if (!isa<PointerType>(X->getType())) {
11110 // Not interesting. Source pointer must be a cast from pointer.
11111 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011112 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11113 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011114 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011115 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11116 // into : GEP i8* X, ...
11117 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011118 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011119 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11120 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011121 if (const ArrayType *CATy =
11122 dyn_cast<ArrayType>(CPTy->getElementType())) {
11123 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11124 if (CATy->getElementType() == XTy->getElementType()) {
11125 // -> GEP i8* X, ...
11126 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11127 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11128 GEP.getName());
11129 } else if (const ArrayType *XATy =
11130 dyn_cast<ArrayType>(XTy->getElementType())) {
11131 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011132 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011133 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011134 // At this point, we know that the cast source type is a pointer
11135 // to an array of the same type as the destination pointer
11136 // array. Because the array type is never stepped over (there
11137 // is a leading zero) we can fold the cast into this GEP.
11138 GEP.setOperand(0, X);
11139 return &GEP;
11140 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011141 }
11142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011143 } else if (GEP.getNumOperands() == 2) {
11144 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011145 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11146 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011147 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11148 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11149 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011150 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11151 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011152 Value *Idx[2];
11153 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11154 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011155 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000011156 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011157 // V and GEP are both pointer types --> BitCast
11158 return new BitCastInst(V, GEP.getType());
11159 }
11160
11161 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011162 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011163 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011164 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011165
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011166 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011167 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011168 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011169
11170 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11171 // allow either a mul, shift, or constant here.
11172 Value *NewIdx = 0;
11173 ConstantInt *Scale = 0;
11174 if (ArrayEltSize == 1) {
11175 NewIdx = GEP.getOperand(1);
Dan Gohman8fd520a2009-06-15 22:12:54 +000011176 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011177 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11178 NewIdx = ConstantInt::get(CI->getType(), 1);
11179 Scale = CI;
11180 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11181 if (Inst->getOpcode() == Instruction::Shl &&
11182 isa<ConstantInt>(Inst->getOperand(1))) {
11183 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11184 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Dan Gohman8fd520a2009-06-15 22:12:54 +000011185 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11186 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011187 NewIdx = Inst->getOperand(0);
11188 } else if (Inst->getOpcode() == Instruction::Mul &&
11189 isa<ConstantInt>(Inst->getOperand(1))) {
11190 Scale = cast<ConstantInt>(Inst->getOperand(1));
11191 NewIdx = Inst->getOperand(0);
11192 }
11193 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011194
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011195 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011196 // out, perform the transformation. Note, we don't know whether Scale is
11197 // signed or not. We'll use unsigned version of division/modulo
11198 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011199 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011200 Scale->getZExtValue() % ArrayEltSize == 0) {
11201 Scale = ConstantInt::get(Scale->getType(),
11202 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011203 if (Scale->getZExtValue() != 1) {
11204 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011205 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011206 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011207 NewIdx = InsertNewInstBefore(Sc, GEP);
11208 }
11209
11210 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011211 Value *Idx[2];
11212 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11213 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011214 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011215 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011216 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11217 // The NewGEP must be pointer typed, so must the old one -> BitCast
11218 return new BitCastInst(NewGEP, GEP.getType());
11219 }
11220 }
11221 }
11222 }
Chris Lattner111ea772009-01-09 04:53:57 +000011223
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011224 /// See if we can simplify:
11225 /// X = bitcast A to B*
11226 /// Y = gep X, <...constant indices...>
11227 /// into a gep of the original struct. This is important for SROA and alias
11228 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011229 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011230 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11231 // Determine how much the GEP moves the pointer. We are guaranteed to get
11232 // a constant back from EmitGEPOffset.
11233 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11234 int64_t Offset = OffsetV->getSExtValue();
11235
11236 // If this GEP instruction doesn't move the pointer, just replace the GEP
11237 // with a bitcast of the real input to the dest type.
11238 if (Offset == 0) {
11239 // If the bitcast is of an allocation, and the allocation will be
11240 // converted to match the type of the cast, don't touch this.
11241 if (isa<AllocationInst>(BCI->getOperand(0))) {
11242 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11243 if (Instruction *I = visitBitCast(*BCI)) {
11244 if (I != BCI) {
11245 I->takeName(BCI);
11246 BCI->getParent()->getInstList().insert(BCI, I);
11247 ReplaceInstUsesWith(*BCI, I);
11248 }
11249 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011250 }
Chris Lattner111ea772009-01-09 04:53:57 +000011251 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011252 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011253 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011254
11255 // Otherwise, if the offset is non-zero, we need to find out if there is a
11256 // field at Offset in 'A's type. If so, we can pull the cast through the
11257 // GEP.
11258 SmallVector<Value*, 8> NewIndices;
11259 const Type *InTy =
11260 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11261 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11262 Instruction *NGEP =
11263 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11264 NewIndices.end());
11265 if (NGEP->getType() == GEP.getType()) return NGEP;
11266 InsertNewInstBefore(NGEP, GEP);
11267 NGEP->takeName(&GEP);
11268 return new BitCastInst(NGEP, GEP.getType());
11269 }
Chris Lattner111ea772009-01-09 04:53:57 +000011270 }
11271 }
11272
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011273 return 0;
11274}
11275
11276Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11277 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011278 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011279 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11280 const Type *NewTy =
11281 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11282 AllocationInst *New = 0;
11283
11284 // Create and insert the replacement instruction...
11285 if (isa<MallocInst>(AI))
11286 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11287 else {
11288 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11289 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11290 }
11291
11292 InsertNewInstBefore(New, AI);
11293
11294 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011295 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011296 //
11297 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011298 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011299
11300 // Now that I is pointing to the first non-allocation-inst in the block,
11301 // insert our getelementptr instruction...
11302 //
11303 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011304 Value *Idx[2];
11305 Idx[0] = NullIdx;
11306 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011307 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11308 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011309
11310 // Now make everything use the getelementptr instead of the original
11311 // allocation.
11312 return ReplaceInstUsesWith(AI, V);
11313 } else if (isa<UndefValue>(AI.getArraySize())) {
11314 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11315 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011316 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011317
Dan Gohman28e78f02009-01-13 20:18:38 +000011318 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11319 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011320 // Note that we only do this for alloca's, because malloc should allocate
11321 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011322 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Dan Gohman28e78f02009-01-13 20:18:38 +000011323 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11324
11325 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11326 if (AI.getAlignment() == 0)
11327 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11328 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011329
11330 return 0;
11331}
11332
11333Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11334 Value *Op = FI.getOperand(0);
11335
11336 // free undef -> unreachable.
11337 if (isa<UndefValue>(Op)) {
11338 // Insert a new store to null because we cannot modify the CFG here.
11339 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000011340 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011341 return EraseInstFromFunction(FI);
11342 }
11343
11344 // If we have 'free null' delete the instruction. This can happen in stl code
11345 // when lots of inlining happens.
11346 if (isa<ConstantPointerNull>(Op))
11347 return EraseInstFromFunction(FI);
11348
11349 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11350 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11351 FI.setOperand(0, CI->getOperand(0));
11352 return &FI;
11353 }
11354
11355 // Change free (gep X, 0,0,0,0) into free(X)
11356 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11357 if (GEPI->hasAllZeroIndices()) {
11358 AddToWorkList(GEPI);
11359 FI.setOperand(0, GEPI->getOperand(0));
11360 return &FI;
11361 }
11362 }
11363
11364 // Change free(malloc) into nothing, if the malloc has a single use.
11365 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11366 if (MI->hasOneUse()) {
11367 EraseInstFromFunction(FI);
11368 return EraseInstFromFunction(*MI);
11369 }
11370
11371 return 0;
11372}
11373
11374
11375/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011376static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011377 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011378 User *CI = cast<User>(LI.getOperand(0));
11379 Value *CastOp = CI->getOperand(0);
11380
Nick Lewycky291c5942009-05-08 06:47:37 +000011381 if (TD) {
11382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11383 // Instead of loading constant c string, use corresponding integer value
11384 // directly if string length is small enough.
11385 std::string Str;
11386 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11387 unsigned len = Str.length();
11388 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11389 unsigned numBits = Ty->getPrimitiveSizeInBits();
11390 // Replace LI with immediate integer store.
11391 if ((numBits >> 3) == len + 1) {
11392 APInt StrVal(numBits, 0);
11393 APInt SingleChar(numBits, 0);
11394 if (TD->isLittleEndian()) {
11395 for (signed i = len-1; i >= 0; i--) {
11396 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11397 StrVal = (StrVal << 8) | SingleChar;
11398 }
11399 } else {
11400 for (unsigned i = 0; i < len; i++) {
11401 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11402 StrVal = (StrVal << 8) | SingleChar;
11403 }
11404 // Append NULL at the end.
11405 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011406 StrVal = (StrVal << 8) | SingleChar;
11407 }
Nick Lewycky291c5942009-05-08 06:47:37 +000011408 Value *NL = ConstantInt::get(StrVal);
11409 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011410 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011411 }
11412 }
11413 }
11414
Mon P Wangbd05ed82009-02-07 22:19:29 +000011415 const PointerType *DestTy = cast<PointerType>(CI->getType());
11416 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011417 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011418
11419 // If the address spaces don't match, don't eliminate the cast.
11420 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11421 return 0;
11422
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011423 const Type *SrcPTy = SrcTy->getElementType();
11424
11425 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11426 isa<VectorType>(DestPTy)) {
11427 // If the source is an array, the code below will not succeed. Check to
11428 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11429 // constants.
11430 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11431 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11432 if (ASrcTy->getNumElements() != 0) {
11433 Value *Idxs[2];
11434 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11435 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11436 SrcTy = cast<PointerType>(CastOp->getType());
11437 SrcPTy = SrcTy->getElementType();
11438 }
11439
11440 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11441 isa<VectorType>(SrcPTy)) &&
11442 // Do not allow turning this into a load of an integer, which is then
11443 // casted to a pointer, this pessimizes pointer analysis a lot.
11444 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11445 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11446 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11447
11448 // Okay, we are casting from one integer or pointer type to another of
11449 // the same size. Instead of casting the pointer before the load, cast
11450 // the result of the loaded value.
11451 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11452 CI->getName(),
11453 LI.isVolatile()),LI);
11454 // Now cast the result of the load.
11455 return new BitCastInst(NewLoad, LI.getType());
11456 }
11457 }
11458 }
11459 return 0;
11460}
11461
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011462Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11463 Value *Op = LI.getOperand(0);
11464
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011465 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011466 unsigned KnownAlign =
11467 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011468 if (KnownAlign >
11469 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11470 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011471 LI.setAlignment(KnownAlign);
11472
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011473 // load (cast X) --> cast (load X) iff safe
11474 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011475 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011476 return Res;
11477
11478 // None of the following transforms are legal for volatile loads.
11479 if (LI.isVolatile()) return 0;
11480
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011481 // Do really simple store-to-load forwarding and load CSE, to catch cases
11482 // where there are several consequtive memory accesses to the same location,
11483 // separated by a few arithmetic operations.
11484 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011485 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11486 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011487
Christopher Lamb2c175392007-12-29 07:56:53 +000011488 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11489 const Value *GEPI0 = GEPI->getOperand(0);
11490 // TODO: Consider a target hook for valid address spaces for this xform.
11491 if (isa<ConstantPointerNull>(GEPI0) &&
11492 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011493 // Insert a new store to null instruction before the load to indicate
11494 // that this code is not reachable. We do this instead of inserting
11495 // an unreachable instruction directly because we cannot modify the
11496 // CFG.
11497 new StoreInst(UndefValue::get(LI.getType()),
11498 Constant::getNullValue(Op->getType()), &LI);
11499 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11500 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011501 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011502
11503 if (Constant *C = dyn_cast<Constant>(Op)) {
11504 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011505 // TODO: Consider a target hook for valid address spaces for this xform.
11506 if (isa<UndefValue>(C) || (C->isNullValue() &&
11507 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011508 // Insert a new store to null instruction before the load to indicate that
11509 // this code is not reachable. We do this instead of inserting an
11510 // unreachable instruction directly because we cannot modify the CFG.
11511 new StoreInst(UndefValue::get(LI.getType()),
11512 Constant::getNullValue(Op->getType()), &LI);
11513 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11514 }
11515
11516 // Instcombine load (constant global) into the value loaded.
11517 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011518 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011519 return ReplaceInstUsesWith(LI, GV->getInitializer());
11520
11521 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011522 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011523 if (CE->getOpcode() == Instruction::GetElementPtr) {
11524 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011525 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011526 if (Constant *V =
11527 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11528 return ReplaceInstUsesWith(LI, V);
11529 if (CE->getOperand(0)->isNullValue()) {
11530 // Insert a new store to null instruction before the load to indicate
11531 // that this code is not reachable. We do this instead of inserting
11532 // an unreachable instruction directly because we cannot modify the
11533 // CFG.
11534 new StoreInst(UndefValue::get(LI.getType()),
11535 Constant::getNullValue(Op->getType()), &LI);
11536 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11537 }
11538
11539 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011540 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011541 return Res;
11542 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011543 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011544 }
Chris Lattner0270a112007-08-11 18:48:48 +000011545
11546 // If this load comes from anywhere in a constant global, and if the global
11547 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011548 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011549 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011550 if (GV->getInitializer()->isNullValue())
11551 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11552 else if (isa<UndefValue>(GV->getInitializer()))
11553 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11554 }
11555 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011556
11557 if (Op->hasOneUse()) {
11558 // Change select and PHI nodes to select values instead of addresses: this
11559 // helps alias analysis out a lot, allows many others simplifications, and
11560 // exposes redundancy in the code.
11561 //
11562 // Note that we cannot do the transformation unless we know that the
11563 // introduced loads cannot trap! Something like this is valid as long as
11564 // the condition is always false: load (select bool %C, int* null, int* %G),
11565 // but it would not be valid if we transformed it to load from null
11566 // unconditionally.
11567 //
11568 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11569 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11570 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11571 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11572 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11573 SI->getOperand(1)->getName()+".val"), LI);
11574 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11575 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011576 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011577 }
11578
11579 // load (select (cond, null, P)) -> load P
11580 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11581 if (C->isNullValue()) {
11582 LI.setOperand(0, SI->getOperand(2));
11583 return &LI;
11584 }
11585
11586 // load (select (cond, P, null)) -> load P
11587 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11588 if (C->isNullValue()) {
11589 LI.setOperand(0, SI->getOperand(1));
11590 return &LI;
11591 }
11592 }
11593 }
11594 return 0;
11595}
11596
11597/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011598/// when possible. This makes it generally easy to do alias analysis and/or
11599/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011600static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11601 User *CI = cast<User>(SI.getOperand(1));
11602 Value *CastOp = CI->getOperand(0);
11603
11604 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011605 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11606 if (SrcTy == 0) return 0;
11607
11608 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011609
Chris Lattnera032c0e2009-01-16 20:08:59 +000011610 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11611 return 0;
11612
Chris Lattner54dddc72009-01-24 01:00:13 +000011613 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11614 /// to its first element. This allows us to handle things like:
11615 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11616 /// on 32-bit hosts.
11617 SmallVector<Value*, 4> NewGEPIndices;
11618
Chris Lattnera032c0e2009-01-16 20:08:59 +000011619 // If the source is an array, the code below will not succeed. Check to
11620 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11621 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011622 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11623 // Index through pointer.
11624 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11625 NewGEPIndices.push_back(Zero);
11626
11627 while (1) {
11628 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011629 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011630 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011631 NewGEPIndices.push_back(Zero);
11632 SrcPTy = STy->getElementType(0);
11633 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11634 NewGEPIndices.push_back(Zero);
11635 SrcPTy = ATy->getElementType();
11636 } else {
11637 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011638 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011639 }
11640
11641 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11642 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011643
11644 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11645 return 0;
11646
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011647 // If the pointers point into different address spaces or if they point to
11648 // values with different sizes, we can't do the transformation.
11649 if (SrcTy->getAddressSpace() !=
11650 cast<PointerType>(CI->getType())->getAddressSpace() ||
11651 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattnera032c0e2009-01-16 20:08:59 +000011652 IC.getTargetData().getTypeSizeInBits(DestPTy))
11653 return 0;
11654
11655 // Okay, we are casting from one integer or pointer type to another of
11656 // the same size. Instead of casting the pointer before
11657 // the store, cast the value to be stored.
11658 Value *NewCast;
11659 Value *SIOp0 = SI.getOperand(0);
11660 Instruction::CastOps opcode = Instruction::BitCast;
11661 const Type* CastSrcTy = SIOp0->getType();
11662 const Type* CastDstTy = SrcPTy;
11663 if (isa<PointerType>(CastDstTy)) {
11664 if (CastSrcTy->isInteger())
11665 opcode = Instruction::IntToPtr;
11666 } else if (isa<IntegerType>(CastDstTy)) {
11667 if (isa<PointerType>(SIOp0->getType()))
11668 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011669 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011670
11671 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11672 // emit a GEP to index into its first field.
11673 if (!NewGEPIndices.empty()) {
11674 if (Constant *C = dyn_cast<Constant>(CastOp))
11675 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11676 NewGEPIndices.size());
11677 else
11678 CastOp = IC.InsertNewInstBefore(
11679 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11680 NewGEPIndices.end()), SI);
11681 }
11682
Chris Lattnera032c0e2009-01-16 20:08:59 +000011683 if (Constant *C = dyn_cast<Constant>(SIOp0))
11684 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11685 else
11686 NewCast = IC.InsertNewInstBefore(
11687 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11688 SI);
11689 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011690}
11691
Chris Lattner6fd8c802008-11-27 08:56:30 +000011692/// equivalentAddressValues - Test if A and B will obviously have the same
11693/// value. This includes recognizing that %t0 and %t1 will have the same
11694/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011695/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011696/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011697/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011698/// %t2 = load i32* %t1
11699///
11700static bool equivalentAddressValues(Value *A, Value *B) {
11701 // Test if the values are trivially equivalent.
11702 if (A == B) return true;
11703
11704 // Test if the values come form identical arithmetic instructions.
11705 if (isa<BinaryOperator>(A) ||
11706 isa<CastInst>(A) ||
11707 isa<PHINode>(A) ||
11708 isa<GetElementPtrInst>(A))
11709 if (Instruction *BI = dyn_cast<Instruction>(B))
11710 if (cast<Instruction>(A)->isIdenticalTo(BI))
11711 return true;
11712
11713 // Otherwise they may not be equivalent.
11714 return false;
11715}
11716
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011717// If this instruction has two uses, one of which is a llvm.dbg.declare,
11718// return the llvm.dbg.declare.
11719DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11720 if (!V->hasNUses(2))
11721 return 0;
11722 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11723 UI != E; ++UI) {
11724 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11725 return DI;
11726 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11727 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11728 return DI;
11729 }
11730 }
11731 return 0;
11732}
11733
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011734Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11735 Value *Val = SI.getOperand(0);
11736 Value *Ptr = SI.getOperand(1);
11737
11738 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11739 EraseInstFromFunction(SI);
11740 ++NumCombined;
11741 return 0;
11742 }
11743
11744 // If the RHS is an alloca with a single use, zapify the store, making the
11745 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011746 // If the RHS is an alloca with a two uses, the other one being a
11747 // llvm.dbg.declare, zapify the store and the declare, making the
11748 // alloca dead. We must do this to prevent declare's from affecting
11749 // codegen.
11750 if (!SI.isVolatile()) {
11751 if (Ptr->hasOneUse()) {
11752 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011753 EraseInstFromFunction(SI);
11754 ++NumCombined;
11755 return 0;
11756 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011757 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11758 if (isa<AllocaInst>(GEP->getOperand(0))) {
11759 if (GEP->getOperand(0)->hasOneUse()) {
11760 EraseInstFromFunction(SI);
11761 ++NumCombined;
11762 return 0;
11763 }
11764 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11765 EraseInstFromFunction(*DI);
11766 EraseInstFromFunction(SI);
11767 ++NumCombined;
11768 return 0;
11769 }
11770 }
11771 }
11772 }
11773 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11774 EraseInstFromFunction(*DI);
11775 EraseInstFromFunction(SI);
11776 ++NumCombined;
11777 return 0;
11778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011779 }
11780
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011781 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011782 unsigned KnownAlign =
11783 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011784 if (KnownAlign >
11785 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11786 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011787 SI.setAlignment(KnownAlign);
11788
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011789 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011790 // stores to the same location, separated by a few arithmetic operations. This
11791 // situation often occurs with bitfield accesses.
11792 BasicBlock::iterator BBI = &SI;
11793 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11794 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011795 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011796 // Don't count debug info directives, lest they affect codegen,
11797 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11798 // It is necessary for correctness to skip those that feed into a
11799 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011800 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011801 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011802 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011803 continue;
11804 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011805
11806 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11807 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011808 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11809 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011810 ++NumDeadStore;
11811 ++BBI;
11812 EraseInstFromFunction(*PrevSI);
11813 continue;
11814 }
11815 break;
11816 }
11817
11818 // If this is a load, we have to stop. However, if the loaded value is from
11819 // the pointer we're loading and is producing the pointer we're storing,
11820 // then *this* store is dead (X = load P; store X -> P).
11821 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011822 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11823 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011824 EraseInstFromFunction(SI);
11825 ++NumCombined;
11826 return 0;
11827 }
11828 // Otherwise, this is a load from some other location. Stores before it
11829 // may not be dead.
11830 break;
11831 }
11832
11833 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011834 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011835 break;
11836 }
11837
11838
11839 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11840
11841 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011842 if (isa<ConstantPointerNull>(Ptr) &&
11843 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011844 if (!isa<UndefValue>(Val)) {
11845 SI.setOperand(0, UndefValue::get(Val->getType()));
11846 if (Instruction *U = dyn_cast<Instruction>(Val))
11847 AddToWorkList(U); // Dropped a use.
11848 ++NumCombined;
11849 }
11850 return 0; // Do not modify these!
11851 }
11852
11853 // store undef, Ptr -> noop
11854 if (isa<UndefValue>(Val)) {
11855 EraseInstFromFunction(SI);
11856 ++NumCombined;
11857 return 0;
11858 }
11859
11860 // If the pointer destination is a cast, see if we can fold the cast into the
11861 // source instead.
11862 if (isa<CastInst>(Ptr))
11863 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11864 return Res;
11865 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11866 if (CE->isCast())
11867 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11868 return Res;
11869
11870
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011871 // If this store is the last instruction in the basic block (possibly
11872 // excepting debug info instructions and the pointer bitcasts that feed
11873 // into them), and if the block ends with an unconditional branch, try
11874 // to move it to the successor block.
11875 BBI = &SI;
11876 do {
11877 ++BBI;
11878 } while (isa<DbgInfoIntrinsic>(BBI) ||
11879 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011880 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11881 if (BI->isUnconditional())
11882 if (SimplifyStoreAtEndOfBlock(SI))
11883 return 0; // xform done!
11884
11885 return 0;
11886}
11887
11888/// SimplifyStoreAtEndOfBlock - Turn things like:
11889/// if () { *P = v1; } else { *P = v2 }
11890/// into a phi node with a store in the successor.
11891///
11892/// Simplify things like:
11893/// *P = v1; if () { *P = v2; }
11894/// into a phi node with a store in the successor.
11895///
11896bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11897 BasicBlock *StoreBB = SI.getParent();
11898
11899 // Check to see if the successor block has exactly two incoming edges. If
11900 // so, see if the other predecessor contains a store to the same location.
11901 // if so, insert a PHI node (if needed) and move the stores down.
11902 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11903
11904 // Determine whether Dest has exactly two predecessors and, if so, compute
11905 // the other predecessor.
11906 pred_iterator PI = pred_begin(DestBB);
11907 BasicBlock *OtherBB = 0;
11908 if (*PI != StoreBB)
11909 OtherBB = *PI;
11910 ++PI;
11911 if (PI == pred_end(DestBB))
11912 return false;
11913
11914 if (*PI != StoreBB) {
11915 if (OtherBB)
11916 return false;
11917 OtherBB = *PI;
11918 }
11919 if (++PI != pred_end(DestBB))
11920 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011921
11922 // Bail out if all the relevant blocks aren't distinct (this can happen,
11923 // for example, if SI is in an infinite loop)
11924 if (StoreBB == DestBB || OtherBB == DestBB)
11925 return false;
11926
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011927 // Verify that the other block ends in a branch and is not otherwise empty.
11928 BasicBlock::iterator BBI = OtherBB->getTerminator();
11929 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11930 if (!OtherBr || BBI == OtherBB->begin())
11931 return false;
11932
11933 // If the other block ends in an unconditional branch, check for the 'if then
11934 // else' case. there is an instruction before the branch.
11935 StoreInst *OtherStore = 0;
11936 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011937 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011938 // Skip over debugging info.
11939 while (isa<DbgInfoIntrinsic>(BBI) ||
11940 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11941 if (BBI==OtherBB->begin())
11942 return false;
11943 --BBI;
11944 }
11945 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011946 OtherStore = dyn_cast<StoreInst>(BBI);
11947 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11948 return false;
11949 } else {
11950 // Otherwise, the other block ended with a conditional branch. If one of the
11951 // destinations is StoreBB, then we have the if/then case.
11952 if (OtherBr->getSuccessor(0) != StoreBB &&
11953 OtherBr->getSuccessor(1) != StoreBB)
11954 return false;
11955
11956 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11957 // if/then triangle. See if there is a store to the same ptr as SI that
11958 // lives in OtherBB.
11959 for (;; --BBI) {
11960 // Check to see if we find the matching store.
11961 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11962 if (OtherStore->getOperand(1) != SI.getOperand(1))
11963 return false;
11964 break;
11965 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011966 // If we find something that may be using or overwriting the stored
11967 // value, or if we run out of instructions, we can't do the xform.
11968 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011969 BBI == OtherBB->begin())
11970 return false;
11971 }
11972
11973 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011974 // make sure nothing reads or overwrites the stored value in
11975 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011976 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11977 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011978 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011979 return false;
11980 }
11981 }
11982
11983 // Insert a PHI node now if we need it.
11984 Value *MergedVal = OtherStore->getOperand(0);
11985 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011986 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011987 PN->reserveOperandSpace(2);
11988 PN->addIncoming(SI.getOperand(0), SI.getParent());
11989 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11990 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11991 }
11992
11993 // Advance to a place where it is safe to insert the new store and
11994 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011995 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011996 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11997 OtherStore->isVolatile()), *BBI);
11998
11999 // Nuke the old stores.
12000 EraseInstFromFunction(SI);
12001 EraseInstFromFunction(*OtherStore);
12002 ++NumCombined;
12003 return true;
12004}
12005
12006
12007Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12008 // Change br (not X), label True, label False to: br X, label False, True
12009 Value *X = 0;
12010 BasicBlock *TrueDest;
12011 BasicBlock *FalseDest;
12012 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12013 !isa<Constant>(X)) {
12014 // Swap Destinations and condition...
12015 BI.setCondition(X);
12016 BI.setSuccessor(0, FalseDest);
12017 BI.setSuccessor(1, TrueDest);
12018 return &BI;
12019 }
12020
12021 // Cannonicalize fcmp_one -> fcmp_oeq
12022 FCmpInst::Predicate FPred; Value *Y;
12023 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12024 TrueDest, FalseDest)))
12025 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12026 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12027 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12028 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12029 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12030 NewSCC->takeName(I);
12031 // Swap Destinations and condition...
12032 BI.setCondition(NewSCC);
12033 BI.setSuccessor(0, FalseDest);
12034 BI.setSuccessor(1, TrueDest);
12035 RemoveFromWorkList(I);
12036 I->eraseFromParent();
12037 AddToWorkList(NewSCC);
12038 return &BI;
12039 }
12040
12041 // Cannonicalize icmp_ne -> icmp_eq
12042 ICmpInst::Predicate IPred;
12043 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12044 TrueDest, FalseDest)))
12045 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12046 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12047 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12048 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12049 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12050 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12051 NewSCC->takeName(I);
12052 // Swap Destinations and condition...
12053 BI.setCondition(NewSCC);
12054 BI.setSuccessor(0, FalseDest);
12055 BI.setSuccessor(1, TrueDest);
12056 RemoveFromWorkList(I);
12057 I->eraseFromParent();;
12058 AddToWorkList(NewSCC);
12059 return &BI;
12060 }
12061
12062 return 0;
12063}
12064
12065Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12066 Value *Cond = SI.getCondition();
12067 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12068 if (I->getOpcode() == Instruction::Add)
12069 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12070 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12071 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12072 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12073 AddRHS));
12074 SI.setOperand(0, I->getOperand(0));
12075 AddToWorkList(I);
12076 return &SI;
12077 }
12078 }
12079 return 0;
12080}
12081
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012082Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012083 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012084
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012085 if (!EV.hasIndices())
12086 return ReplaceInstUsesWith(EV, Agg);
12087
12088 if (Constant *C = dyn_cast<Constant>(Agg)) {
12089 if (isa<UndefValue>(C))
12090 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12091
12092 if (isa<ConstantAggregateZero>(C))
12093 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12094
12095 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12096 // Extract the element indexed by the first index out of the constant
12097 Value *V = C->getOperand(*EV.idx_begin());
12098 if (EV.getNumIndices() > 1)
12099 // Extract the remaining indices out of the constant indexed by the
12100 // first index
12101 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12102 else
12103 return ReplaceInstUsesWith(EV, V);
12104 }
12105 return 0; // Can't handle other constants
12106 }
12107 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12108 // We're extracting from an insertvalue instruction, compare the indices
12109 const unsigned *exti, *exte, *insi, *inse;
12110 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12111 exte = EV.idx_end(), inse = IV->idx_end();
12112 exti != exte && insi != inse;
12113 ++exti, ++insi) {
12114 if (*insi != *exti)
12115 // The insert and extract both reference distinctly different elements.
12116 // This means the extract is not influenced by the insert, and we can
12117 // replace the aggregate operand of the extract with the aggregate
12118 // operand of the insert. i.e., replace
12119 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12120 // %E = extractvalue { i32, { i32 } } %I, 0
12121 // with
12122 // %E = extractvalue { i32, { i32 } } %A, 0
12123 return ExtractValueInst::Create(IV->getAggregateOperand(),
12124 EV.idx_begin(), EV.idx_end());
12125 }
12126 if (exti == exte && insi == inse)
12127 // Both iterators are at the end: Index lists are identical. Replace
12128 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12129 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12130 // with "i32 42"
12131 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12132 if (exti == exte) {
12133 // The extract list is a prefix of the insert list. i.e. replace
12134 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12135 // %E = extractvalue { i32, { i32 } } %I, 1
12136 // with
12137 // %X = extractvalue { i32, { i32 } } %A, 1
12138 // %E = insertvalue { i32 } %X, i32 42, 0
12139 // by switching the order of the insert and extract (though the
12140 // insertvalue should be left in, since it may have other uses).
12141 Value *NewEV = InsertNewInstBefore(
12142 ExtractValueInst::Create(IV->getAggregateOperand(),
12143 EV.idx_begin(), EV.idx_end()),
12144 EV);
12145 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12146 insi, inse);
12147 }
12148 if (insi == inse)
12149 // The insert list is a prefix of the extract list
12150 // We can simply remove the common indices from the extract and make it
12151 // operate on the inserted value instead of the insertvalue result.
12152 // i.e., replace
12153 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12154 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12155 // with
12156 // %E extractvalue { i32 } { i32 42 }, 0
12157 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12158 exti, exte);
12159 }
12160 // Can't simplify extracts from other values. Note that nested extracts are
12161 // already simplified implicitely by the above (extract ( extract (insert) )
12162 // will be translated into extract ( insert ( extract ) ) first and then just
12163 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012164 return 0;
12165}
12166
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012167/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12168/// is to leave as a vector operation.
12169static bool CheapToScalarize(Value *V, bool isConstant) {
12170 if (isa<ConstantAggregateZero>(V))
12171 return true;
12172 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12173 if (isConstant) return true;
12174 // If all elts are the same, we can extract.
12175 Constant *Op0 = C->getOperand(0);
12176 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12177 if (C->getOperand(i) != Op0)
12178 return false;
12179 return true;
12180 }
12181 Instruction *I = dyn_cast<Instruction>(V);
12182 if (!I) return false;
12183
12184 // Insert element gets simplified to the inserted element or is deleted if
12185 // this is constant idx extract element and its a constant idx insertelt.
12186 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12187 isa<ConstantInt>(I->getOperand(2)))
12188 return true;
12189 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12190 return true;
12191 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12192 if (BO->hasOneUse() &&
12193 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12194 CheapToScalarize(BO->getOperand(1), isConstant)))
12195 return true;
12196 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12197 if (CI->hasOneUse() &&
12198 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12199 CheapToScalarize(CI->getOperand(1), isConstant)))
12200 return true;
12201
12202 return false;
12203}
12204
12205/// Read and decode a shufflevector mask.
12206///
12207/// It turns undef elements into values that are larger than the number of
12208/// elements in the input.
12209static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12210 unsigned NElts = SVI->getType()->getNumElements();
12211 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12212 return std::vector<unsigned>(NElts, 0);
12213 if (isa<UndefValue>(SVI->getOperand(2)))
12214 return std::vector<unsigned>(NElts, 2*NElts);
12215
12216 std::vector<unsigned> Result;
12217 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012218 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12219 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012220 Result.push_back(NElts*2); // undef -> 8
12221 else
Gabor Greif17396002008-06-12 21:37:33 +000012222 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012223 return Result;
12224}
12225
12226/// FindScalarElement - Given a vector and an element number, see if the scalar
12227/// value is already around as a register, for example if it were inserted then
12228/// extracted from the vector.
12229static Value *FindScalarElement(Value *V, unsigned EltNo) {
12230 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12231 const VectorType *PTy = cast<VectorType>(V->getType());
12232 unsigned Width = PTy->getNumElements();
12233 if (EltNo >= Width) // Out of range access.
12234 return UndefValue::get(PTy->getElementType());
12235
12236 if (isa<UndefValue>(V))
12237 return UndefValue::get(PTy->getElementType());
12238 else if (isa<ConstantAggregateZero>(V))
12239 return Constant::getNullValue(PTy->getElementType());
12240 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12241 return CP->getOperand(EltNo);
12242 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12243 // If this is an insert to a variable element, we don't know what it is.
12244 if (!isa<ConstantInt>(III->getOperand(2)))
12245 return 0;
12246 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12247
12248 // If this is an insert to the element we are looking for, return the
12249 // inserted value.
12250 if (EltNo == IIElt)
12251 return III->getOperand(1);
12252
12253 // Otherwise, the insertelement doesn't modify the value, recurse on its
12254 // vector input.
12255 return FindScalarElement(III->getOperand(0), EltNo);
12256 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012257 unsigned LHSWidth =
12258 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012259 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012260 if (InEl < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012261 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012262 else if (InEl < LHSWidth*2)
12263 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012264 else
12265 return UndefValue::get(PTy->getElementType());
12266 }
12267
12268 // Otherwise, we don't know.
12269 return 0;
12270}
12271
12272Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012273 // If vector val is undef, replace extract with scalar undef.
12274 if (isa<UndefValue>(EI.getOperand(0)))
12275 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12276
12277 // If vector val is constant 0, replace extract with scalar 0.
12278 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12279 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12280
12281 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012282 // If vector val is constant with all elements the same, replace EI with
12283 // that element. When the elements are not identical, we cannot replace yet
12284 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012285 Constant *op0 = C->getOperand(0);
12286 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12287 if (C->getOperand(i) != op0) {
12288 op0 = 0;
12289 break;
12290 }
12291 if (op0)
12292 return ReplaceInstUsesWith(EI, op0);
12293 }
12294
12295 // If extracting a specified index from the vector, see if we can recursively
12296 // find a previously computed scalar that was inserted into the vector.
12297 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12298 unsigned IndexVal = IdxC->getZExtValue();
12299 unsigned VectorWidth =
12300 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12301
12302 // If this is extracting an invalid index, turn this into undef, to avoid
12303 // crashing the code below.
12304 if (IndexVal >= VectorWidth)
12305 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12306
12307 // This instruction only demands the single element from the input vector.
12308 // If the input vector has a single use, simplify it based on this use
12309 // property.
12310 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012311 APInt UndefElts(VectorWidth, 0);
12312 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012313 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012314 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012315 EI.setOperand(0, V);
12316 return &EI;
12317 }
12318 }
12319
12320 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12321 return ReplaceInstUsesWith(EI, Elt);
12322
12323 // If the this extractelement is directly using a bitcast from a vector of
12324 // the same number of elements, see if we can find the source element from
12325 // it. In this case, we will end up needing to bitcast the scalars.
12326 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12327 if (const VectorType *VT =
12328 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12329 if (VT->getNumElements() == VectorWidth)
12330 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12331 return new BitCastInst(Elt, EI.getType());
12332 }
12333 }
12334
12335 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12336 if (I->hasOneUse()) {
12337 // Push extractelement into predecessor operation if legal and
12338 // profitable to do so
12339 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12340 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12341 if (CheapToScalarize(BO, isConstantElt)) {
12342 ExtractElementInst *newEI0 =
12343 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12344 EI.getName()+".lhs");
12345 ExtractElementInst *newEI1 =
12346 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12347 EI.getName()+".rhs");
12348 InsertNewInstBefore(newEI0, EI);
12349 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012350 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012351 }
12352 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012353 unsigned AS =
12354 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012355 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12356 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012357 GetElementPtrInst *GEP =
12358 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012359 InsertNewInstBefore(GEP, EI);
12360 return new LoadInst(GEP);
12361 }
12362 }
12363 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12364 // Extracting the inserted element?
12365 if (IE->getOperand(2) == EI.getOperand(1))
12366 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12367 // If the inserted and extracted elements are constants, they must not
12368 // be the same value, extract from the pre-inserted value instead.
12369 if (isa<Constant>(IE->getOperand(2)) &&
12370 isa<Constant>(EI.getOperand(1))) {
12371 AddUsesToWorkList(EI);
12372 EI.setOperand(0, IE->getOperand(0));
12373 return &EI;
12374 }
12375 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12376 // If this is extracting an element from a shufflevector, figure out where
12377 // it came from and extract from the appropriate input element instead.
12378 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12379 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12380 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012381 unsigned LHSWidth =
12382 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12383
12384 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012385 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012386 else if (SrcIdx < LHSWidth*2) {
12387 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012388 Src = SVI->getOperand(1);
12389 } else {
12390 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12391 }
12392 return new ExtractElementInst(Src, SrcIdx);
12393 }
12394 }
12395 }
12396 return 0;
12397}
12398
12399/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12400/// elements from either LHS or RHS, return the shuffle mask and true.
12401/// Otherwise, return false.
12402static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12403 std::vector<Constant*> &Mask) {
12404 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12405 "Invalid CollectSingleShuffleElements");
12406 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12407
12408 if (isa<UndefValue>(V)) {
12409 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12410 return true;
12411 } else if (V == LHS) {
12412 for (unsigned i = 0; i != NumElts; ++i)
12413 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12414 return true;
12415 } else if (V == RHS) {
12416 for (unsigned i = 0; i != NumElts; ++i)
12417 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12418 return true;
12419 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12420 // If this is an insert of an extract from some other vector, include it.
12421 Value *VecOp = IEI->getOperand(0);
12422 Value *ScalarOp = IEI->getOperand(1);
12423 Value *IdxOp = IEI->getOperand(2);
12424
12425 if (!isa<ConstantInt>(IdxOp))
12426 return false;
12427 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12428
12429 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12430 // Okay, we can handle this if the vector we are insertinting into is
12431 // transitively ok.
12432 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12433 // If so, update the mask to reflect the inserted undef.
12434 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12435 return true;
12436 }
12437 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12438 if (isa<ConstantInt>(EI->getOperand(1)) &&
12439 EI->getOperand(0)->getType() == V->getType()) {
12440 unsigned ExtractedIdx =
12441 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12442
12443 // This must be extracting from either LHS or RHS.
12444 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12445 // Okay, we can handle this if the vector we are insertinting into is
12446 // transitively ok.
12447 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12448 // If so, update the mask to reflect the inserted value.
12449 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012450 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012451 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12452 } else {
12453 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012454 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012455 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12456
12457 }
12458 return true;
12459 }
12460 }
12461 }
12462 }
12463 }
12464 // TODO: Handle shufflevector here!
12465
12466 return false;
12467}
12468
12469/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12470/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12471/// that computes V and the LHS value of the shuffle.
12472static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12473 Value *&RHS) {
12474 assert(isa<VectorType>(V->getType()) &&
12475 (RHS == 0 || V->getType() == RHS->getType()) &&
12476 "Invalid shuffle!");
12477 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12478
12479 if (isa<UndefValue>(V)) {
12480 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12481 return V;
12482 } else if (isa<ConstantAggregateZero>(V)) {
12483 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12484 return V;
12485 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12486 // If this is an insert of an extract from some other vector, include it.
12487 Value *VecOp = IEI->getOperand(0);
12488 Value *ScalarOp = IEI->getOperand(1);
12489 Value *IdxOp = IEI->getOperand(2);
12490
12491 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12492 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12493 EI->getOperand(0)->getType() == V->getType()) {
12494 unsigned ExtractedIdx =
12495 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12496 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12497
12498 // Either the extracted from or inserted into vector must be RHSVec,
12499 // otherwise we'd end up with a shuffle of three inputs.
12500 if (EI->getOperand(0) == RHS || RHS == 0) {
12501 RHS = EI->getOperand(0);
12502 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012503 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012504 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12505 return V;
12506 }
12507
12508 if (VecOp == RHS) {
12509 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12510 // Everything but the extracted element is replaced with the RHS.
12511 for (unsigned i = 0; i != NumElts; ++i) {
12512 if (i != InsertedIdx)
12513 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12514 }
12515 return V;
12516 }
12517
12518 // If this insertelement is a chain that comes from exactly these two
12519 // vectors, return the vector and the effective shuffle.
12520 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12521 return EI->getOperand(0);
12522
12523 }
12524 }
12525 }
12526 // TODO: Handle shufflevector here!
12527
12528 // Otherwise, can't do anything fancy. Return an identity vector.
12529 for (unsigned i = 0; i != NumElts; ++i)
12530 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12531 return V;
12532}
12533
12534Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12535 Value *VecOp = IE.getOperand(0);
12536 Value *ScalarOp = IE.getOperand(1);
12537 Value *IdxOp = IE.getOperand(2);
12538
12539 // Inserting an undef or into an undefined place, remove this.
12540 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12541 ReplaceInstUsesWith(IE, VecOp);
12542
12543 // If the inserted element was extracted from some other vector, and if the
12544 // indexes are constant, try to turn this into a shufflevector operation.
12545 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12546 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12547 EI->getOperand(0)->getType() == IE.getType()) {
12548 unsigned NumVectorElts = IE.getType()->getNumElements();
12549 unsigned ExtractedIdx =
12550 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12551 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12552
12553 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12554 return ReplaceInstUsesWith(IE, VecOp);
12555
12556 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12557 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12558
12559 // If we are extracting a value from a vector, then inserting it right
12560 // back into the same place, just use the input vector.
12561 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12562 return ReplaceInstUsesWith(IE, VecOp);
12563
12564 // We could theoretically do this for ANY input. However, doing so could
12565 // turn chains of insertelement instructions into a chain of shufflevector
12566 // instructions, and right now we do not merge shufflevectors. As such,
12567 // only do this in a situation where it is clear that there is benefit.
12568 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12569 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12570 // the values of VecOp, except then one read from EIOp0.
12571 // Build a new shuffle mask.
12572 std::vector<Constant*> Mask;
12573 if (isa<UndefValue>(VecOp))
12574 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12575 else {
12576 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12577 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12578 NumVectorElts));
12579 }
12580 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12581 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12582 ConstantVector::get(Mask));
12583 }
12584
12585 // If this insertelement isn't used by some other insertelement, turn it
12586 // (and any insertelements it points to), into one big shuffle.
12587 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12588 std::vector<Constant*> Mask;
12589 Value *RHS = 0;
12590 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12591 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12592 // We now have a shuffle of LHS, RHS, Mask.
12593 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12594 }
12595 }
12596 }
12597
Eli Friedmanbefee262009-06-06 20:08:03 +000012598 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12599 APInt UndefElts(VWidth, 0);
12600 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12601 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12602 return &IE;
12603
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012604 return 0;
12605}
12606
12607
12608Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12609 Value *LHS = SVI.getOperand(0);
12610 Value *RHS = SVI.getOperand(1);
12611 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12612
12613 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012614
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012615 // Undefined shuffle mask -> undefined value.
12616 if (isa<UndefValue>(SVI.getOperand(2)))
12617 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012618
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012619 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012620
12621 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12622 return 0;
12623
Evan Cheng63295ab2009-02-03 10:05:09 +000012624 APInt UndefElts(VWidth, 0);
12625 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12626 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012627 LHS = SVI.getOperand(0);
12628 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012629 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012630 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012631
12632 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12633 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12634 if (LHS == RHS || isa<UndefValue>(LHS)) {
12635 if (isa<UndefValue>(LHS) && LHS == RHS) {
12636 // shuffle(undef,undef,mask) -> undef.
12637 return ReplaceInstUsesWith(SVI, LHS);
12638 }
12639
12640 // Remap any references to RHS to use LHS.
12641 std::vector<Constant*> Elts;
12642 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12643 if (Mask[i] >= 2*e)
12644 Elts.push_back(UndefValue::get(Type::Int32Ty));
12645 else {
12646 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012647 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012648 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012649 Elts.push_back(UndefValue::get(Type::Int32Ty));
12650 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012651 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012652 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12653 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012654 }
12655 }
12656 SVI.setOperand(0, SVI.getOperand(1));
12657 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12658 SVI.setOperand(2, ConstantVector::get(Elts));
12659 LHS = SVI.getOperand(0);
12660 RHS = SVI.getOperand(1);
12661 MadeChange = true;
12662 }
12663
12664 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12665 bool isLHSID = true, isRHSID = true;
12666
12667 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12668 if (Mask[i] >= e*2) continue; // Ignore undef values.
12669 // Is this an identity shuffle of the LHS value?
12670 isLHSID &= (Mask[i] == i);
12671
12672 // Is this an identity shuffle of the RHS value?
12673 isRHSID &= (Mask[i]-e == i);
12674 }
12675
12676 // Eliminate identity shuffles.
12677 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12678 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12679
12680 // If the LHS is a shufflevector itself, see if we can combine it with this
12681 // one without producing an unusual shuffle. Here we are really conservative:
12682 // we are absolutely afraid of producing a shuffle mask not in the input
12683 // program, because the code gen may not be smart enough to turn a merged
12684 // shuffle into two specific shuffles: it may produce worse code. As such,
12685 // we only merge two shuffles if the result is one of the two input shuffle
12686 // masks. In this case, merging the shuffles just removes one instruction,
12687 // which we know is safe. This is good for things like turning:
12688 // (splat(splat)) -> splat.
12689 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12690 if (isa<UndefValue>(RHS)) {
12691 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12692
12693 std::vector<unsigned> NewMask;
12694 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12695 if (Mask[i] >= 2*e)
12696 NewMask.push_back(2*e);
12697 else
12698 NewMask.push_back(LHSMask[Mask[i]]);
12699
12700 // If the result mask is equal to the src shuffle or this shuffle mask, do
12701 // the replacement.
12702 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012703 unsigned LHSInNElts =
12704 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012705 std::vector<Constant*> Elts;
12706 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012707 if (NewMask[i] >= LHSInNElts*2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012708 Elts.push_back(UndefValue::get(Type::Int32Ty));
12709 } else {
12710 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12711 }
12712 }
12713 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12714 LHSSVI->getOperand(1),
12715 ConstantVector::get(Elts));
12716 }
12717 }
12718 }
12719
12720 return MadeChange ? &SVI : 0;
12721}
12722
12723
12724
12725
12726/// TryToSinkInstruction - Try to move the specified instruction from its
12727/// current block into the beginning of DestBlock, which can only happen if it's
12728/// safe to move the instruction past all of the instructions between it and the
12729/// end of its block.
12730static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12731 assert(I->hasOneUse() && "Invariants didn't hold!");
12732
12733 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012734 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012735 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012736
12737 // Do not sink alloca instructions out of the entry block.
12738 if (isa<AllocaInst>(I) && I->getParent() ==
12739 &DestBlock->getParent()->getEntryBlock())
12740 return false;
12741
12742 // We can only sink load instructions if there is nothing between the load and
12743 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012744 if (I->mayReadFromMemory()) {
12745 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012746 Scan != E; ++Scan)
12747 if (Scan->mayWriteToMemory())
12748 return false;
12749 }
12750
Dan Gohman514277c2008-05-23 21:05:58 +000012751 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012752
Dale Johannesen24339f12009-03-03 01:09:07 +000012753 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012754 I->moveBefore(InsertPos);
12755 ++NumSunkInst;
12756 return true;
12757}
12758
12759
12760/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12761/// all reachable code to the worklist.
12762///
12763/// This has a couple of tricks to make the code faster and more powerful. In
12764/// particular, we constant fold and DCE instructions as we go, to avoid adding
12765/// them to the worklist (this significantly speeds up instcombine on code where
12766/// many instructions are dead or constant). Additionally, if we find a branch
12767/// whose condition is a known constant, we only visit the reachable successors.
12768///
12769static void AddReachableCodeToWorklist(BasicBlock *BB,
12770 SmallPtrSet<BasicBlock*, 64> &Visited,
12771 InstCombiner &IC,
12772 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012773 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012774 Worklist.push_back(BB);
12775
12776 while (!Worklist.empty()) {
12777 BB = Worklist.back();
12778 Worklist.pop_back();
12779
12780 // We have now visited this block! If we've already been here, ignore it.
12781 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012782
12783 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012784 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12785 Instruction *Inst = BBI++;
12786
12787 // DCE instruction if trivially dead.
12788 if (isInstructionTriviallyDead(Inst)) {
12789 ++NumDeadInst;
12790 DOUT << "IC: DCE: " << *Inst;
12791 Inst->eraseFromParent();
12792 continue;
12793 }
12794
12795 // ConstantProp instruction if trivially constant.
12796 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12797 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12798 Inst->replaceAllUsesWith(C);
12799 ++NumConstProp;
12800 Inst->eraseFromParent();
12801 continue;
12802 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012803
Devang Patel794140c2008-11-19 18:56:50 +000012804 // If there are two consecutive llvm.dbg.stoppoint calls then
12805 // it is likely that the optimizer deleted code in between these
12806 // two intrinsics.
12807 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12808 if (DBI_Next) {
12809 if (DBI_Prev
12810 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12811 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12812 IC.RemoveFromWorkList(DBI_Prev);
12813 DBI_Prev->eraseFromParent();
12814 }
12815 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012816 } else {
12817 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012818 }
12819
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012820 IC.AddToWorkList(Inst);
12821 }
12822
12823 // Recursively visit successors. If this is a branch or switch on a
12824 // constant, only visit the reachable successor.
12825 TerminatorInst *TI = BB->getTerminator();
12826 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12827 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12828 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012829 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012830 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012831 continue;
12832 }
12833 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12834 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12835 // See if this is an explicit destination.
12836 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12837 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012838 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012839 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012840 continue;
12841 }
12842
12843 // Otherwise it is the default destination.
12844 Worklist.push_back(SI->getSuccessor(0));
12845 continue;
12846 }
12847 }
12848
12849 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12850 Worklist.push_back(TI->getSuccessor(i));
12851 }
12852}
12853
12854bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12855 bool Changed = false;
12856 TD = &getAnalysis<TargetData>();
12857
12858 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12859 << F.getNameStr() << "\n");
12860
12861 {
12862 // Do a depth-first traversal of the function, populate the worklist with
12863 // the reachable instructions. Ignore blocks that are not reachable. Keep
12864 // track of which blocks we visit.
12865 SmallPtrSet<BasicBlock*, 64> Visited;
12866 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12867
12868 // Do a quick scan over the function. If we find any blocks that are
12869 // unreachable, remove any instructions inside of them. This prevents
12870 // the instcombine code from having to deal with some bad special cases.
12871 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12872 if (!Visited.count(BB)) {
12873 Instruction *Term = BB->getTerminator();
12874 while (Term != BB->begin()) { // Remove instrs bottom-up
12875 BasicBlock::iterator I = Term; --I;
12876
12877 DOUT << "IC: DCE: " << *I;
Dale Johannesendf356c62009-03-10 21:19:49 +000012878 // A debug intrinsic shouldn't force another iteration if we weren't
12879 // going to do one without it.
12880 if (!isa<DbgInfoIntrinsic>(I)) {
12881 ++NumDeadInst;
12882 Changed = true;
12883 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012884 if (!I->use_empty())
12885 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12886 I->eraseFromParent();
12887 }
12888 }
12889 }
12890
12891 while (!Worklist.empty()) {
12892 Instruction *I = RemoveOneFromWorkList();
12893 if (I == 0) continue; // skip null values.
12894
12895 // Check to see if we can DCE the instruction.
12896 if (isInstructionTriviallyDead(I)) {
12897 // Add operands to the worklist.
12898 if (I->getNumOperands() < 4)
12899 AddUsesToWorkList(*I);
12900 ++NumDeadInst;
12901
12902 DOUT << "IC: DCE: " << *I;
12903
12904 I->eraseFromParent();
12905 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012906 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012907 continue;
12908 }
12909
12910 // Instruction isn't dead, see if we can constant propagate it.
12911 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12912 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12913
12914 // Add operands to the worklist.
12915 AddUsesToWorkList(*I);
12916 ReplaceInstUsesWith(*I, C);
12917
12918 ++NumConstProp;
12919 I->eraseFromParent();
12920 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000012921 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012922 continue;
12923 }
12924
Dan Gohman95b95de2009-05-07 19:43:39 +000012925 if (TD &&
12926 (I->getType()->getTypeID() == Type::VoidTyID ||
12927 I->isTrapping())) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000012928 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000012929 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12930 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewyckyadb67922008-05-25 20:56:15 +000012931 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000012932 if (NewC != CE) {
12933 i->set(NewC);
12934 Changed = true;
12935 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000012936 }
12937
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012938 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012939 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012940 BasicBlock *BB = I->getParent();
12941 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12942 if (UserParent != BB) {
12943 bool UserIsSuccessor = false;
12944 // See if the user is one of our successors.
12945 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12946 if (*SI == UserParent) {
12947 UserIsSuccessor = true;
12948 break;
12949 }
12950
12951 // If the user is one of our immediate successors, and if that successor
12952 // only has us as a predecessors (we'd have to split the critical edge
12953 // otherwise), we can keep going.
12954 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12955 next(pred_begin(UserParent)) == pred_end(UserParent))
12956 // Okay, the CFG is simple enough, try to sink this instruction.
12957 Changed |= TryToSinkInstruction(I, UserParent);
12958 }
12959 }
12960
12961 // Now that we have an instruction, try combining it to simplify it...
12962#ifndef NDEBUG
12963 std::string OrigI;
12964#endif
12965 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12966 if (Instruction *Result = visit(*I)) {
12967 ++NumCombined;
12968 // Should we replace the old instruction with a new one?
12969 if (Result != I) {
12970 DOUT << "IC: Old = " << *I
12971 << " New = " << *Result;
12972
12973 // Everything uses the new instruction now.
12974 I->replaceAllUsesWith(Result);
12975
12976 // Push the new instruction and any users onto the worklist.
12977 AddToWorkList(Result);
12978 AddUsersToWorkList(*Result);
12979
12980 // Move the name to the new instruction first.
12981 Result->takeName(I);
12982
12983 // Insert the new instruction into the basic block...
12984 BasicBlock *InstParent = I->getParent();
12985 BasicBlock::iterator InsertPos = I;
12986
12987 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12988 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12989 ++InsertPos;
12990
12991 InstParent->getInstList().insert(InsertPos, Result);
12992
12993 // Make sure that we reprocess all operands now that we reduced their
12994 // use counts.
12995 AddUsesToWorkList(*I);
12996
12997 // Instructions can end up on the worklist more than once. Make sure
12998 // we do not process an instruction that has been deleted.
12999 RemoveFromWorkList(I);
13000
13001 // Erase the old instruction.
13002 InstParent->getInstList().erase(I);
13003 } else {
13004#ifndef NDEBUG
13005 DOUT << "IC: Mod = " << OrigI
13006 << " New = " << *I;
13007#endif
13008
13009 // If the instruction was modified, it's possible that it is now dead.
13010 // if so, remove it.
13011 if (isInstructionTriviallyDead(I)) {
13012 // Make sure we process all operands now that we are reducing their
13013 // use counts.
13014 AddUsesToWorkList(*I);
13015
13016 // Instructions may end up in the worklist more than once. Erase all
13017 // occurrences of this instruction.
13018 RemoveFromWorkList(I);
13019 I->eraseFromParent();
13020 } else {
13021 AddToWorkList(I);
13022 AddUsersToWorkList(*I);
13023 }
13024 }
13025 Changed = true;
13026 }
13027 }
13028
13029 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013030
13031 // Do an explicit clear, this shrinks the map if needed.
13032 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013033 return Changed;
13034}
13035
13036
13037bool InstCombiner::runOnFunction(Function &F) {
13038 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13039
13040 bool EverMadeChange = false;
13041
13042 // Iterate while there is work to do.
13043 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013044 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013045 EverMadeChange = true;
13046 return EverMadeChange;
13047}
13048
13049FunctionPass *llvm::createInstructionCombiningPass() {
13050 return new InstCombiner();
13051}