blob: 95ed49d5262250c85a97b4bf6b70d437d5db0ba2 [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);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
183 Instruction *visitAnd(BinaryOperator &I);
184 Instruction *visitOr (BinaryOperator &I);
185 Instruction *visitXor(BinaryOperator &I);
186 Instruction *visitShl(BinaryOperator &I);
187 Instruction *visitAShr(BinaryOperator &I);
188 Instruction *visitLShr(BinaryOperator &I);
189 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000190 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196 Instruction *LHS,
197 ConstantInt *RHS);
198 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199 ConstantInt *DivRHS);
200
201 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
203 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
204 BinaryOperator &I);
205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonIntCastTransforms(CastInst &CI);
207 Instruction *commonPointerCastTransforms(CastInst &CI);
208 Instruction *visitTrunc(TruncInst &CI);
209 Instruction *visitZExt(ZExtInst &CI);
210 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000211 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000213 Instruction *visitFPToUI(FPToUIInst &FI);
214 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 Instruction *visitUIToFP(CastInst &CI);
216 Instruction *visitSIToFP(CastInst &CI);
217 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000218 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitBitCast(BitCastInst &CI);
220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221 Instruction *FI);
Dan Gohman58c09632008-09-16 18:46:06 +0000222 Instruction *visitSelectInst(SelectInst &SI);
223 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 Instruction *visitCallInst(CallInst &CI);
225 Instruction *visitInvokeInst(InvokeInst &II);
226 Instruction *visitPHINode(PHINode &PN);
227 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
228 Instruction *visitAllocationInst(AllocationInst &AI);
229 Instruction *visitFreeInst(FreeInst &FI);
230 Instruction *visitLoadInst(LoadInst &LI);
231 Instruction *visitStoreInst(StoreInst &SI);
232 Instruction *visitBranchInst(BranchInst &BI);
233 Instruction *visitSwitchInst(SwitchInst &SI);
234 Instruction *visitInsertElementInst(InsertElementInst &IE);
235 Instruction *visitExtractElementInst(ExtractElementInst &EI);
236 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000237 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238
239 // visitInstruction - Specify what to return for unhandled instructions...
240 Instruction *visitInstruction(Instruction &I) { return 0; }
241
242 private:
243 Instruction *visitCallSite(CallSite CS);
244 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000245 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000246 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
247 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000248 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249
250 public:
251 // InsertNewInstBefore - insert an instruction New before instruction Old
252 // in the program. Add the new instruction to the worklist.
253 //
254 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
255 assert(New && New->getParent() == 0 &&
256 "New instruction already inserted into a basic block!");
257 BasicBlock *BB = Old.getParent();
258 BB->getInstList().insert(&Old, New); // Insert inst
259 AddToWorkList(New);
260 return New;
261 }
262
263 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
264 /// This also adds the cast to the worklist. Finally, this returns the
265 /// cast.
266 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
267 Instruction &Pos) {
268 if (V->getType() == Ty) return V;
269
270 if (Constant *CV = dyn_cast<Constant>(V))
271 return ConstantExpr::getCast(opc, CV, Ty);
272
Gabor Greifa645dd32008-05-16 19:29:10 +0000273 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 AddToWorkList(C);
275 return C;
276 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000277
278 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
279 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
280 }
281
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282
283 // ReplaceInstUsesWith - This method is to be used when an instruction is
284 // found to be dead, replacable with another preexisting expression. Here
285 // we add all uses of I to the worklist, replace all uses of I with the new
286 // value, then return I, so that the inst combiner will know that I was
287 // modified.
288 //
289 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
290 AddUsersToWorkList(I); // Add all modified instrs to worklist
291 if (&I != V) {
292 I.replaceAllUsesWith(V);
293 return &I;
294 } else {
295 // If we are replacing the instruction with itself, this must be in a
296 // segment of unreachable code, so just clobber the instruction.
297 I.replaceAllUsesWith(UndefValue::get(I.getType()));
298 return &I;
299 }
300 }
301
302 // UpdateValueUsesWith - This method is to be used when an value is
303 // found to be replacable with another preexisting expression or was
304 // updated. Here we add all uses of I to the worklist, replace all uses of
305 // I with the new value (unless the instruction was just updated), then
306 // return true, so that the inst combiner will know that I was modified.
307 //
308 bool UpdateValueUsesWith(Value *Old, Value *New) {
309 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
310 if (Old != New)
311 Old->replaceAllUsesWith(New);
312 if (Instruction *I = dyn_cast<Instruction>(Old))
313 AddToWorkList(I);
314 if (Instruction *I = dyn_cast<Instruction>(New))
315 AddToWorkList(I);
316 return true;
317 }
318
319 // EraseInstFromFunction - When dealing with an instruction that has side
320 // effects or produces a void value, we can't rely on DCE to delete the
321 // instruction. Instead, visit methods should return the value returned by
322 // this function.
323 Instruction *EraseInstFromFunction(Instruction &I) {
324 assert(I.use_empty() && "Cannot erase instruction that is used!");
325 AddUsesToWorkList(I);
326 RemoveFromWorkList(&I);
327 I.eraseFromParent();
328 return 0; // Don't do anything with FI
329 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000330
331 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
332 APInt &KnownOne, unsigned Depth = 0) const {
333 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
334 }
335
336 bool MaskedValueIsZero(Value *V, const APInt &Mask,
337 unsigned Depth = 0) const {
338 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
339 }
340 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
341 return llvm::ComputeNumSignBits(Op, TD, Depth);
342 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343
344 private:
345 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
346 /// InsertBefore instruction. This is specialized a bit to avoid inserting
347 /// casts that are known to not do anything...
348 ///
349 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
350 Value *V, const Type *DestTy,
351 Instruction *InsertBefore);
352
353 /// SimplifyCommutative - This performs a few simplifications for
354 /// commutative operators.
355 bool SimplifyCommutative(BinaryOperator &I);
356
357 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
358 /// most-complex to least-complex order.
359 bool SimplifyCompare(CmpInst &I);
360
361 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
362 /// on the demanded bits.
363 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
364 APInt& KnownZero, APInt& KnownOne,
365 unsigned Depth = 0);
366
367 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
368 uint64_t &UndefElts, unsigned Depth = 0);
369
370 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
371 // PHI node as operand #0, see if we can fold the instruction into the PHI
372 // (which is only possible if all operands to the PHI are constants).
373 Instruction *FoldOpIntoPhi(Instruction &I);
374
375 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
376 // operator and they all are only used by the PHI, PHI together their
377 // inputs, and do the operation once, to the result of the PHI.
378 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
379 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
380
381
382 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383 ConstantInt *AndRHS, BinaryOperator &TheAnd);
384
385 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
386 bool isSub, Instruction &I);
387 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
388 bool isSigned, bool Inside, Instruction &IB);
389 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
390 Instruction *MatchBSwap(BinaryOperator &I);
391 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000392 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000393 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000394
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395
396 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000397
Dan Gohman2d648bb2008-04-10 18:43:06 +0000398 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
399 unsigned CastOpc,
400 int &NumCastsRemoved);
401 unsigned GetOrEnforceKnownAlignment(Value *V,
402 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000403
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405}
406
Dan Gohman089efff2008-05-13 00:00:25 +0000407char InstCombiner::ID = 0;
408static RegisterPass<InstCombiner>
409X("instcombine", "Combine redundant instructions");
410
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411// getComplexity: Assign a complexity or rank value to LLVM Values...
412// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
413static unsigned getComplexity(Value *V) {
414 if (isa<Instruction>(V)) {
415 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
416 return 3;
417 return 4;
418 }
419 if (isa<Argument>(V)) return 3;
420 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
421}
422
423// isOnlyUse - Return true if this instruction will be deleted if we stop using
424// it.
425static bool isOnlyUse(Value *V) {
426 return V->hasOneUse() || isa<Constant>(V);
427}
428
429// getPromotedType - Return the specified type promoted as it would be to pass
430// though a va_arg area...
431static const Type *getPromotedType(const Type *Ty) {
432 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433 if (ITy->getBitWidth() < 32)
434 return Type::Int32Ty;
435 }
436 return Ty;
437}
438
439/// getBitCastOperand - If the specified operand is a CastInst or a constant
440/// expression bitcast, return the operand value, otherwise return null.
441static Value *getBitCastOperand(Value *V) {
442 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
443 return I->getOperand(0);
444 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
445 if (CE->getOpcode() == Instruction::BitCast)
446 return CE->getOperand(0);
447 return 0;
448}
449
450/// This function is a wrapper around CastInst::isEliminableCastPair. It
451/// simply extracts arguments and returns what that function returns.
452static Instruction::CastOps
453isEliminableCastPair(
454 const CastInst *CI, ///< The first cast instruction
455 unsigned opcode, ///< The opcode of the second cast instruction
456 const Type *DstTy, ///< The target type for the second cast instruction
457 TargetData *TD ///< The target data for pointer size
458) {
459
460 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
461 const Type *MidTy = CI->getType(); // B from above
462
463 // Get the opcodes of the two Cast instructions
464 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
465 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
466
467 return Instruction::CastOps(
468 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
469 DstTy, TD->getIntPtrType()));
470}
471
472/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
473/// in any code being generated. It does not require codegen if V is simple
474/// enough or if the cast can be folded into other casts.
475static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
476 const Type *Ty, TargetData *TD) {
477 if (V->getType() == Ty || isa<Constant>(V)) return false;
478
479 // If this is another cast that can be eliminated, it isn't codegen either.
480 if (const CastInst *CI = dyn_cast<CastInst>(V))
481 if (isEliminableCastPair(CI, opcode, Ty, TD))
482 return false;
483 return true;
484}
485
486/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
487/// InsertBefore instruction. This is specialized a bit to avoid inserting
488/// casts that are known to not do anything...
489///
490Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
491 Value *V, const Type *DestTy,
492 Instruction *InsertBefore) {
493 if (V->getType() == DestTy) return V;
494 if (Constant *C = dyn_cast<Constant>(V))
495 return ConstantExpr::getCast(opcode, C, DestTy);
496
497 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
498}
499
500// SimplifyCommutative - This performs a few simplifications for commutative
501// operators:
502//
503// 1. Order operands such that they are listed from right (least complex) to
504// left (most complex). This puts constants before unary operators before
505// binary operators.
506//
507// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
508// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
509//
510bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
511 bool Changed = false;
512 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
513 Changed = !I.swapOperands();
514
515 if (!I.isAssociative()) return Changed;
516 Instruction::BinaryOps Opcode = I.getOpcode();
517 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
518 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
519 if (isa<Constant>(I.getOperand(1))) {
520 Constant *Folded = ConstantExpr::get(I.getOpcode(),
521 cast<Constant>(I.getOperand(1)),
522 cast<Constant>(Op->getOperand(1)));
523 I.setOperand(0, Op->getOperand(0));
524 I.setOperand(1, Folded);
525 return true;
526 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
527 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
528 isOnlyUse(Op) && isOnlyUse(Op1)) {
529 Constant *C1 = cast<Constant>(Op->getOperand(1));
530 Constant *C2 = cast<Constant>(Op1->getOperand(1));
531
532 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
533 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000534 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 Op1->getOperand(0),
536 Op1->getName(), &I);
537 AddToWorkList(New);
538 I.setOperand(0, New);
539 I.setOperand(1, Folded);
540 return true;
541 }
542 }
543 return Changed;
544}
545
546/// SimplifyCompare - For a CmpInst this function just orders the operands
547/// so that theyare listed from right (least complex) to left (most complex).
548/// This puts constants before unary operators before binary operators.
549bool InstCombiner::SimplifyCompare(CmpInst &I) {
550 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
551 return false;
552 I.swapOperands();
553 // Compare instructions are not associative so there's nothing else we can do.
554 return true;
555}
556
557// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
558// if the LHS is a constant zero (which is the 'negate' form).
559//
560static inline Value *dyn_castNegVal(Value *V) {
561 if (BinaryOperator::isNeg(V))
562 return BinaryOperator::getNegArgument(V);
563
564 // Constants can be considered to be negated values if they can be folded.
565 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
566 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000567
568 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
569 if (C->getType()->getElementType()->isInteger())
570 return ConstantExpr::getNeg(C);
571
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572 return 0;
573}
574
575static inline Value *dyn_castNotVal(Value *V) {
576 if (BinaryOperator::isNot(V))
577 return BinaryOperator::getNotArgument(V);
578
579 // Constants can be considered to be not'ed values...
580 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
581 return ConstantInt::get(~C->getValue());
582 return 0;
583}
584
585// dyn_castFoldableMul - If this value is a multiply that can be folded into
586// other computations (because it has a constant operand), return the
587// non-constant operand of the multiply, and set CST to point to the multiplier.
588// Otherwise, return null.
589//
590static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
591 if (V->hasOneUse() && V->getType()->isInteger())
592 if (Instruction *I = dyn_cast<Instruction>(V)) {
593 if (I->getOpcode() == Instruction::Mul)
594 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
595 return I->getOperand(0);
596 if (I->getOpcode() == Instruction::Shl)
597 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
598 // The multiplier is really 1 << CST.
599 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
600 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
601 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
602 return I->getOperand(0);
603 }
604 }
605 return 0;
606}
607
608/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
609/// expression, return it.
610static User *dyn_castGetElementPtr(Value *V) {
611 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
612 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
613 if (CE->getOpcode() == Instruction::GetElementPtr)
614 return cast<User>(V);
615 return false;
616}
617
Dan Gohman2d648bb2008-04-10 18:43:06 +0000618/// getOpcode - If this is an Instruction or a ConstantExpr, return the
619/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000620static unsigned getOpcode(const Value *V) {
621 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000622 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000623 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000624 return CE->getOpcode();
625 // Use UserOp1 to mean there's no opcode.
626 return Instruction::UserOp1;
627}
628
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629/// AddOne - Add one to a ConstantInt
630static ConstantInt *AddOne(ConstantInt *C) {
631 APInt Val(C->getValue());
632 return ConstantInt::get(++Val);
633}
634/// SubOne - Subtract one from a ConstantInt
635static ConstantInt *SubOne(ConstantInt *C) {
636 APInt Val(C->getValue());
637 return ConstantInt::get(--Val);
638}
639/// Add - Add two ConstantInts together
640static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
641 return ConstantInt::get(C1->getValue() + C2->getValue());
642}
643/// And - Bitwise AND two ConstantInts together
644static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() & C2->getValue());
646}
647/// Subtract - Subtract one ConstantInt from another
648static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() - C2->getValue());
650}
651/// Multiply - Multiply two ConstantInts together
652static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
653 return ConstantInt::get(C1->getValue() * C2->getValue());
654}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000655/// MultiplyOverflows - True if the multiply can not be expressed in an int
656/// this size.
657static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
658 uint32_t W = C1->getBitWidth();
659 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
660 if (sign) {
661 LHSExt.sext(W * 2);
662 RHSExt.sext(W * 2);
663 } else {
664 LHSExt.zext(W * 2);
665 RHSExt.zext(W * 2);
666 }
667
668 APInt MulExt = LHSExt * RHSExt;
669
670 if (sign) {
671 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
672 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
673 return MulExt.slt(Min) || MulExt.sgt(Max);
674 } else
675 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
676}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678
679/// ShrinkDemandedConstant - Check to see if the specified operand of the
680/// specified instruction is a constant integer. If so, check to see if there
681/// are any bits set in the constant that are not demanded. If so, shrink the
682/// constant and return true.
683static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
684 APInt Demanded) {
685 assert(I && "No instruction?");
686 assert(OpNo < I->getNumOperands() && "Operand index too large");
687
688 // If the operand is not a constant integer, nothing to do.
689 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
690 if (!OpC) return false;
691
692 // If there are no bits set that aren't demanded, nothing to do.
693 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
694 if ((~Demanded & OpC->getValue()) == 0)
695 return false;
696
697 // This instruction is producing bits that are not demanded. Shrink the RHS.
698 Demanded &= OpC->getValue();
699 I->setOperand(OpNo, ConstantInt::get(Demanded));
700 return true;
701}
702
703// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
704// set of known zero and one bits, compute the maximum and minimum values that
705// could have the specified known zero and known one bits, returning them in
706// min/max.
707static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
708 const APInt& KnownZero,
709 const APInt& KnownOne,
710 APInt& Min, APInt& Max) {
711 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
712 assert(KnownZero.getBitWidth() == BitWidth &&
713 KnownOne.getBitWidth() == BitWidth &&
714 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
715 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
716 APInt UnknownBits = ~(KnownZero|KnownOne);
717
718 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
719 // bit if it is unknown.
720 Min = KnownOne;
721 Max = KnownOne|UnknownBits;
722
723 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
724 Min.set(BitWidth-1);
725 Max.clear(BitWidth-1);
726 }
727}
728
729// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
730// a set of known zero and one bits, compute the maximum and minimum values that
731// could have the specified known zero and known one bits, returning them in
732// min/max.
733static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000734 const APInt &KnownZero,
735 const APInt &KnownOne,
736 APInt &Min, APInt &Max) {
737 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 assert(KnownZero.getBitWidth() == BitWidth &&
739 KnownOne.getBitWidth() == BitWidth &&
740 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
741 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
742 APInt UnknownBits = ~(KnownZero|KnownOne);
743
744 // The minimum value is when the unknown bits are all zeros.
745 Min = KnownOne;
746 // The maximum value is when the unknown bits are all ones.
747 Max = KnownOne|UnknownBits;
748}
749
750/// SimplifyDemandedBits - This function attempts to replace V with a simpler
751/// value based on the demanded bits. When this function is called, it is known
752/// that only the bits set in DemandedMask of the result of V are ever used
753/// downstream. Consequently, depending on the mask and V, it may be possible
754/// to replace V with a constant or one of its operands. In such cases, this
755/// function does the replacement and returns true. In all other cases, it
756/// returns false after analyzing the expression and setting KnownOne and known
757/// to be one in the expression. KnownZero contains all the bits that are known
758/// to be zero in the expression. These are provided to potentially allow the
759/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
760/// the expression. KnownOne and KnownZero always follow the invariant that
761/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
762/// the bits in KnownOne and KnownZero may only be accurate for those bits set
763/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
764/// and KnownOne must all be the same.
765bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
766 APInt& KnownZero, APInt& KnownOne,
767 unsigned Depth) {
768 assert(V != 0 && "Null pointer of Value???");
769 assert(Depth <= 6 && "Limit Search Depth");
770 uint32_t BitWidth = DemandedMask.getBitWidth();
771 const IntegerType *VTy = cast<IntegerType>(V->getType());
772 assert(VTy->getBitWidth() == BitWidth &&
773 KnownZero.getBitWidth() == BitWidth &&
774 KnownOne.getBitWidth() == BitWidth &&
775 "Value *V, DemandedMask, KnownZero and KnownOne \
776 must have same BitWidth");
777 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
778 // We know all of the bits for a constant!
779 KnownOne = CI->getValue() & DemandedMask;
780 KnownZero = ~KnownOne & DemandedMask;
781 return false;
782 }
783
784 KnownZero.clear();
785 KnownOne.clear();
786 if (!V->hasOneUse()) { // Other users may use these bits.
787 if (Depth != 0) { // Not at the root.
788 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
789 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
790 return false;
791 }
792 // If this is the root being simplified, allow it to have multiple uses,
793 // just set the DemandedMask to all bits.
794 DemandedMask = APInt::getAllOnesValue(BitWidth);
795 } else if (DemandedMask == 0) { // Not demanding any bits from V.
796 if (V != UndefValue::get(VTy))
797 return UpdateValueUsesWith(V, UndefValue::get(VTy));
798 return false;
799 } else if (Depth == 6) { // Limit search depth.
800 return false;
801 }
802
803 Instruction *I = dyn_cast<Instruction>(V);
804 if (!I) return false; // Only analyze instructions.
805
806 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
807 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
808 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000809 default:
810 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
811 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 case Instruction::And:
813 // If either the LHS or the RHS are Zero, the result is zero.
814 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
815 RHSKnownZero, RHSKnownOne, Depth+1))
816 return true;
817 assert((RHSKnownZero & RHSKnownOne) == 0 &&
818 "Bits known to be one AND zero?");
819
820 // If something is known zero on the RHS, the bits aren't demanded on the
821 // LHS.
822 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
823 LHSKnownZero, LHSKnownOne, Depth+1))
824 return true;
825 assert((LHSKnownZero & LHSKnownOne) == 0 &&
826 "Bits known to be one AND zero?");
827
828 // If all of the demanded bits are known 1 on one side, return the other.
829 // These bits cannot contribute to the result of the 'and'.
830 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
831 (DemandedMask & ~LHSKnownZero))
832 return UpdateValueUsesWith(I, I->getOperand(0));
833 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
834 (DemandedMask & ~RHSKnownZero))
835 return UpdateValueUsesWith(I, I->getOperand(1));
836
837 // If all of the demanded bits in the inputs are known zeros, return zero.
838 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
839 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
840
841 // If the RHS is a constant, see if we can simplify it.
842 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
843 return UpdateValueUsesWith(I, I);
844
845 // Output known-1 bits are only known if set in both the LHS & RHS.
846 RHSKnownOne &= LHSKnownOne;
847 // Output known-0 are known to be clear if zero in either the LHS | RHS.
848 RHSKnownZero |= LHSKnownZero;
849 break;
850 case Instruction::Or:
851 // If either the LHS or the RHS are One, the result is One.
852 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
853 RHSKnownZero, RHSKnownOne, Depth+1))
854 return true;
855 assert((RHSKnownZero & RHSKnownOne) == 0 &&
856 "Bits known to be one AND zero?");
857 // If something is known one on the RHS, the bits aren't demanded on the
858 // LHS.
859 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
860 LHSKnownZero, LHSKnownOne, Depth+1))
861 return true;
862 assert((LHSKnownZero & LHSKnownOne) == 0 &&
863 "Bits known to be one AND zero?");
864
865 // If all of the demanded bits are known zero on one side, return the other.
866 // These bits cannot contribute to the result of the 'or'.
867 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
868 (DemandedMask & ~LHSKnownOne))
869 return UpdateValueUsesWith(I, I->getOperand(0));
870 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
871 (DemandedMask & ~RHSKnownOne))
872 return UpdateValueUsesWith(I, I->getOperand(1));
873
874 // If all of the potentially set bits on one side are known to be set on
875 // the other side, just use the 'other' side.
876 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
877 (DemandedMask & (~RHSKnownZero)))
878 return UpdateValueUsesWith(I, I->getOperand(0));
879 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
880 (DemandedMask & (~LHSKnownZero)))
881 return UpdateValueUsesWith(I, I->getOperand(1));
882
883 // If the RHS is a constant, see if we can simplify it.
884 if (ShrinkDemandedConstant(I, 1, DemandedMask))
885 return UpdateValueUsesWith(I, I);
886
887 // Output known-0 bits are only known if clear in both the LHS & RHS.
888 RHSKnownZero &= LHSKnownZero;
889 // Output known-1 are known to be set if set in either the LHS | RHS.
890 RHSKnownOne |= LHSKnownOne;
891 break;
892 case Instruction::Xor: {
893 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
894 RHSKnownZero, RHSKnownOne, Depth+1))
895 return true;
896 assert((RHSKnownZero & RHSKnownOne) == 0 &&
897 "Bits known to be one AND zero?");
898 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
899 LHSKnownZero, LHSKnownOne, Depth+1))
900 return true;
901 assert((LHSKnownZero & LHSKnownOne) == 0 &&
902 "Bits known to be one AND zero?");
903
904 // If all of the demanded bits are known zero on one side, return the other.
905 // These bits cannot contribute to the result of the 'xor'.
906 if ((DemandedMask & RHSKnownZero) == DemandedMask)
907 return UpdateValueUsesWith(I, I->getOperand(0));
908 if ((DemandedMask & LHSKnownZero) == DemandedMask)
909 return UpdateValueUsesWith(I, I->getOperand(1));
910
911 // Output known-0 bits are known if clear or set in both the LHS & RHS.
912 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
913 (RHSKnownOne & LHSKnownOne);
914 // Output known-1 are known to be set if set in only one of the LHS, RHS.
915 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
916 (RHSKnownOne & LHSKnownZero);
917
918 // If all of the demanded bits are known to be zero on one side or the
919 // other, turn this into an *inclusive* or.
920 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
921 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
922 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +0000923 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 I->getName());
925 InsertNewInstBefore(Or, *I);
926 return UpdateValueUsesWith(I, Or);
927 }
928
929 // If all of the demanded bits on one side are known, and all of the set
930 // bits on that side are also known to be set on the other side, turn this
931 // into an AND, as we know the bits will be cleared.
932 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
933 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
934 // all known
935 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
936 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
937 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +0000938 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 InsertNewInstBefore(And, *I);
940 return UpdateValueUsesWith(I, And);
941 }
942 }
943
944 // If the RHS is a constant, see if we can simplify it.
945 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
946 if (ShrinkDemandedConstant(I, 1, DemandedMask))
947 return UpdateValueUsesWith(I, I);
948
949 RHSKnownZero = KnownZeroOut;
950 RHSKnownOne = KnownOneOut;
951 break;
952 }
953 case Instruction::Select:
954 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
955 RHSKnownZero, RHSKnownOne, Depth+1))
956 return true;
957 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
958 LHSKnownZero, LHSKnownOne, Depth+1))
959 return true;
960 assert((RHSKnownZero & RHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
962 assert((LHSKnownZero & LHSKnownOne) == 0 &&
963 "Bits known to be one AND zero?");
964
965 // If the operands are constants, see if we can simplify them.
966 if (ShrinkDemandedConstant(I, 1, DemandedMask))
967 return UpdateValueUsesWith(I, I);
968 if (ShrinkDemandedConstant(I, 2, DemandedMask))
969 return UpdateValueUsesWith(I, I);
970
971 // Only known if known in both the LHS and RHS.
972 RHSKnownOne &= LHSKnownOne;
973 RHSKnownZero &= LHSKnownZero;
974 break;
975 case Instruction::Trunc: {
976 uint32_t truncBf =
977 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
978 DemandedMask.zext(truncBf);
979 RHSKnownZero.zext(truncBf);
980 RHSKnownOne.zext(truncBf);
981 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
982 RHSKnownZero, RHSKnownOne, Depth+1))
983 return true;
984 DemandedMask.trunc(BitWidth);
985 RHSKnownZero.trunc(BitWidth);
986 RHSKnownOne.trunc(BitWidth);
987 assert((RHSKnownZero & RHSKnownOne) == 0 &&
988 "Bits known to be one AND zero?");
989 break;
990 }
991 case Instruction::BitCast:
992 if (!I->getOperand(0)->getType()->isInteger())
993 return false;
994
995 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
996 RHSKnownZero, RHSKnownOne, Depth+1))
997 return true;
998 assert((RHSKnownZero & RHSKnownOne) == 0 &&
999 "Bits known to be one AND zero?");
1000 break;
1001 case Instruction::ZExt: {
1002 // Compute the bits in the result that are not present in the input.
1003 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1004 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1005
1006 DemandedMask.trunc(SrcBitWidth);
1007 RHSKnownZero.trunc(SrcBitWidth);
1008 RHSKnownOne.trunc(SrcBitWidth);
1009 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1010 RHSKnownZero, RHSKnownOne, Depth+1))
1011 return true;
1012 DemandedMask.zext(BitWidth);
1013 RHSKnownZero.zext(BitWidth);
1014 RHSKnownOne.zext(BitWidth);
1015 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1016 "Bits known to be one AND zero?");
1017 // The top bits are known to be zero.
1018 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1019 break;
1020 }
1021 case Instruction::SExt: {
1022 // Compute the bits in the result that are not present in the input.
1023 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1024 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1025
1026 APInt InputDemandedBits = DemandedMask &
1027 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1028
1029 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1030 // If any of the sign extended bits are demanded, we know that the sign
1031 // bit is demanded.
1032 if ((NewBits & DemandedMask) != 0)
1033 InputDemandedBits.set(SrcBitWidth-1);
1034
1035 InputDemandedBits.trunc(SrcBitWidth);
1036 RHSKnownZero.trunc(SrcBitWidth);
1037 RHSKnownOne.trunc(SrcBitWidth);
1038 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1039 RHSKnownZero, RHSKnownOne, Depth+1))
1040 return true;
1041 InputDemandedBits.zext(BitWidth);
1042 RHSKnownZero.zext(BitWidth);
1043 RHSKnownOne.zext(BitWidth);
1044 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1045 "Bits known to be one AND zero?");
1046
1047 // If the sign bit of the input is known set or clear, then we know the
1048 // top bits of the result.
1049
1050 // If the input sign bit is known zero, or if the NewBits are not demanded
1051 // convert this into a zero extension.
1052 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1053 {
1054 // Convert to ZExt cast
1055 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1056 return UpdateValueUsesWith(I, NewCast);
1057 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1058 RHSKnownOne |= NewBits;
1059 }
1060 break;
1061 }
1062 case Instruction::Add: {
1063 // Figure out what the input bits are. If the top bits of the and result
1064 // are not demanded, then the add doesn't demand them from its input
1065 // either.
1066 uint32_t NLZ = DemandedMask.countLeadingZeros();
1067
1068 // If there is a constant on the RHS, there are a variety of xformations
1069 // we can do.
1070 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1071 // If null, this should be simplified elsewhere. Some of the xforms here
1072 // won't work if the RHS is zero.
1073 if (RHS->isZero())
1074 break;
1075
1076 // If the top bit of the output is demanded, demand everything from the
1077 // input. Otherwise, we demand all the input bits except NLZ top bits.
1078 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1079
1080 // Find information about known zero/one bits in the input.
1081 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1082 LHSKnownZero, LHSKnownOne, Depth+1))
1083 return true;
1084
1085 // If the RHS of the add has bits set that can't affect the input, reduce
1086 // the constant.
1087 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1088 return UpdateValueUsesWith(I, I);
1089
1090 // Avoid excess work.
1091 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1092 break;
1093
1094 // Turn it into OR if input bits are zero.
1095 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1096 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001097 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 I->getName());
1099 InsertNewInstBefore(Or, *I);
1100 return UpdateValueUsesWith(I, Or);
1101 }
1102
1103 // We can say something about the output known-zero and known-one bits,
1104 // depending on potential carries from the input constant and the
1105 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1106 // bits set and the RHS constant is 0x01001, then we know we have a known
1107 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1108
1109 // To compute this, we first compute the potential carry bits. These are
1110 // the bits which may be modified. I'm not aware of a better way to do
1111 // this scan.
1112 const APInt& RHSVal = RHS->getValue();
1113 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1114
1115 // Now that we know which bits have carries, compute the known-1/0 sets.
1116
1117 // Bits are known one if they are known zero in one operand and one in the
1118 // other, and there is no input carry.
1119 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1120 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1121
1122 // Bits are known zero if they are known zero in both operands and there
1123 // is no input carry.
1124 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1125 } else {
1126 // If the high-bits of this ADD are not demanded, then it does not demand
1127 // the high bits of its LHS or RHS.
1128 if (DemandedMask[BitWidth-1] == 0) {
1129 // Right fill the mask of bits for this ADD to demand the most
1130 // significant bit and all those below it.
1131 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1132 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1133 LHSKnownZero, LHSKnownOne, Depth+1))
1134 return true;
1135 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1136 LHSKnownZero, LHSKnownOne, Depth+1))
1137 return true;
1138 }
1139 }
1140 break;
1141 }
1142 case Instruction::Sub:
1143 // If the high-bits of this SUB are not demanded, then it does not demand
1144 // the high bits of its LHS or RHS.
1145 if (DemandedMask[BitWidth-1] == 0) {
1146 // Right fill the mask of bits for this SUB to demand the most
1147 // significant bit and all those below it.
1148 uint32_t NLZ = DemandedMask.countLeadingZeros();
1149 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1150 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1151 LHSKnownZero, LHSKnownOne, Depth+1))
1152 return true;
1153 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1154 LHSKnownZero, LHSKnownOne, Depth+1))
1155 return true;
1156 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001157 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1158 // the known zeros and ones.
1159 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 break;
1161 case Instruction::Shl:
1162 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1164 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1165 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1166 RHSKnownZero, RHSKnownOne, Depth+1))
1167 return true;
1168 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1169 "Bits known to be one AND zero?");
1170 RHSKnownZero <<= ShiftAmt;
1171 RHSKnownOne <<= ShiftAmt;
1172 // low bits known zero.
1173 if (ShiftAmt)
1174 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1175 }
1176 break;
1177 case Instruction::LShr:
1178 // For a logical shift right
1179 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1180 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1181
1182 // Unsigned shift right.
1183 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1184 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1185 RHSKnownZero, RHSKnownOne, Depth+1))
1186 return true;
1187 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1188 "Bits known to be one AND zero?");
1189 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1190 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1191 if (ShiftAmt) {
1192 // Compute the new bits that are at the top now.
1193 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1194 RHSKnownZero |= HighBits; // high bits known zero.
1195 }
1196 }
1197 break;
1198 case Instruction::AShr:
1199 // If this is an arithmetic shift right and only the low-bit is set, we can
1200 // always convert this into a logical shr, even if the shift amount is
1201 // variable. The low bit of the shift cannot be an input sign bit unless
1202 // the shift amount is >= the size of the datatype, which is undefined.
1203 if (DemandedMask == 1) {
1204 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001205 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206 I->getOperand(0), I->getOperand(1), I->getName());
1207 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1208 return UpdateValueUsesWith(I, NewVal);
1209 }
1210
1211 // If the sign bit is the only bit demanded by this ashr, then there is no
1212 // need to do it, the shift doesn't change the high bit.
1213 if (DemandedMask.isSignBit())
1214 return UpdateValueUsesWith(I, I->getOperand(0));
1215
1216 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1217 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1218
1219 // Signed shift right.
1220 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1221 // If any of the "high bits" are demanded, we should set the sign bit as
1222 // demanded.
1223 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1224 DemandedMaskIn.set(BitWidth-1);
1225 if (SimplifyDemandedBits(I->getOperand(0),
1226 DemandedMaskIn,
1227 RHSKnownZero, RHSKnownOne, Depth+1))
1228 return true;
1229 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1230 "Bits known to be one AND zero?");
1231 // Compute the new bits that are at the top now.
1232 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1233 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1234 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1235
1236 // Handle the sign bits.
1237 APInt SignBit(APInt::getSignBit(BitWidth));
1238 // Adjust to where it is now in the mask.
1239 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1240
1241 // If the input sign bit is known to be zero, or if none of the top bits
1242 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001243 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 (HighBits & ~DemandedMask) == HighBits) {
1245 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001246 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 I->getOperand(0), SA, I->getName());
1248 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1249 return UpdateValueUsesWith(I, NewVal);
1250 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1251 RHSKnownOne |= HighBits;
1252 }
1253 }
1254 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001255 case Instruction::SRem:
1256 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257 APInt RA = Rem->getValue();
1258 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Nick Lewycky245de422008-07-12 05:04:38 +00001259 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1260 return UpdateValueUsesWith(I, I->getOperand(0));
1261
Dan Gohman5a154a12008-05-06 00:51:48 +00001262 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001263 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1264 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1265 LHSKnownZero, LHSKnownOne, Depth+1))
1266 return true;
1267
1268 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1269 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001270
1271 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001272
1273 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1274 }
1275 }
1276 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001277 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001278 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1279 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001280 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1281 KnownZero2, KnownOne2, Depth+1))
1282 return true;
1283
Dan Gohmanbec16052008-04-28 17:02:21 +00001284 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001285 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001286 KnownZero2, KnownOne2, Depth+1))
1287 return true;
1288
1289 Leaders = std::max(Leaders,
1290 KnownZero2.countLeadingOnes());
1291 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001292 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 }
Chris Lattner989ba312008-06-18 04:33:20 +00001294 case Instruction::Call:
1295 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1296 switch (II->getIntrinsicID()) {
1297 default: break;
1298 case Intrinsic::bswap: {
1299 // If the only bits demanded come from one byte of the bswap result,
1300 // just shift the input byte into position to eliminate the bswap.
1301 unsigned NLZ = DemandedMask.countLeadingZeros();
1302 unsigned NTZ = DemandedMask.countTrailingZeros();
1303
1304 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1305 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1306 // have 14 leading zeros, round to 8.
1307 NLZ &= ~7;
1308 NTZ &= ~7;
1309 // If we need exactly one byte, we can do this transformation.
1310 if (BitWidth-NLZ-NTZ == 8) {
1311 unsigned ResultBit = NTZ;
1312 unsigned InputBit = BitWidth-NTZ-8;
1313
1314 // Replace this with either a left or right shift to get the byte into
1315 // the right place.
1316 Instruction *NewVal;
1317 if (InputBit > ResultBit)
1318 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1319 ConstantInt::get(I->getType(), InputBit-ResultBit));
1320 else
1321 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1322 ConstantInt::get(I->getType(), ResultBit-InputBit));
1323 NewVal->takeName(I);
1324 InsertNewInstBefore(NewVal, *I);
1325 return UpdateValueUsesWith(I, NewVal);
1326 }
1327
1328 // TODO: Could compute known zero/one bits based on the input.
1329 break;
1330 }
1331 }
1332 }
Chris Lattner4946e222008-06-18 18:11:55 +00001333 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001334 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001335 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336
1337 // If the client is only demanding bits that we know, return the known
1338 // constant.
1339 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1340 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1341 return false;
1342}
1343
1344
1345/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1346/// 64 or fewer elements. DemandedElts contains the set of elements that are
1347/// actually used by the caller. This method analyzes which elements of the
1348/// operand are undef and returns that information in UndefElts.
1349///
1350/// If the information about demanded elements can be used to simplify the
1351/// operation, the operation is simplified, then the resultant value is
1352/// returned. This returns null if no change was made.
1353Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1354 uint64_t &UndefElts,
1355 unsigned Depth) {
1356 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1357 assert(VWidth <= 64 && "Vector too wide to analyze!");
1358 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001359 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360
1361 if (isa<UndefValue>(V)) {
1362 // If the entire vector is undefined, just return this info.
1363 UndefElts = EltMask;
1364 return 0;
1365 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1366 UndefElts = EltMask;
1367 return UndefValue::get(V->getType());
1368 }
1369
1370 UndefElts = 0;
1371 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1372 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1373 Constant *Undef = UndefValue::get(EltTy);
1374
1375 std::vector<Constant*> Elts;
1376 for (unsigned i = 0; i != VWidth; ++i)
1377 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1378 Elts.push_back(Undef);
1379 UndefElts |= (1ULL << i);
1380 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else { // Otherwise, defined.
1384 Elts.push_back(CP->getOperand(i));
1385 }
1386
1387 // If we changed the constant, return it.
1388 Constant *NewCP = ConstantVector::get(Elts);
1389 return NewCP != CP ? NewCP : 0;
1390 } else if (isa<ConstantAggregateZero>(V)) {
1391 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1392 // set to undef.
1393 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1394 Constant *Zero = Constant::getNullValue(EltTy);
1395 Constant *Undef = UndefValue::get(EltTy);
1396 std::vector<Constant*> Elts;
1397 for (unsigned i = 0; i != VWidth; ++i)
1398 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1399 UndefElts = DemandedElts ^ EltMask;
1400 return ConstantVector::get(Elts);
1401 }
1402
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001403 // Limit search depth.
1404 if (Depth == 10)
1405 return false;
1406
1407 // If multiple users are using the root value, procede with
1408 // simplification conservatively assuming that all elements
1409 // are needed.
1410 if (!V->hasOneUse()) {
1411 // Quit if we find multiple users of a non-root value though.
1412 // They'll be handled when it's their turn to be visited by
1413 // the main instcombine process.
1414 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 // TODO: Just compute the UndefElts information recursively.
1416 return false;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001417
1418 // Conservatively assume that all elements are needed.
1419 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 }
1421
1422 Instruction *I = dyn_cast<Instruction>(V);
1423 if (!I) return false; // Only analyze instructions.
1424
1425 bool MadeChange = false;
1426 uint64_t UndefElts2;
1427 Value *TmpV;
1428 switch (I->getOpcode()) {
1429 default: break;
1430
1431 case Instruction::InsertElement: {
1432 // If this is a variable index, we don't know which element it overwrites.
1433 // demand exactly the same input as we produce.
1434 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1435 if (Idx == 0) {
1436 // Note that we can't propagate undef elt info, because we don't know
1437 // which elt is getting updated.
1438 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1439 UndefElts2, Depth+1);
1440 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1441 break;
1442 }
1443
1444 // If this is inserting an element that isn't demanded, remove this
1445 // insertelement.
1446 unsigned IdxNo = Idx->getZExtValue();
1447 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1448 return AddSoonDeadInstToWorklist(*I, 0);
1449
1450 // Otherwise, the element inserted overwrites whatever was there, so the
1451 // input demanded set is simpler than the output set.
1452 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1453 DemandedElts & ~(1ULL << IdxNo),
1454 UndefElts, Depth+1);
1455 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1456
1457 // The inserted element is defined.
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001458 UndefElts &= ~(1ULL << IdxNo);
1459 break;
1460 }
1461 case Instruction::ShuffleVector: {
1462 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1463 uint64_t LeftDemanded = 0, RightDemanded = 0;
1464 for (unsigned i = 0; i < VWidth; i++) {
1465 if (DemandedElts & (1ULL << i)) {
1466 unsigned MaskVal = Shuffle->getMaskValue(i);
1467 if (MaskVal != -1u) {
1468 assert(MaskVal < VWidth * 2 &&
1469 "shufflevector mask index out of range!");
1470 if (MaskVal < VWidth)
1471 LeftDemanded |= 1ULL << MaskVal;
1472 else
1473 RightDemanded |= 1ULL << (MaskVal - VWidth);
1474 }
1475 }
1476 }
1477
1478 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1479 UndefElts2, Depth+1);
1480 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1481
1482 uint64_t UndefElts3;
1483 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1484 UndefElts3, Depth+1);
1485 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1486
1487 bool NewUndefElts = false;
1488 for (unsigned i = 0; i < VWidth; i++) {
1489 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001490 if (MaskVal == -1u) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001491 uint64_t NewBit = 1ULL << i;
1492 UndefElts |= NewBit;
1493 } else if (MaskVal < VWidth) {
1494 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1495 NewUndefElts |= NewBit;
1496 UndefElts |= NewBit;
1497 } else {
1498 uint64_t NewBit = ((UndefElts3 >> (MaskVal - VWidth)) & 1) << i;
1499 NewUndefElts |= NewBit;
1500 UndefElts |= NewBit;
1501 }
1502 }
1503
1504 if (NewUndefElts) {
1505 // Add additional discovered undefs.
1506 std::vector<Constant*> Elts;
1507 for (unsigned i = 0; i < VWidth; ++i) {
1508 if (UndefElts & (1ULL << i))
1509 Elts.push_back(UndefValue::get(Type::Int32Ty));
1510 else
1511 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1512 Shuffle->getMaskValue(i)));
1513 }
1514 I->setOperand(2, ConstantVector::get(Elts));
1515 MadeChange = true;
1516 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 break;
1518 }
1519 case Instruction::BitCast: {
1520 // Vector->vector casts only.
1521 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1522 if (!VTy) break;
1523 unsigned InVWidth = VTy->getNumElements();
1524 uint64_t InputDemandedElts = 0;
1525 unsigned Ratio;
1526
1527 if (VWidth == InVWidth) {
1528 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1529 // elements as are demanded of us.
1530 Ratio = 1;
1531 InputDemandedElts = DemandedElts;
1532 } else if (VWidth > InVWidth) {
1533 // Untested so far.
1534 break;
1535
1536 // If there are more elements in the result than there are in the source,
1537 // then an input element is live if any of the corresponding output
1538 // elements are live.
1539 Ratio = VWidth/InVWidth;
1540 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1541 if (DemandedElts & (1ULL << OutIdx))
1542 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1543 }
1544 } else {
1545 // Untested so far.
1546 break;
1547
1548 // If there are more elements in the source than there are in the result,
1549 // then an input element is live if the corresponding output element is
1550 // live.
1551 Ratio = InVWidth/VWidth;
1552 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1553 if (DemandedElts & (1ULL << InIdx/Ratio))
1554 InputDemandedElts |= 1ULL << InIdx;
1555 }
1556
1557 // div/rem demand all inputs, because they don't want divide by zero.
1558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1559 UndefElts2, Depth+1);
1560 if (TmpV) {
1561 I->setOperand(0, TmpV);
1562 MadeChange = true;
1563 }
1564
1565 UndefElts = UndefElts2;
1566 if (VWidth > InVWidth) {
1567 assert(0 && "Unimp");
1568 // If there are more elements in the result than there are in the source,
1569 // then an output element is undef if the corresponding input element is
1570 // undef.
1571 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1572 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1573 UndefElts |= 1ULL << OutIdx;
1574 } else if (VWidth < InVWidth) {
1575 assert(0 && "Unimp");
1576 // If there are more elements in the source than there are in the result,
1577 // then a result element is undef if all of the corresponding input
1578 // elements are undef.
1579 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1580 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1581 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1582 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1583 }
1584 break;
1585 }
1586 case Instruction::And:
1587 case Instruction::Or:
1588 case Instruction::Xor:
1589 case Instruction::Add:
1590 case Instruction::Sub:
1591 case Instruction::Mul:
1592 // div/rem demand all inputs, because they don't want divide by zero.
1593 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1594 UndefElts, Depth+1);
1595 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1596 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1597 UndefElts2, Depth+1);
1598 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1599
1600 // Output elements are undefined if both are undefined. Consider things
1601 // like undef&0. The result is known zero, not undef.
1602 UndefElts &= UndefElts2;
1603 break;
1604
1605 case Instruction::Call: {
1606 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1607 if (!II) break;
1608 switch (II->getIntrinsicID()) {
1609 default: break;
1610
1611 // Binary vector operations that work column-wise. A dest element is a
1612 // function of the corresponding input elements from the two inputs.
1613 case Intrinsic::x86_sse_sub_ss:
1614 case Intrinsic::x86_sse_mul_ss:
1615 case Intrinsic::x86_sse_min_ss:
1616 case Intrinsic::x86_sse_max_ss:
1617 case Intrinsic::x86_sse2_sub_sd:
1618 case Intrinsic::x86_sse2_mul_sd:
1619 case Intrinsic::x86_sse2_min_sd:
1620 case Intrinsic::x86_sse2_max_sd:
1621 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1622 UndefElts, Depth+1);
1623 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1624 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1625 UndefElts2, Depth+1);
1626 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1627
1628 // If only the low elt is demanded and this is a scalarizable intrinsic,
1629 // scalarize it now.
1630 if (DemandedElts == 1) {
1631 switch (II->getIntrinsicID()) {
1632 default: break;
1633 case Intrinsic::x86_sse_sub_ss:
1634 case Intrinsic::x86_sse_mul_ss:
1635 case Intrinsic::x86_sse2_sub_sd:
1636 case Intrinsic::x86_sse2_mul_sd:
1637 // TODO: Lower MIN/MAX/ABS/etc
1638 Value *LHS = II->getOperand(1);
1639 Value *RHS = II->getOperand(2);
1640 // Extract the element as scalars.
1641 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1642 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1643
1644 switch (II->getIntrinsicID()) {
1645 default: assert(0 && "Case stmts out of sync!");
1646 case Intrinsic::x86_sse_sub_ss:
1647 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001648 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 II->getName()), *II);
1650 break;
1651 case Intrinsic::x86_sse_mul_ss:
1652 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001653 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001654 II->getName()), *II);
1655 break;
1656 }
1657
1658 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001659 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1660 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001661 InsertNewInstBefore(New, *II);
1662 AddSoonDeadInstToWorklist(*II, 0);
1663 return New;
1664 }
1665 }
1666
1667 // Output elements are undefined if both are undefined. Consider things
1668 // like undef&0. The result is known zero, not undef.
1669 UndefElts &= UndefElts2;
1670 break;
1671 }
1672 break;
1673 }
1674 }
1675 return MadeChange ? I : 0;
1676}
1677
Dan Gohman5d56fd42008-05-19 22:14:15 +00001678
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679/// AssociativeOpt - Perform an optimization on an associative operator. This
1680/// function is designed to check a chain of associative operators for a
1681/// potential to apply a certain optimization. Since the optimization may be
1682/// applicable if the expression was reassociated, this checks the chain, then
1683/// reassociates the expression as necessary to expose the optimization
1684/// opportunity. This makes use of a special Functor, which must define
1685/// 'shouldApply' and 'apply' methods.
1686///
1687template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001688static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689 unsigned Opcode = Root.getOpcode();
1690 Value *LHS = Root.getOperand(0);
1691
1692 // Quick check, see if the immediate LHS matches...
1693 if (F.shouldApply(LHS))
1694 return F.apply(Root);
1695
1696 // Otherwise, if the LHS is not of the same opcode as the root, return.
1697 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1698 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1699 // Should we apply this transform to the RHS?
1700 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1701
1702 // If not to the RHS, check to see if we should apply to the LHS...
1703 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1704 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1705 ShouldApply = true;
1706 }
1707
1708 // If the functor wants to apply the optimization to the RHS of LHSI,
1709 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1710 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001711 // Now all of the instructions are in the current basic block, go ahead
1712 // and perform the reassociation.
1713 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1714
1715 // First move the selected RHS to the LHS of the root...
1716 Root.setOperand(0, LHSI->getOperand(1));
1717
1718 // Make what used to be the LHS of the root be the user of the root...
1719 Value *ExtraOperand = TmpLHSI->getOperand(1);
1720 if (&Root == TmpLHSI) {
1721 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1722 return 0;
1723 }
1724 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1725 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001726 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001727 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728 ARI = Root;
1729
1730 // Now propagate the ExtraOperand down the chain of instructions until we
1731 // get to LHSI.
1732 while (TmpLHSI != LHSI) {
1733 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1734 // Move the instruction to immediately before the chain we are
1735 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001736 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737 ARI = NextLHSI;
1738
1739 Value *NextOp = NextLHSI->getOperand(1);
1740 NextLHSI->setOperand(1, ExtraOperand);
1741 TmpLHSI = NextLHSI;
1742 ExtraOperand = NextOp;
1743 }
1744
1745 // Now that the instructions are reassociated, have the functor perform
1746 // the transformation...
1747 return F.apply(Root);
1748 }
1749
1750 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1751 }
1752 return 0;
1753}
1754
Dan Gohman089efff2008-05-13 00:00:25 +00001755namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001756
Nick Lewycky27f6c132008-05-23 04:34:58 +00001757// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758struct AddRHS {
1759 Value *RHS;
1760 AddRHS(Value *rhs) : RHS(rhs) {}
1761 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1762 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001763 return BinaryOperator::CreateShl(Add.getOperand(0),
1764 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765 }
1766};
1767
1768// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1769// iff C1&C2 == 0
1770struct AddMaskingAnd {
1771 Constant *C2;
1772 AddMaskingAnd(Constant *c) : C2(c) {}
1773 bool shouldApply(Value *LHS) const {
1774 ConstantInt *C1;
1775 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1776 ConstantExpr::getAnd(C1, C2)->isNullValue();
1777 }
1778 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001779 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001780 }
1781};
1782
Dan Gohman089efff2008-05-13 00:00:25 +00001783}
1784
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1786 InstCombiner *IC) {
1787 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1788 if (Constant *SOC = dyn_cast<Constant>(SO))
1789 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1790
Gabor Greifa645dd32008-05-16 19:29:10 +00001791 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001792 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1793 }
1794
1795 // Figure out if the constant is the left or the right argument.
1796 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1797 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1798
1799 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1800 if (ConstIsRHS)
1801 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1802 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1803 }
1804
1805 Value *Op0 = SO, *Op1 = ConstOperand;
1806 if (!ConstIsRHS)
1807 std::swap(Op0, Op1);
1808 Instruction *New;
1809 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001810 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001812 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813 SO->getName()+".cmp");
1814 else {
1815 assert(0 && "Unknown binary instruction type!");
1816 abort();
1817 }
1818 return IC->InsertNewInstBefore(New, I);
1819}
1820
1821// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1822// constant as the other operand, try to fold the binary operator into the
1823// select arguments. This also works for Cast instructions, which obviously do
1824// not have a second operand.
1825static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1826 InstCombiner *IC) {
1827 // Don't modify shared select instructions
1828 if (!SI->hasOneUse()) return 0;
1829 Value *TV = SI->getOperand(1);
1830 Value *FV = SI->getOperand(2);
1831
1832 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1833 // Bool selects with constant operands can be folded to logical ops.
1834 if (SI->getType() == Type::Int1Ty) return 0;
1835
1836 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1837 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1838
Gabor Greifd6da1d02008-04-06 20:25:17 +00001839 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1840 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001841 }
1842 return 0;
1843}
1844
1845
1846/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1847/// node as operand #0, see if we can fold the instruction into the PHI (which
1848/// is only possible if all operands to the PHI are constants).
1849Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1850 PHINode *PN = cast<PHINode>(I.getOperand(0));
1851 unsigned NumPHIValues = PN->getNumIncomingValues();
1852 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1853
1854 // Check to see if all of the operands of the PHI are constants. If there is
1855 // one non-constant value, remember the BB it is. If there is more than one
1856 // or if *it* is a PHI, bail out.
1857 BasicBlock *NonConstBB = 0;
1858 for (unsigned i = 0; i != NumPHIValues; ++i)
1859 if (!isa<Constant>(PN->getIncomingValue(i))) {
1860 if (NonConstBB) return 0; // More than one non-const value.
1861 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1862 NonConstBB = PN->getIncomingBlock(i);
1863
1864 // If the incoming non-constant value is in I's block, we have an infinite
1865 // loop.
1866 if (NonConstBB == I.getParent())
1867 return 0;
1868 }
1869
1870 // If there is exactly one non-constant value, we can insert a copy of the
1871 // operation in that block. However, if this is a critical edge, we would be
1872 // inserting the computation one some other paths (e.g. inside a loop). Only
1873 // do this if the pred block is unconditionally branching into the phi block.
1874 if (NonConstBB) {
1875 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1876 if (!BI || !BI->isUnconditional()) return 0;
1877 }
1878
1879 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001880 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001881 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1882 InsertNewInstBefore(NewPN, *PN);
1883 NewPN->takeName(PN);
1884
1885 // Next, add all of the operands to the PHI.
1886 if (I.getNumOperands() == 2) {
1887 Constant *C = cast<Constant>(I.getOperand(1));
1888 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001889 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001890 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1891 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1892 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1893 else
1894 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1895 } else {
1896 assert(PN->getIncomingBlock(i) == NonConstBB);
1897 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001898 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001899 PN->getIncomingValue(i), C, "phitmp",
1900 NonConstBB->getTerminator());
1901 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001902 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 CI->getPredicate(),
1904 PN->getIncomingValue(i), C, "phitmp",
1905 NonConstBB->getTerminator());
1906 else
1907 assert(0 && "Unknown binop!");
1908
1909 AddToWorkList(cast<Instruction>(InV));
1910 }
1911 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1912 }
1913 } else {
1914 CastInst *CI = cast<CastInst>(&I);
1915 const Type *RetTy = CI->getType();
1916 for (unsigned i = 0; i != NumPHIValues; ++i) {
1917 Value *InV;
1918 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1919 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1920 } else {
1921 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001922 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001923 I.getType(), "phitmp",
1924 NonConstBB->getTerminator());
1925 AddToWorkList(cast<Instruction>(InV));
1926 }
1927 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1928 }
1929 }
1930 return ReplaceInstUsesWith(I, NewPN);
1931}
1932
Chris Lattner55476162008-01-29 06:52:45 +00001933
Chris Lattner3554f972008-05-20 05:46:13 +00001934/// WillNotOverflowSignedAdd - Return true if we can prove that:
1935/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1936/// This basically requires proving that the add in the original type would not
1937/// overflow to change the sign bit or have a carry out.
1938bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1939 // There are different heuristics we can use for this. Here are some simple
1940 // ones.
1941
1942 // Add has the property that adding any two 2's complement numbers can only
1943 // have one carry bit which can change a sign. As such, if LHS and RHS each
1944 // have at least two sign bits, we know that the addition of the two values will
1945 // sign extend fine.
1946 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1947 return true;
1948
1949
1950 // If one of the operands only has one non-zero bit, and if the other operand
1951 // has a known-zero bit in a more significant place than it (not including the
1952 // sign bit) the ripple may go up to and fill the zero, but won't change the
1953 // sign. For example, (X & ~4) + 1.
1954
1955 // TODO: Implement.
1956
1957 return false;
1958}
1959
Chris Lattner55476162008-01-29 06:52:45 +00001960
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001961Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1962 bool Changed = SimplifyCommutative(I);
1963 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1964
1965 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1966 // X + undef -> undef
1967 if (isa<UndefValue>(RHS))
1968 return ReplaceInstUsesWith(I, RHS);
1969
1970 // X + 0 --> X
1971 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1972 if (RHSC->isNullValue())
1973 return ReplaceInstUsesWith(I, LHS);
1974 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001975 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1976 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977 return ReplaceInstUsesWith(I, LHS);
1978 }
1979
1980 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1981 // X + (signbit) --> X ^ signbit
1982 const APInt& Val = CI->getValue();
1983 uint32_t BitWidth = Val.getBitWidth();
1984 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00001985 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001986
1987 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1988 // (X & 254)+1 -> (X&254)|1
1989 if (!isa<VectorType>(I.getType())) {
1990 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1991 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1992 KnownZero, KnownOne))
1993 return &I;
1994 }
1995 }
1996
1997 if (isa<PHINode>(LHS))
1998 if (Instruction *NV = FoldOpIntoPhi(I))
1999 return NV;
2000
2001 ConstantInt *XorRHS = 0;
2002 Value *XorLHS = 0;
2003 if (isa<ConstantInt>(RHSC) &&
2004 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2005 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2006 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2007
2008 uint32_t Size = TySizeBits / 2;
2009 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2010 APInt CFF80Val(-C0080Val);
2011 do {
2012 if (TySizeBits > Size) {
2013 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2014 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2015 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2016 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2017 // This is a sign extend if the top bits are known zero.
2018 if (!MaskedValueIsZero(XorLHS,
2019 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2020 Size = 0; // Not a sign ext, but can't be any others either.
2021 break;
2022 }
2023 }
2024 Size >>= 1;
2025 C0080Val = APIntOps::lshr(C0080Val, Size);
2026 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2027 } while (Size >= 1);
2028
2029 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002030 // with funny bit widths then this switch statement should be removed. It
2031 // is just here to get the size of the "middle" type back up to something
2032 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002033 const Type *MiddleType = 0;
2034 switch (Size) {
2035 default: break;
2036 case 32: MiddleType = Type::Int32Ty; break;
2037 case 16: MiddleType = Type::Int16Ty; break;
2038 case 8: MiddleType = Type::Int8Ty; break;
2039 }
2040 if (MiddleType) {
2041 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2042 InsertNewInstBefore(NewTrunc, I);
2043 return new SExtInst(NewTrunc, I.getType(), I.getName());
2044 }
2045 }
2046 }
2047
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002048 if (I.getType() == Type::Int1Ty)
2049 return BinaryOperator::CreateXor(LHS, RHS);
2050
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002051 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002052 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2054
2055 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2056 if (RHSI->getOpcode() == Instruction::Sub)
2057 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2058 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2059 }
2060 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2061 if (LHSI->getOpcode() == Instruction::Sub)
2062 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2063 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2064 }
2065 }
2066
2067 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002068 // -A + -B --> -(A + B)
2069 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002070 if (LHS->getType()->isIntOrIntVector()) {
2071 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002072 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002073 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002074 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002075 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002076 }
2077
Gabor Greifa645dd32008-05-16 19:29:10 +00002078 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002079 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002080
2081 // A + -B --> A - B
2082 if (!isa<Constant>(RHS))
2083 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002084 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085
2086
2087 ConstantInt *C2;
2088 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2089 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002090 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002091
2092 // X*C1 + X*C2 --> X * (C1+C2)
2093 ConstantInt *C1;
2094 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002095 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002096 }
2097
2098 // X + X*C --> X * (C+1)
2099 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002100 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002101
2102 // X + ~X --> -1 since ~X = -X-1
2103 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2104 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2105
2106
2107 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2108 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2109 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2110 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002111
2112 // A+B --> A|B iff A and B have no bits set in common.
2113 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2114 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2115 APInt LHSKnownOne(IT->getBitWidth(), 0);
2116 APInt LHSKnownZero(IT->getBitWidth(), 0);
2117 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2118 if (LHSKnownZero != 0) {
2119 APInt RHSKnownOne(IT->getBitWidth(), 0);
2120 APInt RHSKnownZero(IT->getBitWidth(), 0);
2121 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2122
2123 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002124 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002125 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002126 }
2127 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002128
Nick Lewycky83598a72008-02-03 07:42:09 +00002129 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002130 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002131 Value *W, *X, *Y, *Z;
2132 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2133 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2134 if (W != Y) {
2135 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002136 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002137 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002138 std::swap(W, X);
2139 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002140 std::swap(Y, Z);
2141 std::swap(W, X);
2142 }
2143 }
2144
2145 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002146 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002147 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002148 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002149 }
2150 }
2151 }
2152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002153 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2154 Value *X = 0;
2155 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002156 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002157
2158 // (X & FF00) + xx00 -> (X+xx00) & FF00
2159 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2160 Constant *Anded = And(CRHS, C2);
2161 if (Anded == CRHS) {
2162 // See if all bits from the first bit set in the Add RHS up are included
2163 // in the mask. First, get the rightmost bit.
2164 const APInt& AddRHSV = CRHS->getValue();
2165
2166 // Form a mask of all bits from the lowest bit added through the top.
2167 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2168
2169 // See if the and mask includes all of these bits.
2170 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2171
2172 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2173 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002174 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002176 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 }
2178 }
2179 }
2180
2181 // Try to fold constant add into select arguments.
2182 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2183 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2184 return R;
2185 }
2186
2187 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002188 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 {
2190 CastInst *CI = dyn_cast<CastInst>(LHS);
2191 Value *Other = RHS;
2192 if (!CI) {
2193 CI = dyn_cast<CastInst>(RHS);
2194 Other = LHS;
2195 }
2196 if (CI && CI->getType()->isSized() &&
2197 (CI->getType()->getPrimitiveSizeInBits() ==
2198 TD->getIntPtrType()->getPrimitiveSizeInBits())
2199 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002200 unsigned AS =
2201 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002202 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2203 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002204 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002205 return new PtrToIntInst(I2, CI->getType());
2206 }
2207 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002208
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002209 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002210 {
2211 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2212 Value *Other = RHS;
2213 if (!SI) {
2214 SI = dyn_cast<SelectInst>(RHS);
2215 Other = LHS;
2216 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002217 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002218 Value *TV = SI->getTrueValue();
2219 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002220 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002221
2222 // Can we fold the add into the argument of the select?
2223 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002224 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2225 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002226 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002227 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2228 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002229 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002230 }
2231 }
Chris Lattner55476162008-01-29 06:52:45 +00002232
2233 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2234 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2235 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2236 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002237
Chris Lattner3554f972008-05-20 05:46:13 +00002238 // Check for (add (sext x), y), see if we can merge this into an
2239 // integer add followed by a sext.
2240 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2241 // (add (sext x), cst) --> (sext (add x, cst'))
2242 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2243 Constant *CI =
2244 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2245 if (LHSConv->hasOneUse() &&
2246 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2247 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2248 // Insert the new, smaller add.
2249 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2250 CI, "addconv");
2251 InsertNewInstBefore(NewAdd, I);
2252 return new SExtInst(NewAdd, I.getType());
2253 }
2254 }
2255
2256 // (add (sext x), (sext y)) --> (sext (add int x, y))
2257 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2258 // Only do this if x/y have the same type, if at last one of them has a
2259 // single use (so we don't increase the number of sexts), and if the
2260 // integer add will not overflow.
2261 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2262 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2263 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2264 RHSConv->getOperand(0))) {
2265 // Insert the new integer add.
2266 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2267 RHSConv->getOperand(0),
2268 "addconv");
2269 InsertNewInstBefore(NewAdd, I);
2270 return new SExtInst(NewAdd, I.getType());
2271 }
2272 }
2273 }
2274
2275 // Check for (add double (sitofp x), y), see if we can merge this into an
2276 // integer add followed by a promotion.
2277 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2278 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2279 // ... if the constant fits in the integer value. This is useful for things
2280 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2281 // requires a constant pool load, and generally allows the add to be better
2282 // instcombined.
2283 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2284 Constant *CI =
2285 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2286 if (LHSConv->hasOneUse() &&
2287 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2288 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2289 // Insert the new integer add.
2290 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2291 CI, "addconv");
2292 InsertNewInstBefore(NewAdd, I);
2293 return new SIToFPInst(NewAdd, I.getType());
2294 }
2295 }
2296
2297 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2298 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2299 // Only do this if x/y have the same type, if at last one of them has a
2300 // single use (so we don't increase the number of int->fp conversions),
2301 // and if the integer add will not overflow.
2302 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2303 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2304 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2305 RHSConv->getOperand(0))) {
2306 // Insert the new integer add.
2307 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2308 RHSConv->getOperand(0),
2309 "addconv");
2310 InsertNewInstBefore(NewAdd, I);
2311 return new SIToFPInst(NewAdd, I.getType());
2312 }
2313 }
2314 }
2315
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 return Changed ? &I : 0;
2317}
2318
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2321
Chris Lattner27fbef42008-07-17 06:07:20 +00002322 if (Op0 == Op1 && // sub X, X -> 0
2323 !I.getType()->isFPOrFPVector())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2325
2326 // If this is a 'B = x-(-A)', change to B = x+A...
2327 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002328 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002329
2330 if (isa<UndefValue>(Op0))
2331 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2332 if (isa<UndefValue>(Op1))
2333 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2334
2335 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2336 // Replace (-1 - A) with (~A)...
2337 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002338 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002339
2340 // C - ~X == X + (1+C)
2341 Value *X = 0;
2342 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002343 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344
2345 // -(X >>u 31) -> (X >>s 31)
2346 // -(X >>s 31) -> (X >>u 31)
2347 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002348 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002349 if (SI->getOpcode() == Instruction::LShr) {
2350 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2351 // Check to see if we are shifting out everything but the sign bit.
2352 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2353 SI->getType()->getPrimitiveSizeInBits()-1) {
2354 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002355 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002356 SI->getOperand(0), CU, SI->getName());
2357 }
2358 }
2359 }
2360 else if (SI->getOpcode() == Instruction::AShr) {
2361 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2362 // Check to see if we are shifting out everything but the sign bit.
2363 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2364 SI->getType()->getPrimitiveSizeInBits()-1) {
2365 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002366 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002367 SI->getOperand(0), CU, SI->getName());
2368 }
2369 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002370 }
2371 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002372 }
2373
2374 // Try to fold constant sub into select arguments.
2375 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2376 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2377 return R;
2378
2379 if (isa<PHINode>(Op0))
2380 if (Instruction *NV = FoldOpIntoPhi(I))
2381 return NV;
2382 }
2383
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002384 if (I.getType() == Type::Int1Ty)
2385 return BinaryOperator::CreateXor(Op0, Op1);
2386
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002387 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2388 if (Op1I->getOpcode() == Instruction::Add &&
2389 !Op0->getType()->isFPOrFPVector()) {
2390 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002391 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002392 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002393 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002394 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2395 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2396 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002397 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002398 Op1I->getOperand(0));
2399 }
2400 }
2401
2402 if (Op1I->hasOneUse()) {
2403 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2404 // is not used by anyone else...
2405 //
2406 if (Op1I->getOpcode() == Instruction::Sub &&
2407 !Op1I->getType()->isFPOrFPVector()) {
2408 // Swap the two operands of the subexpr...
2409 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2410 Op1I->setOperand(0, IIOp1);
2411 Op1I->setOperand(1, IIOp0);
2412
2413 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002414 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002415 }
2416
2417 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2418 //
2419 if (Op1I->getOpcode() == Instruction::And &&
2420 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2421 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2422
2423 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002424 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2425 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426 }
2427
2428 // 0 - (X sdiv C) -> (X sdiv -C)
2429 if (Op1I->getOpcode() == Instruction::SDiv)
2430 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2431 if (CSI->isZero())
2432 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434 ConstantExpr::getNeg(DivRHS));
2435
2436 // X - X*C --> X * (1-C)
2437 ConstantInt *C2 = 0;
2438 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2439 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002440 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002441 }
Dan Gohmanda338742007-09-17 17:31:57 +00002442
2443 // X - ((X / Y) * Y) --> X % Y
2444 if (Op1I->getOpcode() == Instruction::Mul)
2445 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2446 if (Op0 == I->getOperand(0) &&
2447 Op1I->getOperand(1) == I->getOperand(1)) {
2448 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002449 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002450 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002451 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002452 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002453 }
2454 }
2455
2456 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002457 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458 if (Op0I->getOpcode() == Instruction::Add) {
2459 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2460 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2461 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2462 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2463 } else if (Op0I->getOpcode() == Instruction::Sub) {
2464 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002465 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002466 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002467 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002468
2469 ConstantInt *C1;
2470 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2471 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473
2474 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2475 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002476 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002477 }
2478 return 0;
2479}
2480
2481/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2482/// comparison only checks the sign bit. If it only checks the sign bit, set
2483/// TrueIfSigned if the result of the comparison is true when the input value is
2484/// signed.
2485static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2486 bool &TrueIfSigned) {
2487 switch (pred) {
2488 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2489 TrueIfSigned = true;
2490 return RHS->isZero();
2491 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2492 TrueIfSigned = true;
2493 return RHS->isAllOnesValue();
2494 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2495 TrueIfSigned = false;
2496 return RHS->isAllOnesValue();
2497 case ICmpInst::ICMP_UGT:
2498 // True if LHS u> RHS and RHS == high-bit-mask - 1
2499 TrueIfSigned = true;
2500 return RHS->getValue() ==
2501 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2502 case ICmpInst::ICMP_UGE:
2503 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2504 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002505 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 default:
2507 return false;
2508 }
2509}
2510
2511Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2512 bool Changed = SimplifyCommutative(I);
2513 Value *Op0 = I.getOperand(0);
2514
2515 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2516 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
2518 // Simplify mul instructions with a constant RHS...
2519 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2521
2522 // ((X << C1)*C2) == (X * (C2 << C1))
2523 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2524 if (SI->getOpcode() == Instruction::Shl)
2525 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527 ConstantExpr::getShl(CI, ShOp));
2528
2529 if (CI->isZero())
2530 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2531 if (CI->equalsInt(1)) // X * 1 == X
2532 return ReplaceInstUsesWith(I, Op0);
2533 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535
2536 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2537 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002539 ConstantInt::get(Op0->getType(), Val.logBase2()));
2540 }
2541 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2542 if (Op1F->isNullValue())
2543 return ReplaceInstUsesWith(I, Op1);
2544
2545 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2546 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattner6297fc72008-08-11 22:06:05 +00002547 if (Op1F->isExactlyValue(1.0))
2548 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2549 } else if (isa<VectorType>(Op1->getType())) {
2550 if (isa<ConstantAggregateZero>(Op1))
2551 return ReplaceInstUsesWith(I, Op1);
2552
2553 // As above, vector X*splat(1.0) -> X in all defined cases.
2554 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2555 if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2556 if (F->isExactlyValue(1.0))
2557 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 }
2559
2560 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2561 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002562 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002563 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002564 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002565 Op1, "tmp");
2566 InsertNewInstBefore(Add, I);
2567 Value *C1C2 = ConstantExpr::getMul(Op1,
2568 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002569 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002570
2571 }
2572
2573 // Try to fold constant mul into select arguments.
2574 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2575 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2576 return R;
2577
2578 if (isa<PHINode>(Op0))
2579 if (Instruction *NV = FoldOpIntoPhi(I))
2580 return NV;
2581 }
2582
2583 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2584 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002585 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002587 if (I.getType() == Type::Int1Ty)
2588 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2589
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 // If one of the operands of the multiply is a cast from a boolean value, then
2591 // we know the bool is either zero or one, so this is a 'masking' multiply.
2592 // See if we can simplify things based on how the boolean was originally
2593 // formed.
2594 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002595 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002596 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2597 BoolCast = CI;
2598 if (!BoolCast)
2599 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2600 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2601 BoolCast = CI;
2602 if (BoolCast) {
2603 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2604 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2605 const Type *SCOpTy = SCIOp0->getType();
2606 bool TIS = false;
2607
2608 // If the icmp is true iff the sign bit of X is set, then convert this
2609 // multiply into a shift/and combination.
2610 if (isa<ConstantInt>(SCIOp1) &&
2611 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2612 TIS) {
2613 // Shift the X value right to turn it into "all signbits".
2614 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2615 SCOpTy->getPrimitiveSizeInBits()-1);
2616 Value *V =
2617 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002618 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002619 BoolCast->getOperand(0)->getName()+
2620 ".mask"), I);
2621
2622 // If the multiply type is not the same as the source type, sign extend
2623 // or truncate to the multiply type.
2624 if (I.getType() != V->getType()) {
2625 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2626 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2627 Instruction::CastOps opcode =
2628 (SrcBits == DstBits ? Instruction::BitCast :
2629 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2630 V = InsertCastBefore(opcode, V, I.getType(), I);
2631 }
2632
2633 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002634 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002635 }
2636 }
2637 }
2638
2639 return Changed ? &I : 0;
2640}
2641
Chris Lattner76972db2008-07-14 00:15:52 +00002642/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2643/// instruction.
2644bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2645 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2646
2647 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2648 int NonNullOperand = -1;
2649 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2650 if (ST->isNullValue())
2651 NonNullOperand = 2;
2652 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2653 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2654 if (ST->isNullValue())
2655 NonNullOperand = 1;
2656
2657 if (NonNullOperand == -1)
2658 return false;
2659
2660 Value *SelectCond = SI->getOperand(0);
2661
2662 // Change the div/rem to use 'Y' instead of the select.
2663 I.setOperand(1, SI->getOperand(NonNullOperand));
2664
2665 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2666 // problem. However, the select, or the condition of the select may have
2667 // multiple uses. Based on our knowledge that the operand must be non-zero,
2668 // propagate the known value for the select into other uses of it, and
2669 // propagate a known value of the condition into its other users.
2670
2671 // If the select and condition only have a single use, don't bother with this,
2672 // early exit.
2673 if (SI->use_empty() && SelectCond->hasOneUse())
2674 return true;
2675
2676 // Scan the current block backward, looking for other uses of SI.
2677 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2678
2679 while (BBI != BBFront) {
2680 --BBI;
2681 // If we found a call to a function, we can't assume it will return, so
2682 // information from below it cannot be propagated above it.
2683 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2684 break;
2685
2686 // Replace uses of the select or its condition with the known values.
2687 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2688 I != E; ++I) {
2689 if (*I == SI) {
2690 *I = SI->getOperand(NonNullOperand);
2691 AddToWorkList(BBI);
2692 } else if (*I == SelectCond) {
2693 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2694 ConstantInt::getFalse();
2695 AddToWorkList(BBI);
2696 }
2697 }
2698
2699 // If we past the instruction, quit looking for it.
2700 if (&*BBI == SI)
2701 SI = 0;
2702 if (&*BBI == SelectCond)
2703 SelectCond = 0;
2704
2705 // If we ran out of things to eliminate, break out of the loop.
2706 if (SelectCond == 0 && SI == 0)
2707 break;
2708
2709 }
2710 return true;
2711}
2712
2713
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714/// This function implements the transforms on div instructions that work
2715/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2716/// used by the visitors to those instructions.
2717/// @brief Transforms common to all three div instructions
2718Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2720
Chris Lattner653ef3c2008-02-19 06:12:18 +00002721 // undef / X -> 0 for integer.
2722 // undef / X -> undef for FP (the undef could be a snan).
2723 if (isa<UndefValue>(Op0)) {
2724 if (Op0->getType()->isFPOrFPVector())
2725 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002726 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002727 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728
2729 // X / undef -> undef
2730 if (isa<UndefValue>(Op1))
2731 return ReplaceInstUsesWith(I, Op1);
2732
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733 return 0;
2734}
2735
2736/// This function implements the transforms common to both integer division
2737/// instructions (udiv and sdiv). It is called by the visitors to those integer
2738/// division instructions.
2739/// @brief Common integer divide transforms
2740Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2741 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2742
Chris Lattnercefb36c2008-05-16 02:59:42 +00002743 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002744 if (Op0 == Op1) {
2745 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2746 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2747 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2748 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2749 }
2750
2751 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2752 return ReplaceInstUsesWith(I, CI);
2753 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002754
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755 if (Instruction *Common = commonDivTransforms(I))
2756 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002757
2758 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2759 // This does not apply for fdiv.
2760 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2761 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002762
2763 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2764 // div X, 1 == X
2765 if (RHS->equalsInt(1))
2766 return ReplaceInstUsesWith(I, Op0);
2767
2768 // (X / C1) / C2 -> X / (C1*C2)
2769 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2770 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2771 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002772 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2773 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2774 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002775 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002776 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 }
2778
2779 if (!RHS->isZero()) { // avoid X udiv 0
2780 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2781 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2782 return R;
2783 if (isa<PHINode>(Op0))
2784 if (Instruction *NV = FoldOpIntoPhi(I))
2785 return NV;
2786 }
2787 }
2788
2789 // 0 / X == 0, we don't need to preserve faults!
2790 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2791 if (LHS->equalsInt(0))
2792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2793
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002794 // It can't be division by zero, hence it must be division by one.
2795 if (I.getType() == Type::Int1Ty)
2796 return ReplaceInstUsesWith(I, Op0);
2797
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 return 0;
2799}
2800
2801Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2802 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2803
2804 // Handle the integer div common cases
2805 if (Instruction *Common = commonIDivTransforms(I))
2806 return Common;
2807
2808 // X udiv C^2 -> X >> C
2809 // Check to see if this is an unsigned division with an exact power of 2,
2810 // if so, convert to a right shift.
2811 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2812 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002813 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002814 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2815 }
2816
2817 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2818 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2819 if (RHSI->getOpcode() == Instruction::Shl &&
2820 isa<ConstantInt>(RHSI->getOperand(0))) {
2821 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2822 if (C1.isPowerOf2()) {
2823 Value *N = RHSI->getOperand(1);
2824 const Type *NTy = N->getType();
2825 if (uint32_t C2 = C1.logBase2()) {
2826 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002827 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002828 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002829 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830 }
2831 }
2832 }
2833
2834 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2835 // where C1&C2 are powers of two.
2836 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2837 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2838 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2839 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2840 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2841 // Compute the shift amounts
2842 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2843 // Construct the "on true" case of the select
2844 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002845 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846 Op0, TC, SI->getName()+".t");
2847 TSI = InsertNewInstBefore(TSI, I);
2848
2849 // Construct the "on false" case of the select
2850 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002851 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002852 Op0, FC, SI->getName()+".f");
2853 FSI = InsertNewInstBefore(FSI, I);
2854
2855 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002856 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002857 }
2858 }
2859 return 0;
2860}
2861
2862Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2863 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2864
2865 // Handle the integer div common cases
2866 if (Instruction *Common = commonIDivTransforms(I))
2867 return Common;
2868
2869 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2870 // sdiv X, -1 == -X
2871 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002872 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873
2874 // -X/C -> X/-C
2875 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00002876 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002877 }
2878
2879 // If the sign bits of both operands are zero (i.e. we can prove they are
2880 // unsigned inputs), turn this into a udiv.
2881 if (I.getType()->isInteger()) {
2882 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2883 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002884 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002885 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 }
2887 }
2888
2889 return 0;
2890}
2891
2892Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2893 return commonDivTransforms(I);
2894}
2895
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002896/// This function implements the transforms on rem instructions that work
2897/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2898/// is used by the visitors to those instructions.
2899/// @brief Transforms common to all three rem instructions
2900Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2902
Chris Lattner653ef3c2008-02-19 06:12:18 +00002903 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904 if (Constant *LHS = dyn_cast<Constant>(Op0))
2905 if (LHS->isNullValue())
2906 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2907
Chris Lattner653ef3c2008-02-19 06:12:18 +00002908 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2909 if (I.getType()->isFPOrFPVector())
2910 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002912 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913 if (isa<UndefValue>(Op1))
2914 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2915
2916 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00002917 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2918 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919
2920 return 0;
2921}
2922
2923/// This function implements the transforms common to both integer remainder
2924/// instructions (urem and srem). It is called by the visitors to those integer
2925/// remainder instructions.
2926/// @brief Common integer remainder transforms
2927Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
2930 if (Instruction *common = commonRemTransforms(I))
2931 return common;
2932
2933 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2934 // X % 0 == undef, we don't need to preserve faults!
2935 if (RHS->equalsInt(0))
2936 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2937
2938 if (RHS->equalsInt(1)) // X % 1 == 0
2939 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2940
2941 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2942 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2943 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2944 return R;
2945 } else if (isa<PHINode>(Op0I)) {
2946 if (Instruction *NV = FoldOpIntoPhi(I))
2947 return NV;
2948 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002949
2950 // See if we can fold away this rem instruction.
2951 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2952 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2953 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2954 KnownZero, KnownOne))
2955 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956 }
2957 }
2958
2959 return 0;
2960}
2961
2962Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
2965 if (Instruction *common = commonIRemTransforms(I))
2966 return common;
2967
2968 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2969 // X urem C^2 -> X and C
2970 // Check to see if this is an unsigned remainder with an exact power of 2,
2971 // if so, convert to a bitwise and.
2972 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2973 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00002974 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002975 }
2976
2977 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2978 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2979 if (RHSI->getOpcode() == Instruction::Shl &&
2980 isa<ConstantInt>(RHSI->getOperand(0))) {
2981 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2982 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00002983 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002984 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002985 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 }
2987 }
2988 }
2989
2990 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2991 // where C1&C2 are powers of two.
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2993 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2994 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2995 // STO == 0 and SFO == 0 handled above.
2996 if ((STO->getValue().isPowerOf2()) &&
2997 (SFO->getValue().isPowerOf2())) {
2998 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002999 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003001 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003002 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003 }
3004 }
3005 }
3006
3007 return 0;
3008}
3009
3010Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3012
Dan Gohmandb3dd962007-11-05 23:16:33 +00003013 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003014 if (Instruction *common = commonIRemTransforms(I))
3015 return common;
3016
3017 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003018 if (!isa<Constant>(RHSNeg) ||
3019 (isa<ConstantInt>(RHSNeg) &&
3020 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 // X % -Y -> X % Y
3022 AddUsesToWorkList(I);
3023 I.setOperand(1, RHSNeg);
3024 return &I;
3025 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003026
Dan Gohmandb3dd962007-11-05 23:16:33 +00003027 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003029 if (I.getType()->isInteger()) {
3030 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3031 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3032 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003033 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003034 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 }
3036
3037 return 0;
3038}
3039
3040Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3041 return commonRemTransforms(I);
3042}
3043
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003044// isOneBitSet - Return true if there is exactly one bit set in the specified
3045// constant.
3046static bool isOneBitSet(const ConstantInt *CI) {
3047 return CI->getValue().isPowerOf2();
3048}
3049
3050// isHighOnes - Return true if the constant is of the form 1+0+.
3051// This is the same as lowones(~X).
3052static bool isHighOnes(const ConstantInt *CI) {
3053 return (~CI->getValue() + 1).isPowerOf2();
3054}
3055
3056/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3057/// are carefully arranged to allow folding of expressions such as:
3058///
3059/// (A < B) | (A > B) --> (A != B)
3060///
3061/// Note that this is only valid if the first and second predicates have the
3062/// same sign. Is illegal to do: (A u< B) | (A s> B)
3063///
3064/// Three bits are used to represent the condition, as follows:
3065/// 0 A > B
3066/// 1 A == B
3067/// 2 A < B
3068///
3069/// <=> Value Definition
3070/// 000 0 Always false
3071/// 001 1 A > B
3072/// 010 2 A == B
3073/// 011 3 A >= B
3074/// 100 4 A < B
3075/// 101 5 A != B
3076/// 110 6 A <= B
3077/// 111 7 Always true
3078///
3079static unsigned getICmpCode(const ICmpInst *ICI) {
3080 switch (ICI->getPredicate()) {
3081 // False -> 0
3082 case ICmpInst::ICMP_UGT: return 1; // 001
3083 case ICmpInst::ICMP_SGT: return 1; // 001
3084 case ICmpInst::ICMP_EQ: return 2; // 010
3085 case ICmpInst::ICMP_UGE: return 3; // 011
3086 case ICmpInst::ICMP_SGE: return 3; // 011
3087 case ICmpInst::ICMP_ULT: return 4; // 100
3088 case ICmpInst::ICMP_SLT: return 4; // 100
3089 case ICmpInst::ICMP_NE: return 5; // 101
3090 case ICmpInst::ICMP_ULE: return 6; // 110
3091 case ICmpInst::ICMP_SLE: return 6; // 110
3092 // True -> 7
3093 default:
3094 assert(0 && "Invalid ICmp predicate!");
3095 return 0;
3096 }
3097}
3098
3099/// getICmpValue - This is the complement of getICmpCode, which turns an
3100/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003101/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003102/// of predicate to use in new icmp instructions.
3103static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3104 switch (code) {
3105 default: assert(0 && "Illegal ICmp code!");
3106 case 0: return ConstantInt::getFalse();
3107 case 1:
3108 if (sign)
3109 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3110 else
3111 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3112 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3113 case 3:
3114 if (sign)
3115 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3116 else
3117 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3118 case 4:
3119 if (sign)
3120 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3121 else
3122 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3123 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3124 case 6:
3125 if (sign)
3126 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3127 else
3128 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3129 case 7: return ConstantInt::getTrue();
3130 }
3131}
3132
3133static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3134 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3135 (ICmpInst::isSignedPredicate(p1) &&
3136 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3137 (ICmpInst::isSignedPredicate(p2) &&
3138 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3139}
3140
3141namespace {
3142// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3143struct FoldICmpLogical {
3144 InstCombiner &IC;
3145 Value *LHS, *RHS;
3146 ICmpInst::Predicate pred;
3147 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3148 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3149 pred(ICI->getPredicate()) {}
3150 bool shouldApply(Value *V) const {
3151 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3152 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003153 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3154 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 return false;
3156 }
3157 Instruction *apply(Instruction &Log) const {
3158 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3159 if (ICI->getOperand(0) != LHS) {
3160 assert(ICI->getOperand(1) == LHS);
3161 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3162 }
3163
3164 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3165 unsigned LHSCode = getICmpCode(ICI);
3166 unsigned RHSCode = getICmpCode(RHSICI);
3167 unsigned Code;
3168 switch (Log.getOpcode()) {
3169 case Instruction::And: Code = LHSCode & RHSCode; break;
3170 case Instruction::Or: Code = LHSCode | RHSCode; break;
3171 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3172 default: assert(0 && "Illegal logical opcode!"); return 0;
3173 }
3174
3175 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3176 ICmpInst::isSignedPredicate(ICI->getPredicate());
3177
3178 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3179 if (Instruction *I = dyn_cast<Instruction>(RV))
3180 return I;
3181 // Otherwise, it's a constant boolean value...
3182 return IC.ReplaceInstUsesWith(Log, RV);
3183 }
3184};
3185} // end anonymous namespace
3186
3187// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3188// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3189// guaranteed to be a binary operator.
3190Instruction *InstCombiner::OptAndOp(Instruction *Op,
3191 ConstantInt *OpRHS,
3192 ConstantInt *AndRHS,
3193 BinaryOperator &TheAnd) {
3194 Value *X = Op->getOperand(0);
3195 Constant *Together = 0;
3196 if (!Op->isShift())
3197 Together = And(AndRHS, OpRHS);
3198
3199 switch (Op->getOpcode()) {
3200 case Instruction::Xor:
3201 if (Op->hasOneUse()) {
3202 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003203 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 InsertNewInstBefore(And, TheAnd);
3205 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003206 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 }
3208 break;
3209 case Instruction::Or:
3210 if (Together == AndRHS) // (X | C) & C --> C
3211 return ReplaceInstUsesWith(TheAnd, AndRHS);
3212
3213 if (Op->hasOneUse() && Together != OpRHS) {
3214 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003215 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 InsertNewInstBefore(Or, TheAnd);
3217 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003218 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 }
3220 break;
3221 case Instruction::Add:
3222 if (Op->hasOneUse()) {
3223 // Adding a one to a single bit bit-field should be turned into an XOR
3224 // of the bit. First thing to check is to see if this AND is with a
3225 // single bit constant.
3226 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3227
3228 // If there is only one bit set...
3229 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3230 // Ok, at this point, we know that we are masking the result of the
3231 // ADD down to exactly one bit. If the constant we are adding has
3232 // no bits set below this bit, then we can eliminate the ADD.
3233 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3234
3235 // Check to see if any bits below the one bit set in AndRHSV are set.
3236 if ((AddRHS & (AndRHSV-1)) == 0) {
3237 // If not, the only thing that can effect the output of the AND is
3238 // the bit specified by AndRHSV. If that bit is set, the effect of
3239 // the XOR is to toggle the bit. If it is clear, then the ADD has
3240 // no effect.
3241 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3242 TheAnd.setOperand(0, X);
3243 return &TheAnd;
3244 } else {
3245 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003246 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003247 InsertNewInstBefore(NewAnd, TheAnd);
3248 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003249 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003250 }
3251 }
3252 }
3253 }
3254 break;
3255
3256 case Instruction::Shl: {
3257 // We know that the AND will not produce any of the bits shifted in, so if
3258 // the anded constant includes them, clear them now!
3259 //
3260 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3261 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3262 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3263 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3264
3265 if (CI->getValue() == ShlMask) {
3266 // Masking out bits that the shift already masks
3267 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3268 } else if (CI != AndRHS) { // Reducing bits set in and.
3269 TheAnd.setOperand(1, CI);
3270 return &TheAnd;
3271 }
3272 break;
3273 }
3274 case Instruction::LShr:
3275 {
3276 // We know that the AND will not produce any of the bits shifted in, so if
3277 // the anded constant includes them, clear them now! This only applies to
3278 // unsigned shifts, because a signed shr may bring in set bits!
3279 //
3280 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3281 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3282 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3283 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3284
3285 if (CI->getValue() == ShrMask) {
3286 // Masking out bits that the shift already masks.
3287 return ReplaceInstUsesWith(TheAnd, Op);
3288 } else if (CI != AndRHS) {
3289 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3290 return &TheAnd;
3291 }
3292 break;
3293 }
3294 case Instruction::AShr:
3295 // Signed shr.
3296 // See if this is shifting in some sign extension, then masking it out
3297 // with an and.
3298 if (Op->hasOneUse()) {
3299 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3300 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3301 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3302 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3303 if (C == AndRHS) { // Masking out bits shifted in.
3304 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3305 // Make the argument unsigned.
3306 Value *ShVal = Op->getOperand(0);
3307 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003308 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003309 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003310 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003311 }
3312 }
3313 break;
3314 }
3315 return 0;
3316}
3317
3318
3319/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3320/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3321/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3322/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3323/// insert new instructions.
3324Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3325 bool isSigned, bool Inside,
3326 Instruction &IB) {
3327 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3328 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3329 "Lo is not <= Hi in range emission code!");
3330
3331 if (Inside) {
3332 if (Lo == Hi) // Trivially false.
3333 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3334
3335 // V >= Min && V < Hi --> V < Hi
3336 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3337 ICmpInst::Predicate pred = (isSigned ?
3338 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3339 return new ICmpInst(pred, V, Hi);
3340 }
3341
3342 // Emit V-Lo <u Hi-Lo
3343 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003344 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003345 InsertNewInstBefore(Add, IB);
3346 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3347 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3348 }
3349
3350 if (Lo == Hi) // Trivially true.
3351 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3352
3353 // V < Min || V >= Hi -> V > Hi-1
3354 Hi = SubOne(cast<ConstantInt>(Hi));
3355 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3356 ICmpInst::Predicate pred = (isSigned ?
3357 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3358 return new ICmpInst(pred, V, Hi);
3359 }
3360
3361 // Emit V-Lo >u Hi-1-Lo
3362 // Note that Hi has already had one subtracted from it, above.
3363 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003364 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 InsertNewInstBefore(Add, IB);
3366 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3367 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3368}
3369
3370// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3371// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3372// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3373// not, since all 1s are not contiguous.
3374static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3375 const APInt& V = Val->getValue();
3376 uint32_t BitWidth = Val->getType()->getBitWidth();
3377 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3378
3379 // look for the first zero bit after the run of ones
3380 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3381 // look for the first non-zero bit
3382 ME = V.getActiveBits();
3383 return true;
3384}
3385
3386/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3387/// where isSub determines whether the operator is a sub. If we can fold one of
3388/// the following xforms:
3389///
3390/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3391/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3392/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3393///
3394/// return (A +/- B).
3395///
3396Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3397 ConstantInt *Mask, bool isSub,
3398 Instruction &I) {
3399 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3400 if (!LHSI || LHSI->getNumOperands() != 2 ||
3401 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3402
3403 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3404
3405 switch (LHSI->getOpcode()) {
3406 default: return 0;
3407 case Instruction::And:
3408 if (And(N, Mask) == Mask) {
3409 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3410 if ((Mask->getValue().countLeadingZeros() +
3411 Mask->getValue().countPopulation()) ==
3412 Mask->getValue().getBitWidth())
3413 break;
3414
3415 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3416 // part, we don't need any explicit masks to take them out of A. If that
3417 // is all N is, ignore it.
3418 uint32_t MB = 0, ME = 0;
3419 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3420 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3421 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3422 if (MaskedValueIsZero(RHS, Mask))
3423 break;
3424 }
3425 }
3426 return 0;
3427 case Instruction::Or:
3428 case Instruction::Xor:
3429 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3430 if ((Mask->getValue().countLeadingZeros() +
3431 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3432 && And(N, Mask)->isZero())
3433 break;
3434 return 0;
3435 }
3436
3437 Instruction *New;
3438 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003439 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003440 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003441 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 return InsertNewInstBefore(New, I);
3443}
3444
3445Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3446 bool Changed = SimplifyCommutative(I);
3447 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3448
3449 if (isa<UndefValue>(Op1)) // X & undef -> 0
3450 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3451
3452 // and X, X = X
3453 if (Op0 == Op1)
3454 return ReplaceInstUsesWith(I, Op1);
3455
3456 // See if we can simplify any instructions used by the instruction whose sole
3457 // purpose is to compute bits we don't care about.
3458 if (!isa<VectorType>(I.getType())) {
3459 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3460 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3461 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3462 KnownZero, KnownOne))
3463 return &I;
3464 } else {
3465 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3466 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3467 return ReplaceInstUsesWith(I, I.getOperand(0));
3468 } else if (isa<ConstantAggregateZero>(Op1)) {
3469 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3470 }
3471 }
3472
3473 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3474 const APInt& AndRHSMask = AndRHS->getValue();
3475 APInt NotAndRHS(~AndRHSMask);
3476
3477 // Optimize a variety of ((val OP C1) & C2) combinations...
3478 if (isa<BinaryOperator>(Op0)) {
3479 Instruction *Op0I = cast<Instruction>(Op0);
3480 Value *Op0LHS = Op0I->getOperand(0);
3481 Value *Op0RHS = Op0I->getOperand(1);
3482 switch (Op0I->getOpcode()) {
3483 case Instruction::Xor:
3484 case Instruction::Or:
3485 // If the mask is only needed on one incoming arm, push it up.
3486 if (Op0I->hasOneUse()) {
3487 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3488 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003489 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003490 Op0RHS->getName()+".masked");
3491 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003492 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003493 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3494 }
3495 if (!isa<Constant>(Op0RHS) &&
3496 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3497 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003498 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499 Op0LHS->getName()+".masked");
3500 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003501 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003502 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3503 }
3504 }
3505
3506 break;
3507 case Instruction::Add:
3508 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3509 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3510 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3511 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003512 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003513 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003514 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003515 break;
3516
3517 case Instruction::Sub:
3518 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3519 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3520 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3521 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003522 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003523
Nick Lewyckya349ba42008-07-10 05:51:40 +00003524 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3525 // has 1's for all bits that the subtraction with A might affect.
3526 if (Op0I->hasOneUse()) {
3527 uint32_t BitWidth = AndRHSMask.getBitWidth();
3528 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3529 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3530
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003531 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00003532 if (!(A && A->isZero()) && // avoid infinite recursion.
3533 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003534 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3535 InsertNewInstBefore(NewNeg, I);
3536 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3537 }
3538 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003539 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003540
3541 case Instruction::Shl:
3542 case Instruction::LShr:
3543 // (1 << x) & 1 --> zext(x == 0)
3544 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00003545 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003546 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3547 Constant::getNullValue(I.getType()));
3548 InsertNewInstBefore(NewICmp, I);
3549 return new ZExtInst(NewICmp, I.getType());
3550 }
3551 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552 }
3553
3554 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3555 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3556 return Res;
3557 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3558 // If this is an integer truncation or change from signed-to-unsigned, and
3559 // if the source is an and/or with immediate, transform it. This
3560 // frequently occurs for bitfield accesses.
3561 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3562 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3563 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003564 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003565 if (CastOp->getOpcode() == Instruction::And) {
3566 // Change: and (cast (and X, C1) to T), C2
3567 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3568 // This will fold the two constants together, which may allow
3569 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003570 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003571 CastOp->getOperand(0), I.getType(),
3572 CastOp->getName()+".shrunk");
3573 NewCast = InsertNewInstBefore(NewCast, I);
3574 // trunc_or_bitcast(C1)&C2
3575 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3576 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003577 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003578 } else if (CastOp->getOpcode() == Instruction::Or) {
3579 // Change: and (cast (or X, C1) to T), C2
3580 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3581 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3582 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3583 return ReplaceInstUsesWith(I, AndRHS);
3584 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003585 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003586 }
3587 }
3588
3589 // Try to fold constant and into select arguments.
3590 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3591 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3592 return R;
3593 if (isa<PHINode>(Op0))
3594 if (Instruction *NV = FoldOpIntoPhi(I))
3595 return NV;
3596 }
3597
3598 Value *Op0NotVal = dyn_castNotVal(Op0);
3599 Value *Op1NotVal = dyn_castNotVal(Op1);
3600
3601 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3602 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3603
3604 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3605 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003606 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003607 I.getName()+".demorgan");
3608 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003609 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003610 }
3611
3612 {
3613 Value *A = 0, *B = 0, *C = 0, *D = 0;
3614 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3615 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3616 return ReplaceInstUsesWith(I, Op1);
3617
3618 // (A|B) & ~(A&B) -> A^B
3619 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3620 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003621 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003622 }
3623 }
3624
3625 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3626 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3627 return ReplaceInstUsesWith(I, Op0);
3628
3629 // ~(A&B) & (A|B) -> A^B
3630 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3631 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003632 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003633 }
3634 }
3635
3636 if (Op0->hasOneUse() &&
3637 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3638 if (A == Op1) { // (A^B)&A -> A&(A^B)
3639 I.swapOperands(); // Simplify below
3640 std::swap(Op0, Op1);
3641 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3642 cast<BinaryOperator>(Op0)->swapOperands();
3643 I.swapOperands(); // Simplify below
3644 std::swap(Op0, Op1);
3645 }
3646 }
3647 if (Op1->hasOneUse() &&
3648 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3649 if (B == Op0) { // B&(A^B) -> B&(B^A)
3650 cast<BinaryOperator>(Op1)->swapOperands();
3651 std::swap(A, B);
3652 }
3653 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003654 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003656 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003657 }
3658 }
3659 }
3660
Nick Lewycky771d6052008-08-06 04:54:03 +00003661 { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3662 // where C is a power of 2
3663 Value *A, *B;
3664 ConstantInt *C1, *C2;
Evan Cheng94fd9742008-08-20 23:36:48 +00003665 ICmpInst::Predicate LHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3666 ICmpInst::Predicate RHSCC = ICmpInst::BAD_ICMP_PREDICATE;
Nick Lewycky771d6052008-08-06 04:54:03 +00003667 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3668 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3669 if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3670 C1->getValue().isPowerOf2()) {
3671 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3672 InsertNewInstBefore(NewOr, I);
3673 return new ICmpInst(LHSCC, NewOr, C1);
3674 }
3675 }
3676
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003677 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3678 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3679 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3680 return R;
3681
3682 Value *LHSVal, *RHSVal;
3683 ConstantInt *LHSCst, *RHSCst;
3684 ICmpInst::Predicate LHSCC, RHSCC;
3685 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3686 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3687 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3688 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3689 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3690 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3691 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003692 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3693
3694 // Don't try to fold ICMP_SLT + ICMP_ULT.
3695 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3696 ICmpInst::isSignedPredicate(LHSCC) ==
3697 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003699 ICmpInst::Predicate GT;
3700 if (ICmpInst::isSignedPredicate(LHSCC) ||
3701 (ICmpInst::isEquality(LHSCC) &&
3702 ICmpInst::isSignedPredicate(RHSCC)))
3703 GT = ICmpInst::ICMP_SGT;
3704 else
3705 GT = ICmpInst::ICMP_UGT;
3706
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3708 ICmpInst *LHS = cast<ICmpInst>(Op0);
3709 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3710 std::swap(LHS, RHS);
3711 std::swap(LHSCst, RHSCst);
3712 std::swap(LHSCC, RHSCC);
3713 }
3714
3715 // At this point, we know we have have two icmp instructions
3716 // comparing a value against two constants and and'ing the result
3717 // together. Because of the above check, we know that we only have
3718 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3719 // (from the FoldICmpLogical check above), that the two constants
3720 // are not equal and that the larger constant is on the RHS
3721 assert(LHSCst != RHSCst && "Compares not folded above?");
3722
3723 switch (LHSCC) {
3724 default: assert(0 && "Unknown integer condition code!");
3725 case ICmpInst::ICMP_EQ:
3726 switch (RHSCC) {
3727 default: assert(0 && "Unknown integer condition code!");
3728 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3729 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3730 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3731 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3732 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3733 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3734 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3735 return ReplaceInstUsesWith(I, LHS);
3736 }
3737 case ICmpInst::ICMP_NE:
3738 switch (RHSCC) {
3739 default: assert(0 && "Unknown integer condition code!");
3740 case ICmpInst::ICMP_ULT:
3741 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3742 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3743 break; // (X != 13 & X u< 15) -> no change
3744 case ICmpInst::ICMP_SLT:
3745 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3746 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3747 break; // (X != 13 & X s< 15) -> no change
3748 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3749 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3750 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3751 return ReplaceInstUsesWith(I, RHS);
3752 case ICmpInst::ICMP_NE:
3753 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3754 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00003755 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003756 LHSVal->getName()+".off");
3757 InsertNewInstBefore(Add, I);
3758 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3759 ConstantInt::get(Add->getType(), 1));
3760 }
3761 break; // (X != 13 & X != 15) -> no change
3762 }
3763 break;
3764 case ICmpInst::ICMP_ULT:
3765 switch (RHSCC) {
3766 default: assert(0 && "Unknown integer condition code!");
3767 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3768 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3769 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3770 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3771 break;
3772 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3773 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3774 return ReplaceInstUsesWith(I, LHS);
3775 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3776 break;
3777 }
3778 break;
3779 case ICmpInst::ICMP_SLT:
3780 switch (RHSCC) {
3781 default: assert(0 && "Unknown integer condition code!");
3782 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3783 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3784 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3785 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3786 break;
3787 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3788 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3789 return ReplaceInstUsesWith(I, LHS);
3790 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3791 break;
3792 }
3793 break;
3794 case ICmpInst::ICMP_UGT:
3795 switch (RHSCC) {
3796 default: assert(0 && "Unknown integer condition code!");
Eli Friedman22b85622008-06-21 23:36:13 +00003797 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003798 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3799 return ReplaceInstUsesWith(I, RHS);
3800 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3801 break;
3802 case ICmpInst::ICMP_NE:
3803 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3804 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3805 break; // (X u> 13 & X != 15) -> no change
3806 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3807 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3808 true, I);
3809 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3810 break;
3811 }
3812 break;
3813 case ICmpInst::ICMP_SGT:
3814 switch (RHSCC) {
3815 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003816 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003817 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3818 return ReplaceInstUsesWith(I, RHS);
3819 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3820 break;
3821 case ICmpInst::ICMP_NE:
3822 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3823 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3824 break; // (X s> 13 & X != 15) -> no change
3825 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3826 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3827 true, I);
3828 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3829 break;
3830 }
3831 break;
3832 }
3833 }
3834 }
3835
3836 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3837 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3838 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3839 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3840 const Type *SrcTy = Op0C->getOperand(0)->getType();
3841 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3842 // Only do this if the casts both really cause code to be generated.
3843 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3844 I.getType(), TD) &&
3845 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3846 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003847 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003848 Op1C->getOperand(0),
3849 I.getName());
3850 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003851 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003852 }
3853 }
3854
3855 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3856 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3857 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3858 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3859 SI0->getOperand(1) == SI1->getOperand(1) &&
3860 (SI0->hasOneUse() || SI1->hasOneUse())) {
3861 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00003862 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003863 SI1->getOperand(0),
3864 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003865 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 SI1->getOperand(1));
3867 }
3868 }
3869
Chris Lattner91882432007-10-24 05:38:08 +00003870 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3871 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3872 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3873 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3874 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3875 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3876 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3877 // If either of the constants are nans, then the whole thing returns
3878 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003879 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003880 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3881 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3882 RHS->getOperand(0));
3883 }
3884 }
3885 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003886
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003887 return Changed ? &I : 0;
3888}
3889
3890/// CollectBSwapParts - Look to see if the specified value defines a single byte
3891/// in the result. If it does, and if the specified byte hasn't been filled in
3892/// yet, fill it in and return false.
3893static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3894 Instruction *I = dyn_cast<Instruction>(V);
3895 if (I == 0) return true;
3896
3897 // If this is an or instruction, it is an inner node of the bswap.
3898 if (I->getOpcode() == Instruction::Or)
3899 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3900 CollectBSwapParts(I->getOperand(1), ByteValues);
3901
3902 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3903 // If this is a shift by a constant int, and it is "24", then its operand
3904 // defines a byte. We only handle unsigned types here.
3905 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3906 // Not shifting the entire input by N-1 bytes?
3907 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3908 8*(ByteValues.size()-1))
3909 return true;
3910
3911 unsigned DestNo;
3912 if (I->getOpcode() == Instruction::Shl) {
3913 // X << 24 defines the top byte with the lowest of the input bytes.
3914 DestNo = ByteValues.size()-1;
Chris Lattnerc41b0fc2008-10-05 00:50:57 +00003915 } else if (I->getOpcode() == Instruction::LShr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003916 // X >>u 24 defines the low byte with the highest of the input bytes.
3917 DestNo = 0;
Chris Lattnerc41b0fc2008-10-05 00:50:57 +00003918 } else {
3919 // Arithmetic shift right may have the top bits set.
3920 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003921 }
3922
3923 // If the destination byte value is already defined, the values are or'd
3924 // together, which isn't a bswap (unless it's an or of the same bits).
3925 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3926 return true;
3927 ByteValues[DestNo] = I->getOperand(0);
3928 return false;
3929 }
3930
3931 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3932 // don't have this.
3933 Value *Shift = 0, *ShiftLHS = 0;
3934 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3935 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3936 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3937 return true;
3938 Instruction *SI = cast<Instruction>(Shift);
3939
3940 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3941 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3942 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3943 return true;
3944
3945 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3946 unsigned DestByte;
3947 if (AndAmt->getValue().getActiveBits() > 64)
3948 return true;
3949 uint64_t AndAmtVal = AndAmt->getZExtValue();
3950 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3951 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3952 break;
3953 // Unknown mask for bswap.
3954 if (DestByte == ByteValues.size()) return true;
3955
3956 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3957 unsigned SrcByte;
3958 if (SI->getOpcode() == Instruction::Shl)
3959 SrcByte = DestByte - ShiftBytes;
3960 else
3961 SrcByte = DestByte + ShiftBytes;
3962
3963 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3964 if (SrcByte != ByteValues.size()-DestByte-1)
3965 return true;
3966
3967 // If the destination byte value is already defined, the values are or'd
3968 // together, which isn't a bswap (unless it's an or of the same bits).
3969 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3970 return true;
3971 ByteValues[DestByte] = SI->getOperand(0);
3972 return false;
3973}
3974
3975/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3976/// If so, insert the new bswap intrinsic and return it.
3977Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3978 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3979 if (!ITy || ITy->getBitWidth() % 16)
3980 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3981
3982 /// ByteValues - For each byte of the result, we keep track of which value
3983 /// defines each byte.
3984 SmallVector<Value*, 8> ByteValues;
3985 ByteValues.resize(ITy->getBitWidth()/8);
3986
3987 // Try to find all the pieces corresponding to the bswap.
3988 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3989 CollectBSwapParts(I.getOperand(1), ByteValues))
3990 return 0;
3991
3992 // Check to see if all of the bytes come from the same value.
3993 Value *V = ByteValues[0];
3994 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3995
3996 // Check to make sure that all of the bytes come from the same value.
3997 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3998 if (ByteValues[i] != V)
3999 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004000 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004001 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004002 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004003 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004004}
4005
4006
4007Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4008 bool Changed = SimplifyCommutative(I);
4009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4010
4011 if (isa<UndefValue>(Op1)) // X | undef -> -1
4012 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4013
4014 // or X, X = X
4015 if (Op0 == Op1)
4016 return ReplaceInstUsesWith(I, Op0);
4017
4018 // See if we can simplify any instructions used by the instruction whose sole
4019 // purpose is to compute bits we don't care about.
4020 if (!isa<VectorType>(I.getType())) {
4021 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4022 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4023 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4024 KnownZero, KnownOne))
4025 return &I;
4026 } else if (isa<ConstantAggregateZero>(Op1)) {
4027 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4028 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4029 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4030 return ReplaceInstUsesWith(I, I.getOperand(1));
4031 }
4032
4033
4034
4035 // or X, -1 == -1
4036 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4037 ConstantInt *C1 = 0; Value *X = 0;
4038 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4039 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004040 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004041 InsertNewInstBefore(Or, I);
4042 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004043 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004044 ConstantInt::get(RHS->getValue() | C1->getValue()));
4045 }
4046
4047 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4048 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004049 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004050 InsertNewInstBefore(Or, I);
4051 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004052 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004053 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4054 }
4055
4056 // Try to fold constant and into select arguments.
4057 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4058 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4059 return R;
4060 if (isa<PHINode>(Op0))
4061 if (Instruction *NV = FoldOpIntoPhi(I))
4062 return NV;
4063 }
4064
4065 Value *A = 0, *B = 0;
4066 ConstantInt *C1 = 0, *C2 = 0;
4067
4068 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4069 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4070 return ReplaceInstUsesWith(I, Op1);
4071 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4072 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4073 return ReplaceInstUsesWith(I, Op0);
4074
4075 // (A | B) | C and A | (B | C) -> bswap if possible.
4076 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4077 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4078 match(Op1, m_Or(m_Value(), m_Value())) ||
4079 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4080 match(Op1, m_Shift(m_Value(), m_Value())))) {
4081 if (Instruction *BSwap = MatchBSwap(I))
4082 return BSwap;
4083 }
4084
4085 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4086 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4087 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004088 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089 InsertNewInstBefore(NOr, I);
4090 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004091 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004092 }
4093
4094 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4095 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4096 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004097 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004098 InsertNewInstBefore(NOr, I);
4099 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004100 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004101 }
4102
4103 // (A & C)|(B & D)
4104 Value *C = 0, *D = 0;
4105 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4106 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4107 Value *V1 = 0, *V2 = 0, *V3 = 0;
4108 C1 = dyn_cast<ConstantInt>(C);
4109 C2 = dyn_cast<ConstantInt>(D);
4110 if (C1 && C2) { // (A & C1)|(B & C2)
4111 // If we have: ((V + N) & C1) | (V & C2)
4112 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4113 // replace with V+N.
4114 if (C1->getValue() == ~C2->getValue()) {
4115 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4116 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4117 // Add commutes, try both ways.
4118 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4119 return ReplaceInstUsesWith(I, A);
4120 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4121 return ReplaceInstUsesWith(I, A);
4122 }
4123 // Or commutes, try both ways.
4124 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4125 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4126 // Add commutes, try both ways.
4127 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4128 return ReplaceInstUsesWith(I, B);
4129 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4130 return ReplaceInstUsesWith(I, B);
4131 }
4132 }
4133 V1 = 0; V2 = 0; V3 = 0;
4134 }
4135
4136 // Check to see if we have any common things being and'ed. If so, find the
4137 // terms for V1 & (V2|V3).
4138 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4139 if (A == B) // (A & C)|(A & D) == A & (C|D)
4140 V1 = A, V2 = C, V3 = D;
4141 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4142 V1 = A, V2 = B, V3 = C;
4143 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4144 V1 = C, V2 = A, V3 = D;
4145 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4146 V1 = C, V2 = A, V3 = B;
4147
4148 if (V1) {
4149 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004150 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4151 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004153 }
4154 }
4155
4156 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4157 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4158 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4159 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4160 SI0->getOperand(1) == SI1->getOperand(1) &&
4161 (SI0->hasOneUse() || SI1->hasOneUse())) {
4162 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004163 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004164 SI1->getOperand(0),
4165 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004166 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004167 SI1->getOperand(1));
4168 }
4169 }
4170
4171 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4172 if (A == Op1) // ~A | A == -1
4173 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4174 } else {
4175 A = 0;
4176 }
4177 // Note, A is still live here!
4178 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4179 if (Op0 == B)
4180 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4181
4182 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4183 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004184 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004186 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004187 }
4188 }
4189
4190 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4191 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4192 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4193 return R;
4194
4195 Value *LHSVal, *RHSVal;
4196 ConstantInt *LHSCst, *RHSCst;
4197 ICmpInst::Predicate LHSCC, RHSCC;
4198 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4199 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4200 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4201 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4202 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4203 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4204 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4205 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4206 // We can't fold (ugt x, C) | (sgt x, C2).
4207 PredicatesFoldable(LHSCC, RHSCC)) {
4208 // Ensure that the larger constant is on the RHS.
4209 ICmpInst *LHS = cast<ICmpInst>(Op0);
4210 bool NeedsSwap;
Nick Lewycky5515c7a2008-09-30 06:08:34 +00004211 if (ICmpInst::isEquality(LHSCC) ? ICmpInst::isSignedPredicate(RHSCC)
4212 : ICmpInst::isSignedPredicate(LHSCC))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004213 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4214 else
4215 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4216
4217 if (NeedsSwap) {
4218 std::swap(LHS, RHS);
4219 std::swap(LHSCst, RHSCst);
4220 std::swap(LHSCC, RHSCC);
4221 }
4222
4223 // At this point, we know we have have two icmp instructions
4224 // comparing a value against two constants and or'ing the result
4225 // together. Because of the above check, we know that we only have
4226 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4227 // FoldICmpLogical check above), that the two constants are not
4228 // equal.
4229 assert(LHSCst != RHSCst && "Compares not folded above?");
4230
4231 switch (LHSCC) {
4232 default: assert(0 && "Unknown integer condition code!");
4233 case ICmpInst::ICMP_EQ:
4234 switch (RHSCC) {
4235 default: assert(0 && "Unknown integer condition code!");
4236 case ICmpInst::ICMP_EQ:
4237 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4238 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004239 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004240 LHSVal->getName()+".off");
4241 InsertNewInstBefore(Add, I);
4242 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4243 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4244 }
4245 break; // (X == 13 | X == 15) -> no change
4246 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4247 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4248 break;
4249 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4250 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4251 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4252 return ReplaceInstUsesWith(I, RHS);
4253 }
4254 break;
4255 case ICmpInst::ICMP_NE:
4256 switch (RHSCC) {
4257 default: assert(0 && "Unknown integer condition code!");
4258 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4259 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4260 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4261 return ReplaceInstUsesWith(I, LHS);
4262 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4263 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4264 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4265 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4266 }
4267 break;
4268 case ICmpInst::ICMP_ULT:
4269 switch (RHSCC) {
4270 default: assert(0 && "Unknown integer condition code!");
4271 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4272 break;
4273 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004274 // If RHSCst is [us]MAXINT, it is always false. Not handling
4275 // this can cause overflow.
4276 if (RHSCst->isMaxValue(false))
4277 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004278 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4279 false, I);
4280 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4281 break;
4282 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4283 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4284 return ReplaceInstUsesWith(I, RHS);
4285 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4286 break;
4287 }
4288 break;
4289 case ICmpInst::ICMP_SLT:
4290 switch (RHSCC) {
4291 default: assert(0 && "Unknown integer condition code!");
4292 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4293 break;
4294 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004295 // If RHSCst is [us]MAXINT, it is always false. Not handling
4296 // this can cause overflow.
4297 if (RHSCst->isMaxValue(true))
4298 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004299 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4300 false, I);
4301 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4302 break;
4303 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4304 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4305 return ReplaceInstUsesWith(I, RHS);
4306 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4307 break;
4308 }
4309 break;
4310 case ICmpInst::ICMP_UGT:
4311 switch (RHSCC) {
4312 default: assert(0 && "Unknown integer condition code!");
4313 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4314 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4315 return ReplaceInstUsesWith(I, LHS);
4316 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4317 break;
4318 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4319 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4320 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4321 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4322 break;
4323 }
4324 break;
4325 case ICmpInst::ICMP_SGT:
4326 switch (RHSCC) {
4327 default: assert(0 && "Unknown integer condition code!");
4328 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4329 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4330 return ReplaceInstUsesWith(I, LHS);
4331 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4332 break;
4333 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4334 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4335 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4336 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4337 break;
4338 }
4339 break;
4340 }
4341 }
4342 }
4343
4344 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004345 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004346 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4347 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004348 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4349 !isa<ICmpInst>(Op1C->getOperand(0))) {
4350 const Type *SrcTy = Op0C->getOperand(0)->getType();
4351 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4352 // Only do this if the casts both really cause code to be
4353 // generated.
4354 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4355 I.getType(), TD) &&
4356 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4357 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004358 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004359 Op1C->getOperand(0),
4360 I.getName());
4361 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004362 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004363 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004364 }
4365 }
Chris Lattner91882432007-10-24 05:38:08 +00004366 }
4367
4368
4369 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4370 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4371 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4372 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004373 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4374 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004375 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4376 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4377 // If either of the constants are nans, then the whole thing returns
4378 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004379 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004380 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4381
4382 // Otherwise, no need to compare the two constants, compare the
4383 // rest.
4384 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4385 RHS->getOperand(0));
4386 }
4387 }
4388 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004389
4390 return Changed ? &I : 0;
4391}
4392
Dan Gohman089efff2008-05-13 00:00:25 +00004393namespace {
4394
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395// XorSelf - Implements: X ^ X --> 0
4396struct XorSelf {
4397 Value *RHS;
4398 XorSelf(Value *rhs) : RHS(rhs) {}
4399 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4400 Instruction *apply(BinaryOperator &Xor) const {
4401 return &Xor;
4402 }
4403};
4404
Dan Gohman089efff2008-05-13 00:00:25 +00004405}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004406
4407Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4408 bool Changed = SimplifyCommutative(I);
4409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4410
Evan Chenge5cd8032008-03-25 20:07:13 +00004411 if (isa<UndefValue>(Op1)) {
4412 if (isa<UndefValue>(Op0))
4413 // Handle undef ^ undef -> 0 special case. This is a common
4414 // idiom (misuse).
4415 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004418
4419 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4420 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004421 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4423 }
4424
4425 // See if we can simplify any instructions used by the instruction whose sole
4426 // purpose is to compute bits we don't care about.
4427 if (!isa<VectorType>(I.getType())) {
4428 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4429 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4430 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4431 KnownZero, KnownOne))
4432 return &I;
4433 } else if (isa<ConstantAggregateZero>(Op1)) {
4434 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4435 }
4436
4437 // Is this a ~ operation?
4438 if (Value *NotOp = dyn_castNotVal(&I)) {
4439 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4440 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4441 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4442 if (Op0I->getOpcode() == Instruction::And ||
4443 Op0I->getOpcode() == Instruction::Or) {
4444 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4445 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4446 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004447 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004448 Op0I->getOperand(1)->getName()+".not");
4449 InsertNewInstBefore(NotY, I);
4450 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004451 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004452 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004453 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004454 }
4455 }
4456 }
4457 }
4458
4459
4460 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004461 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4462 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4463 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004464 return new ICmpInst(ICI->getInversePredicate(),
4465 ICI->getOperand(0), ICI->getOperand(1));
4466
Nick Lewycky1405e922007-08-06 20:04:16 +00004467 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4468 return new FCmpInst(FCI->getInversePredicate(),
4469 FCI->getOperand(0), FCI->getOperand(1));
4470 }
4471
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004472 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4473 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4474 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4475 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4476 Instruction::CastOps Opcode = Op0C->getOpcode();
4477 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4478 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4479 Op0C->getDestTy())) {
4480 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4481 CI->getOpcode(), CI->getInversePredicate(),
4482 CI->getOperand(0), CI->getOperand(1)), I);
4483 NewCI->takeName(CI);
4484 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4485 }
4486 }
4487 }
4488 }
4489 }
4490
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004491 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4492 // ~(c-X) == X-c-1 == X+(-c-1)
4493 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4494 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4495 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4496 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4497 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004498 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004499 }
4500
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004501 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004502 if (Op0I->getOpcode() == Instruction::Add) {
4503 // ~(X-c) --> (-c-1)-X
4504 if (RHS->isAllOnesValue()) {
4505 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004506 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004507 ConstantExpr::getSub(NegOp0CI,
4508 ConstantInt::get(I.getType(), 1)),
4509 Op0I->getOperand(0));
4510 } else if (RHS->getValue().isSignBit()) {
4511 // (X + C) ^ signbit -> (X + C + signbit)
4512 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004513 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004514
4515 }
4516 } else if (Op0I->getOpcode() == Instruction::Or) {
4517 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4518 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4519 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4520 // Anything in both C1 and C2 is known to be zero, remove it from
4521 // NewRHS.
4522 Constant *CommonBits = And(Op0CI, RHS);
4523 NewRHS = ConstantExpr::getAnd(NewRHS,
4524 ConstantExpr::getNot(CommonBits));
4525 AddToWorkList(Op0I);
4526 I.setOperand(0, Op0I->getOperand(0));
4527 I.setOperand(1, NewRHS);
4528 return &I;
4529 }
4530 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004531 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004532 }
4533
4534 // Try to fold constant and into select arguments.
4535 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4536 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4537 return R;
4538 if (isa<PHINode>(Op0))
4539 if (Instruction *NV = FoldOpIntoPhi(I))
4540 return NV;
4541 }
4542
4543 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4544 if (X == Op1)
4545 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4546
4547 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4548 if (X == Op0)
4549 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4550
4551
4552 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4553 if (Op1I) {
4554 Value *A, *B;
4555 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4556 if (A == Op0) { // B^(B|A) == (A|B)^B
4557 Op1I->swapOperands();
4558 I.swapOperands();
4559 std::swap(Op0, Op1);
4560 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4561 I.swapOperands(); // Simplified below.
4562 std::swap(Op0, Op1);
4563 }
4564 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4565 if (Op0 == A) // A^(A^B) == B
4566 return ReplaceInstUsesWith(I, B);
4567 else if (Op0 == B) // A^(B^A) == B
4568 return ReplaceInstUsesWith(I, A);
4569 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4570 if (A == Op0) { // A^(A&B) -> A^(B&A)
4571 Op1I->swapOperands();
4572 std::swap(A, B);
4573 }
4574 if (B == Op0) { // A^(B&A) -> (B&A)^A
4575 I.swapOperands(); // Simplified below.
4576 std::swap(Op0, Op1);
4577 }
4578 }
4579 }
4580
4581 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4582 if (Op0I) {
4583 Value *A, *B;
4584 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4585 if (A == Op1) // (B|A)^B == (A|B)^B
4586 std::swap(A, B);
4587 if (B == Op1) { // (A|B)^B == A & ~B
4588 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004589 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4590 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004591 }
4592 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4593 if (Op1 == A) // (A^B)^A == B
4594 return ReplaceInstUsesWith(I, B);
4595 else if (Op1 == B) // (B^A)^A == B
4596 return ReplaceInstUsesWith(I, A);
4597 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4598 if (A == Op1) // (A&B)^A -> (B&A)^A
4599 std::swap(A, B);
4600 if (B == Op1 && // (B&A)^A == ~B & A
4601 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4602 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004603 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4604 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004605 }
4606 }
4607 }
4608
4609 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4610 if (Op0I && Op1I && Op0I->isShift() &&
4611 Op0I->getOpcode() == Op1I->getOpcode() &&
4612 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4613 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4614 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004615 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004616 Op1I->getOperand(0),
4617 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004618 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004619 Op1I->getOperand(1));
4620 }
4621
4622 if (Op0I && Op1I) {
4623 Value *A, *B, *C, *D;
4624 // (A & B)^(A | B) -> A ^ B
4625 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4626 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4627 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004628 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004629 }
4630 // (A | B)^(A & B) -> A ^ B
4631 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4632 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4633 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004634 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004635 }
4636
4637 // (A & B)^(C & D)
4638 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4639 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4640 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4641 // (X & Y)^(X & Y) -> (Y^Z) & X
4642 Value *X = 0, *Y = 0, *Z = 0;
4643 if (A == C)
4644 X = A, Y = B, Z = D;
4645 else if (A == D)
4646 X = A, Y = B, Z = C;
4647 else if (B == C)
4648 X = B, Y = A, Z = D;
4649 else if (B == D)
4650 X = B, Y = A, Z = C;
4651
4652 if (X) {
4653 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004654 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4655 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004656 }
4657 }
4658 }
4659
4660 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4661 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4662 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4663 return R;
4664
4665 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004666 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004667 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4668 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4669 const Type *SrcTy = Op0C->getOperand(0)->getType();
4670 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4671 // Only do this if the casts both really cause code to be generated.
4672 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4673 I.getType(), TD) &&
4674 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4675 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004676 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004677 Op1C->getOperand(0),
4678 I.getName());
4679 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004680 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004681 }
4682 }
Chris Lattner91882432007-10-24 05:38:08 +00004683 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004684
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004685 return Changed ? &I : 0;
4686}
4687
4688/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4689/// overflowed for this type.
4690static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4691 ConstantInt *In2, bool IsSigned = false) {
4692 Result = cast<ConstantInt>(Add(In1, In2));
4693
4694 if (IsSigned)
4695 if (In2->getValue().isNegative())
4696 return Result->getValue().sgt(In1->getValue());
4697 else
4698 return Result->getValue().slt(In1->getValue());
4699 else
4700 return Result->getValue().ult(In1->getValue());
4701}
4702
Dan Gohmanb80d5612008-09-10 23:30:57 +00004703/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
4704/// overflowed for this type.
4705static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4706 ConstantInt *In2, bool IsSigned = false) {
Dan Gohman2c3b4892008-09-11 18:53:02 +00004707 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohmanb80d5612008-09-10 23:30:57 +00004708
4709 if (IsSigned)
4710 if (In2->getValue().isNegative())
4711 return Result->getValue().slt(In1->getValue());
4712 else
4713 return Result->getValue().sgt(In1->getValue());
4714 else
4715 return Result->getValue().ugt(In1->getValue());
4716}
4717
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004718/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4719/// code necessary to compute the offset from the base pointer (without adding
4720/// in the base pointer). Return the result as a signed integer of intptr size.
4721static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4722 TargetData &TD = IC.getTargetData();
4723 gep_type_iterator GTI = gep_type_begin(GEP);
4724 const Type *IntPtrTy = TD.getIntPtrType();
4725 Value *Result = Constant::getNullValue(IntPtrTy);
4726
4727 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004728 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004729 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4730
Gabor Greif17396002008-06-12 21:37:33 +00004731 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4732 ++i, ++GTI) {
4733 Value *Op = *i;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004734 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004735 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4736 if (OpC->isZero()) continue;
4737
4738 // Handle a struct index, which adds its field offset to the pointer.
4739 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4740 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4741
4742 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4743 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4744 else
4745 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004746 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004747 ConstantInt::get(IntPtrTy, Size),
4748 GEP->getName()+".offs"), I);
4749 continue;
4750 }
4751
4752 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4753 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4754 Scale = ConstantExpr::getMul(OC, Scale);
4755 if (Constant *RC = dyn_cast<Constant>(Result))
4756 Result = ConstantExpr::getAdd(RC, Scale);
4757 else {
4758 // Emit an add instruction.
4759 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004760 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004761 GEP->getName()+".offs"), I);
4762 }
4763 continue;
4764 }
4765 // Convert to correct type.
4766 if (Op->getType() != IntPtrTy) {
4767 if (Constant *OpC = dyn_cast<Constant>(Op))
4768 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4769 else
4770 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4771 Op->getName()+".c"), I);
4772 }
4773 if (Size != 1) {
4774 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4775 if (Constant *OpC = dyn_cast<Constant>(Op))
4776 Op = ConstantExpr::getMul(OpC, Scale);
4777 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00004778 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004779 GEP->getName()+".idx"), I);
4780 }
4781
4782 // Emit an add instruction.
4783 if (isa<Constant>(Op) && isa<Constant>(Result))
4784 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4785 cast<Constant>(Result));
4786 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004787 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004788 GEP->getName()+".offs"), I);
4789 }
4790 return Result;
4791}
4792
Chris Lattnereba75862008-04-22 02:53:33 +00004793
4794/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4795/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4796/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4797/// complex, and scales are involved. The above expression would also be legal
4798/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4799/// later form is less amenable to optimization though, and we are allowed to
4800/// generate the first by knowing that pointer arithmetic doesn't overflow.
4801///
4802/// If we can't emit an optimized form for this expression, this returns null.
4803///
4804static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4805 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00004806 TargetData &TD = IC.getTargetData();
4807 gep_type_iterator GTI = gep_type_begin(GEP);
4808
4809 // Check to see if this gep only has a single variable index. If so, and if
4810 // any constant indices are a multiple of its scale, then we can compute this
4811 // in terms of the scale of the variable index. For example, if the GEP
4812 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4813 // because the expression will cross zero at the same point.
4814 unsigned i, e = GEP->getNumOperands();
4815 int64_t Offset = 0;
4816 for (i = 1; i != e; ++i, ++GTI) {
4817 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4818 // Compute the aggregate offset of constant indices.
4819 if (CI->isZero()) continue;
4820
4821 // Handle a struct index, which adds its field offset to the pointer.
4822 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4823 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4824 } else {
4825 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4826 Offset += Size*CI->getSExtValue();
4827 }
4828 } else {
4829 // Found our variable index.
4830 break;
4831 }
4832 }
4833
4834 // If there are no variable indices, we must have a constant offset, just
4835 // evaluate it the general way.
4836 if (i == e) return 0;
4837
4838 Value *VariableIdx = GEP->getOperand(i);
4839 // Determine the scale factor of the variable element. For example, this is
4840 // 4 if the variable index is into an array of i32.
4841 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4842
4843 // Verify that there are no other variable indices. If so, emit the hard way.
4844 for (++i, ++GTI; i != e; ++i, ++GTI) {
4845 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4846 if (!CI) return 0;
4847
4848 // Compute the aggregate offset of constant indices.
4849 if (CI->isZero()) continue;
4850
4851 // Handle a struct index, which adds its field offset to the pointer.
4852 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4853 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4854 } else {
4855 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4856 Offset += Size*CI->getSExtValue();
4857 }
4858 }
4859
4860 // Okay, we know we have a single variable index, which must be a
4861 // pointer/array/vector index. If there is no offset, life is simple, return
4862 // the index.
4863 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4864 if (Offset == 0) {
4865 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4866 // we don't need to bother extending: the extension won't affect where the
4867 // computation crosses zero.
4868 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4869 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4870 VariableIdx->getNameStart(), &I);
4871 return VariableIdx;
4872 }
4873
4874 // Otherwise, there is an index. The computation we will do will be modulo
4875 // the pointer size, so get it.
4876 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4877
4878 Offset &= PtrSizeMask;
4879 VariableScale &= PtrSizeMask;
4880
4881 // To do this transformation, any constant index must be a multiple of the
4882 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4883 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4884 // multiple of the variable scale.
4885 int64_t NewOffs = Offset / (int64_t)VariableScale;
4886 if (Offset != NewOffs*(int64_t)VariableScale)
4887 return 0;
4888
4889 // Okay, we can do this evaluation. Start by converting the index to intptr.
4890 const Type *IntPtrTy = TD.getIntPtrType();
4891 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00004892 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00004893 true /*SExt*/,
4894 VariableIdx->getNameStart(), &I);
4895 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00004896 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00004897}
4898
4899
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004900/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4901/// else. At this point we know that the GEP is on the LHS of the comparison.
4902Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4903 ICmpInst::Predicate Cond,
4904 Instruction &I) {
4905 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4906
Chris Lattnereba75862008-04-22 02:53:33 +00004907 // Look through bitcasts.
4908 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4909 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004910
4911 Value *PtrBase = GEPLHS->getOperand(0);
4912 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004913 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00004914 // This transformation (ignoring the base and scales) is valid because we
4915 // know pointers can't overflow. See if we can output an optimized form.
4916 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4917
4918 // If not, synthesize the offset the hard way.
4919 if (Offset == 0)
4920 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00004921 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4922 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004923 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4924 // If the base pointers are different, but the indices are the same, just
4925 // compare the base pointer.
4926 if (PtrBase != GEPRHS->getOperand(0)) {
4927 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4928 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4929 GEPRHS->getOperand(0)->getType();
4930 if (IndicesTheSame)
4931 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4932 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4933 IndicesTheSame = false;
4934 break;
4935 }
4936
4937 // If all indices are the same, just compare the base pointers.
4938 if (IndicesTheSame)
4939 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4940 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4941
4942 // Otherwise, the base pointers are different and the indices are
4943 // different, bail out.
4944 return 0;
4945 }
4946
4947 // If one of the GEPs has all zero indices, recurse.
4948 bool AllZeros = true;
4949 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4950 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4951 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4952 AllZeros = false;
4953 break;
4954 }
4955 if (AllZeros)
4956 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4957 ICmpInst::getSwappedPredicate(Cond), I);
4958
4959 // If the other GEP has all zero indices, recurse.
4960 AllZeros = true;
4961 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4962 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4963 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4964 AllZeros = false;
4965 break;
4966 }
4967 if (AllZeros)
4968 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4969
4970 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4971 // If the GEPs only differ by one index, compare it.
4972 unsigned NumDifferences = 0; // Keep track of # differences.
4973 unsigned DiffOperand = 0; // The operand that differs.
4974 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4975 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4976 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4977 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4978 // Irreconcilable differences.
4979 NumDifferences = 2;
4980 break;
4981 } else {
4982 if (NumDifferences++) break;
4983 DiffOperand = i;
4984 }
4985 }
4986
4987 if (NumDifferences == 0) // SAME GEP?
4988 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004989 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00004990 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00004991
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004992 else if (NumDifferences == 1) {
4993 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4994 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4995 // Make sure we do a signed comparison here.
4996 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4997 }
4998 }
4999
5000 // Only lower this if the icmp is the only user of the GEP or if we expect
5001 // the result to fold to a constant!
5002 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5003 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5004 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5005 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5006 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5007 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5008 }
5009 }
5010 return 0;
5011}
5012
Chris Lattnere6b62d92008-05-19 20:18:56 +00005013/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5014///
5015Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5016 Instruction *LHSI,
5017 Constant *RHSC) {
5018 if (!isa<ConstantFP>(RHSC)) return 0;
5019 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5020
5021 // Get the width of the mantissa. We don't want to hack on conversions that
5022 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005023 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005024 if (MantissaWidth == -1) return 0; // Unknown.
5025
5026 // Check to see that the input is converted from an integer type that is small
5027 // enough that preserves all bits. TODO: check here for "known" sign bits.
5028 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5029 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5030
5031 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5032 if (isa<UIToFPInst>(LHSI))
5033 ++InputSize;
5034
5035 // If the conversion would lose info, don't hack on this.
5036 if ((int)InputSize > MantissaWidth)
5037 return 0;
5038
5039 // Otherwise, we can potentially simplify the comparison. We know that it
5040 // will always come through as an integer value and we know the constant is
5041 // not a NAN (it would have been previously simplified).
5042 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5043
5044 ICmpInst::Predicate Pred;
5045 switch (I.getPredicate()) {
5046 default: assert(0 && "Unexpected predicate!");
5047 case FCmpInst::FCMP_UEQ:
5048 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5049 case FCmpInst::FCMP_UGT:
5050 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5051 case FCmpInst::FCMP_UGE:
5052 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5053 case FCmpInst::FCMP_ULT:
5054 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5055 case FCmpInst::FCMP_ULE:
5056 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5057 case FCmpInst::FCMP_UNE:
5058 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5059 case FCmpInst::FCMP_ORD:
5060 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5061 case FCmpInst::FCMP_UNO:
5062 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5063 }
5064
5065 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5066
5067 // Now we know that the APFloat is a normal number, zero or inf.
5068
Chris Lattnerf13ff492008-05-20 03:50:52 +00005069 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005070 // comparing an i8 to 300.0.
5071 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5072
5073 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5074 // and large values.
5075 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5076 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5077 APFloat::rmNearestTiesToEven);
5078 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner82a80002008-05-24 04:06:28 +00005079 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5080 Pred == ICmpInst::ICMP_SLE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005081 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5082 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5083 }
5084
5085 // See if the RHS value is < SignedMin.
5086 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5087 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5088 APFloat::rmNearestTiesToEven);
5089 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner82a80002008-05-24 04:06:28 +00005090 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5091 Pred == ICmpInst::ICMP_SGE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005092 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5093 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5094 }
5095
5096 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5097 // it may still be fractional. See if it is fractional by casting the FP
5098 // value to the integer value and back, checking for equality. Don't do this
5099 // for zero, because -0.0 is not fractional.
5100 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5101 if (!RHS.isZero() &&
5102 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5103 // If we had a comparison against a fractional value, we have to adjust
5104 // the compare predicate and sometimes the value. RHSC is rounded towards
5105 // zero at this point.
5106 switch (Pred) {
5107 default: assert(0 && "Unexpected integer comparison!");
5108 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5109 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5110 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5111 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5112 case ICmpInst::ICMP_SLE:
5113 // (float)int <= 4.4 --> int <= 4
5114 // (float)int <= -4.4 --> int < -4
5115 if (RHS.isNegative())
5116 Pred = ICmpInst::ICMP_SLT;
5117 break;
5118 case ICmpInst::ICMP_SLT:
5119 // (float)int < -4.4 --> int < -4
5120 // (float)int < 4.4 --> int <= 4
5121 if (!RHS.isNegative())
5122 Pred = ICmpInst::ICMP_SLE;
5123 break;
5124 case ICmpInst::ICMP_SGT:
5125 // (float)int > 4.4 --> int > 4
5126 // (float)int > -4.4 --> int >= -4
5127 if (RHS.isNegative())
5128 Pred = ICmpInst::ICMP_SGE;
5129 break;
5130 case ICmpInst::ICMP_SGE:
5131 // (float)int >= -4.4 --> int >= -4
5132 // (float)int >= 4.4 --> int > 4
5133 if (!RHS.isNegative())
5134 Pred = ICmpInst::ICMP_SGT;
5135 break;
5136 }
5137 }
5138
5139 // Lower this FP comparison into an appropriate integer version of the
5140 // comparison.
5141 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5142}
5143
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005144Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5145 bool Changed = SimplifyCompare(I);
5146 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5147
5148 // Fold trivial predicates.
5149 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5150 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5151 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5152 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5153
5154 // Simplify 'fcmp pred X, X'
5155 if (Op0 == Op1) {
5156 switch (I.getPredicate()) {
5157 default: assert(0 && "Unknown predicate!");
5158 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5159 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5160 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5161 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5162 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5163 case FCmpInst::FCMP_OLT: // True if ordered and less than
5164 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5165 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5166
5167 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5168 case FCmpInst::FCMP_ULT: // True if unordered or less than
5169 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5170 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5171 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5172 I.setPredicate(FCmpInst::FCMP_UNO);
5173 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5174 return &I;
5175
5176 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5177 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5178 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5179 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5180 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5181 I.setPredicate(FCmpInst::FCMP_ORD);
5182 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5183 return &I;
5184 }
5185 }
5186
5187 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5188 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5189
5190 // Handle fcmp with constant RHS
5191 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005192 // If the constant is a nan, see if we can fold the comparison based on it.
5193 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5194 if (CFP->getValueAPF().isNaN()) {
5195 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5196 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005197 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5198 "Comparison must be either ordered or unordered!");
5199 // True if unordered.
5200 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005201 }
5202 }
5203
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005204 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5205 switch (LHSI->getOpcode()) {
5206 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005207 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5208 // block. If in the same block, we're encouraging jump threading. If
5209 // not, we are just pessimizing the code by making an i1 phi.
5210 if (LHSI->getParent() == I.getParent())
5211 if (Instruction *NV = FoldOpIntoPhi(I))
5212 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005213 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005214 case Instruction::SIToFP:
5215 case Instruction::UIToFP:
5216 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5217 return NV;
5218 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005219 case Instruction::Select:
5220 // If either operand of the select is a constant, we can fold the
5221 // comparison into the select arms, which will cause one to be
5222 // constant folded and the select turned into a bitwise or.
5223 Value *Op1 = 0, *Op2 = 0;
5224 if (LHSI->hasOneUse()) {
5225 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5226 // Fold the known value into the constant operand.
5227 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5228 // Insert a new FCmp of the other select operand.
5229 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5230 LHSI->getOperand(2), RHSC,
5231 I.getName()), I);
5232 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5233 // Fold the known value into the constant operand.
5234 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5235 // Insert a new FCmp of the other select operand.
5236 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5237 LHSI->getOperand(1), RHSC,
5238 I.getName()), I);
5239 }
5240 }
5241
5242 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005243 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005244 break;
5245 }
5246 }
5247
5248 return Changed ? &I : 0;
5249}
5250
5251Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5252 bool Changed = SimplifyCompare(I);
5253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5254 const Type *Ty = Op0->getType();
5255
5256 // icmp X, X
5257 if (Op0 == Op1)
5258 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005259 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005260
5261 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5262 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005263
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005264 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5265 // addresses never equal each other! We already know that Op0 != Op1.
5266 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5267 isa<ConstantPointerNull>(Op0)) &&
5268 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5269 isa<ConstantPointerNull>(Op1)))
5270 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005271 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005272
5273 // icmp's with boolean values can always be turned into bitwise operations
5274 if (Ty == Type::Int1Ty) {
5275 switch (I.getPredicate()) {
5276 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005277 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005278 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005279 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005280 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005281 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005282 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005283 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005284
5285 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005286 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005287 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005288 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00005289 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005290 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005291 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005292 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005293 case ICmpInst::ICMP_SGT:
5294 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005295 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005296 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5297 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5298 InsertNewInstBefore(Not, I);
5299 return BinaryOperator::CreateAnd(Not, Op0);
5300 }
5301 case ICmpInst::ICMP_UGE:
5302 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5303 // FALL THROUGH
5304 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005305 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005306 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005307 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005308 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005309 case ICmpInst::ICMP_SGE:
5310 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5311 // FALL THROUGH
5312 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5313 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5314 InsertNewInstBefore(Not, I);
5315 return BinaryOperator::CreateOr(Not, Op0);
5316 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005317 }
5318 }
5319
Dan Gohman58c09632008-09-16 18:46:06 +00005320 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3d816532008-07-11 04:09:09 +00005322 Value *A, *B;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005323
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005324 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5325 if (I.isEquality() && CI->isNullValue() &&
5326 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5327 // (icmp cond A B) if cond is equality
5328 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005329 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005330
Dan Gohman58c09632008-09-16 18:46:06 +00005331 // If we have an icmp le or icmp ge instruction, turn it into the
5332 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5333 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00005334 switch (I.getPredicate()) {
5335 default: break;
5336 case ICmpInst::ICMP_ULE:
5337 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5338 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5339 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5340 case ICmpInst::ICMP_SLE:
5341 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5342 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5343 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5344 case ICmpInst::ICMP_UGE:
5345 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5346 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5347 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5348 case ICmpInst::ICMP_SGE:
5349 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5350 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5351 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5352 }
5353
Chris Lattnera1308652008-07-11 05:40:05 +00005354 // See if we can fold the comparison based on range information we can get
5355 // by checking whether bits are known to be zero or one in the input.
5356 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5357 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5358
5359 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005360 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005361 bool UnusedBit;
5362 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5363
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005364 if (SimplifyDemandedBits(Op0,
5365 isSignBit ? APInt::getSignBit(BitWidth)
5366 : APInt::getAllOnesValue(BitWidth),
5367 KnownZero, KnownOne, 0))
5368 return &I;
5369
5370 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00005371 // in. Compute the Min, Max and RHS values based on the known bits. For the
5372 // EQ and NE we use unsigned values.
5373 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner62d0f232008-07-11 05:08:55 +00005374 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5375 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5376 else
5377 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5378
Chris Lattnera1308652008-07-11 05:40:05 +00005379 // If Min and Max are known to be the same, then SimplifyDemandedBits
5380 // figured out that the LHS is a constant. Just constant fold this now so
5381 // that code below can assume that Min != Max.
5382 if (Min == Max)
5383 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5384 ConstantInt::get(Min),
5385 CI));
5386
5387 // Based on the range information we know about the LHS, see if we can
5388 // simplify this comparison. For example, (x&4) < 8 is always true.
5389 const APInt &RHSVal = CI->getValue();
Chris Lattner62d0f232008-07-11 05:08:55 +00005390 switch (I.getPredicate()) { // LE/GE have been folded already.
5391 default: assert(0 && "Unknown icmp opcode!");
5392 case ICmpInst::ICMP_EQ:
5393 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5394 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5395 break;
5396 case ICmpInst::ICMP_NE:
5397 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5398 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5399 break;
5400 case ICmpInst::ICMP_ULT:
Chris Lattnera1308652008-07-11 05:40:05 +00005401 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005402 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005403 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005404 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005405 if (RHSVal == Max) // A <u MAX -> A != MAX
5406 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5407 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5408 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5409
5410 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5411 if (CI->isMinValue(true))
5412 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5413 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005414 break;
5415 case ICmpInst::ICMP_UGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005416 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005417 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005418 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005419 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005420
5421 if (RHSVal == Min) // A >u MIN -> A != MIN
5422 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5423 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5424 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5425
5426 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5427 if (CI->isMaxValue(true))
5428 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5429 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005430 break;
5431 case ICmpInst::ICMP_SLT:
Chris Lattnera1308652008-07-11 05:40:05 +00005432 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005433 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner611b43e2008-07-11 06:40:29 +00005434 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005435 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005436 if (RHSVal == Max) // A <s MAX -> A != MAX
5437 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattner3496f3e2008-07-11 06:36:01 +00005438 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattner55ab3152008-07-11 06:38:16 +00005439 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005440 break;
5441 case ICmpInst::ICMP_SGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005442 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005443 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005444 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005445 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005446
5447 if (RHSVal == Min) // A >s MIN -> A != MIN
5448 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5449 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5450 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005451 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005452 }
Dan Gohman58c09632008-09-16 18:46:06 +00005453 }
5454
5455 // Test if the ICmpInst instruction is used exclusively by a select as
5456 // part of a minimum or maximum operation. If so, refrain from doing
5457 // any other folding. This helps out other analyses which understand
5458 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5459 // and CodeGen. And in this case, at least one of the comparison
5460 // operands has at least one user besides the compare (the select),
5461 // which would often largely negate the benefit of folding anyway.
5462 if (I.hasOneUse())
5463 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5464 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5465 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5466 return 0;
5467
5468 // See if we are doing a comparison between a constant and an instruction that
5469 // can be folded into the comparison.
5470 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005471 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5472 // instruction, see if that instruction also has constants so that the
5473 // instruction can be folded into the icmp
5474 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5475 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5476 return Res;
5477 }
5478
5479 // Handle icmp with constant (but not simple integer constant) RHS
5480 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5481 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5482 switch (LHSI->getOpcode()) {
5483 case Instruction::GetElementPtr:
5484 if (RHSC->isNullValue()) {
5485 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5486 bool isAllZeros = true;
5487 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5488 if (!isa<Constant>(LHSI->getOperand(i)) ||
5489 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5490 isAllZeros = false;
5491 break;
5492 }
5493 if (isAllZeros)
5494 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5495 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5496 }
5497 break;
5498
5499 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005500 // Only fold icmp into the PHI if the phi and fcmp are in the same
5501 // block. If in the same block, we're encouraging jump threading. If
5502 // not, we are just pessimizing the code by making an i1 phi.
5503 if (LHSI->getParent() == I.getParent())
5504 if (Instruction *NV = FoldOpIntoPhi(I))
5505 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005506 break;
5507 case Instruction::Select: {
5508 // If either operand of the select is a constant, we can fold the
5509 // comparison into the select arms, which will cause one to be
5510 // constant folded and the select turned into a bitwise or.
5511 Value *Op1 = 0, *Op2 = 0;
5512 if (LHSI->hasOneUse()) {
5513 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5514 // Fold the known value into the constant operand.
5515 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5516 // Insert a new ICmp of the other select operand.
5517 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5518 LHSI->getOperand(2), RHSC,
5519 I.getName()), I);
5520 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5521 // Fold the known value into the constant operand.
5522 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5523 // Insert a new ICmp of the other select operand.
5524 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5525 LHSI->getOperand(1), RHSC,
5526 I.getName()), I);
5527 }
5528 }
5529
5530 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005531 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005532 break;
5533 }
5534 case Instruction::Malloc:
5535 // If we have (malloc != null), and if the malloc has a single use, we
5536 // can assume it is successful and remove the malloc.
5537 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5538 AddToWorkList(LHSI);
5539 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005540 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005541 }
5542 break;
5543 }
5544 }
5545
5546 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5547 if (User *GEP = dyn_castGetElementPtr(Op0))
5548 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5549 return NI;
5550 if (User *GEP = dyn_castGetElementPtr(Op1))
5551 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5552 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5553 return NI;
5554
5555 // Test to see if the operands of the icmp are casted versions of other
5556 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5557 // now.
5558 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5559 if (isa<PointerType>(Op0->getType()) &&
5560 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5561 // We keep moving the cast from the left operand over to the right
5562 // operand, where it can often be eliminated completely.
5563 Op0 = CI->getOperand(0);
5564
5565 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5566 // so eliminate it as well.
5567 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5568 Op1 = CI2->getOperand(0);
5569
5570 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005571 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005572 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5573 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5574 } else {
5575 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005576 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005577 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005578 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005579 return new ICmpInst(I.getPredicate(), Op0, Op1);
5580 }
5581 }
5582
5583 if (isa<CastInst>(Op0)) {
5584 // Handle the special case of: icmp (cast bool to X), <cst>
5585 // This comes up when you have code like
5586 // int X = A < B;
5587 // if (X) ...
5588 // For generality, we handle any zero-extension of any operand comparison
5589 // with a constant or another cast from the same type.
5590 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5591 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5592 return R;
5593 }
5594
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005595 // See if it's the same type of instruction on the left and right.
5596 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5597 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005598 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5599 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5600 I.isEquality()) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00005601 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005602 default: break;
5603 case Instruction::Add:
5604 case Instruction::Sub:
5605 case Instruction::Xor:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005606 // a+x icmp eq/ne b+x --> a icmp b
5607 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5608 Op1I->getOperand(0));
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005609 break;
5610 case Instruction::Mul:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005611 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5612 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5613 // Mask = -1 >> count-trailing-zeros(Cst).
5614 if (!CI->isZero() && !CI->isOne()) {
5615 const APInt &AP = CI->getValue();
5616 ConstantInt *Mask = ConstantInt::get(
5617 APInt::getLowBitsSet(AP.getBitWidth(),
5618 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005619 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005620 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5621 Mask);
5622 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5623 Mask);
5624 InsertNewInstBefore(And1, I);
5625 InsertNewInstBefore(And2, I);
5626 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005627 }
5628 }
5629 break;
5630 }
5631 }
5632 }
5633 }
5634
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005635 // ~x < ~y --> y < x
5636 { Value *A, *B;
5637 if (match(Op0, m_Not(m_Value(A))) &&
5638 match(Op1, m_Not(m_Value(B))))
5639 return new ICmpInst(I.getPredicate(), B, A);
5640 }
5641
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005642 if (I.isEquality()) {
5643 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005644
5645 // -x == -y --> x == y
5646 if (match(Op0, m_Neg(m_Value(A))) &&
5647 match(Op1, m_Neg(m_Value(B))))
5648 return new ICmpInst(I.getPredicate(), A, B);
5649
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005650 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5651 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5652 Value *OtherVal = A == Op1 ? B : A;
5653 return new ICmpInst(I.getPredicate(), OtherVal,
5654 Constant::getNullValue(A->getType()));
5655 }
5656
5657 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5658 // A^c1 == C^c2 --> A == C^(c1^c2)
5659 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5660 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5661 if (Op1->hasOneUse()) {
5662 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005663 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005664 return new ICmpInst(I.getPredicate(), A,
5665 InsertNewInstBefore(Xor, I));
5666 }
5667
5668 // A^B == A^D -> B == D
5669 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5670 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5671 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5672 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5673 }
5674 }
5675
5676 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5677 (A == Op0 || B == Op0)) {
5678 // A == (A^B) -> B == 0
5679 Value *OtherVal = A == Op0 ? B : A;
5680 return new ICmpInst(I.getPredicate(), OtherVal,
5681 Constant::getNullValue(A->getType()));
5682 }
5683 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5684 // (A-B) == A -> B == 0
5685 return new ICmpInst(I.getPredicate(), B,
5686 Constant::getNullValue(B->getType()));
5687 }
5688 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5689 // A == (A-B) -> B == 0
5690 return new ICmpInst(I.getPredicate(), B,
5691 Constant::getNullValue(B->getType()));
5692 }
5693
5694 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5695 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5696 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5697 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5698 Value *X = 0, *Y = 0, *Z = 0;
5699
5700 if (A == C) {
5701 X = B; Y = D; Z = A;
5702 } else if (A == D) {
5703 X = B; Y = C; Z = A;
5704 } else if (B == C) {
5705 X = A; Y = D; Z = B;
5706 } else if (B == D) {
5707 X = A; Y = C; Z = B;
5708 }
5709
5710 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005711 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5712 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005713 I.setOperand(0, Op1);
5714 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5715 return &I;
5716 }
5717 }
5718 }
5719 return Changed ? &I : 0;
5720}
5721
5722
5723/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5724/// and CmpRHS are both known to be integer constants.
5725Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5726 ConstantInt *DivRHS) {
5727 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5728 const APInt &CmpRHSV = CmpRHS->getValue();
5729
5730 // FIXME: If the operand types don't match the type of the divide
5731 // then don't attempt this transform. The code below doesn't have the
5732 // logic to deal with a signed divide and an unsigned compare (and
5733 // vice versa). This is because (x /s C1) <s C2 produces different
5734 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5735 // (x /u C1) <u C2. Simply casting the operands and result won't
5736 // work. :( The if statement below tests that condition and bails
5737 // if it finds it.
5738 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5739 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5740 return 0;
5741 if (DivRHS->isZero())
5742 return 0; // The ProdOV computation fails on divide by zero.
5743
5744 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5745 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5746 // C2 (CI). By solving for X we can turn this into a range check
5747 // instead of computing a divide.
5748 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5749
5750 // Determine if the product overflows by seeing if the product is
5751 // not equal to the divide. Make sure we do the same kind of divide
5752 // as in the LHS instruction that we're folding.
5753 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5754 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5755
5756 // Get the ICmp opcode
5757 ICmpInst::Predicate Pred = ICI.getPredicate();
5758
5759 // Figure out the interval that is being checked. For example, a comparison
5760 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5761 // Compute this interval based on the constants involved and the signedness of
5762 // the compare/divide. This computes a half-open interval, keeping track of
5763 // whether either value in the interval overflows. After analysis each
5764 // overflow variable is set to 0 if it's corresponding bound variable is valid
5765 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5766 int LoOverflow = 0, HiOverflow = 0;
5767 ConstantInt *LoBound = 0, *HiBound = 0;
5768
5769
5770 if (!DivIsSigned) { // udiv
5771 // e.g. X/5 op 3 --> [15, 20)
5772 LoBound = Prod;
5773 HiOverflow = LoOverflow = ProdOV;
5774 if (!HiOverflow)
5775 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005776 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005777 if (CmpRHSV == 0) { // (X / pos) op 0
5778 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5779 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5780 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005781 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005782 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5783 HiOverflow = LoOverflow = ProdOV;
5784 if (!HiOverflow)
5785 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5786 } else { // (X / pos) op neg
5787 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5788 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5789 LoOverflow = AddWithOverflow(LoBound, Prod,
5790 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5791 HiBound = AddOne(Prod);
5792 HiOverflow = ProdOV ? -1 : 0;
5793 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005794 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005795 if (CmpRHSV == 0) { // (X / neg) op 0
5796 // e.g. X/-5 op 0 --> [-4, 5)
5797 LoBound = AddOne(DivRHS);
5798 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5799 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5800 HiOverflow = 1; // [INTMIN+1, overflow)
5801 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5802 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005803 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005804 // e.g. X/-5 op 3 --> [-19, -14)
5805 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5806 if (!LoOverflow)
5807 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5808 HiBound = AddOne(Prod);
5809 } else { // (X / neg) op neg
5810 // e.g. X/-5 op -3 --> [15, 20)
5811 LoBound = Prod;
5812 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Dan Gohman45408ea2008-09-11 00:25:00 +00005813 if (!HiOverflow)
5814 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005815 }
5816
5817 // Dividing by a negative swaps the condition. LT <-> GT
5818 Pred = ICmpInst::getSwappedPredicate(Pred);
5819 }
5820
5821 Value *X = DivI->getOperand(0);
5822 switch (Pred) {
5823 default: assert(0 && "Unhandled icmp opcode!");
5824 case ICmpInst::ICMP_EQ:
5825 if (LoOverflow && HiOverflow)
5826 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5827 else if (HiOverflow)
5828 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5829 ICmpInst::ICMP_UGE, X, LoBound);
5830 else if (LoOverflow)
5831 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5832 ICmpInst::ICMP_ULT, X, HiBound);
5833 else
5834 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5835 case ICmpInst::ICMP_NE:
5836 if (LoOverflow && HiOverflow)
5837 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5838 else if (HiOverflow)
5839 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5840 ICmpInst::ICMP_ULT, X, LoBound);
5841 else if (LoOverflow)
5842 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5843 ICmpInst::ICMP_UGE, X, HiBound);
5844 else
5845 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5846 case ICmpInst::ICMP_ULT:
5847 case ICmpInst::ICMP_SLT:
5848 if (LoOverflow == +1) // Low bound is greater than input range.
5849 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5850 if (LoOverflow == -1) // Low bound is less than input range.
5851 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5852 return new ICmpInst(Pred, X, LoBound);
5853 case ICmpInst::ICMP_UGT:
5854 case ICmpInst::ICMP_SGT:
5855 if (HiOverflow == +1) // High bound greater than input range.
5856 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5857 else if (HiOverflow == -1) // High bound less than input range.
5858 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5859 if (Pred == ICmpInst::ICMP_UGT)
5860 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5861 else
5862 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5863 }
5864}
5865
5866
5867/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5868///
5869Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5870 Instruction *LHSI,
5871 ConstantInt *RHS) {
5872 const APInt &RHSV = RHS->getValue();
5873
5874 switch (LHSI->getOpcode()) {
5875 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5876 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5877 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5878 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005879 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5880 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005881 Value *CompareVal = LHSI->getOperand(0);
5882
5883 // If the sign bit of the XorCST is not set, there is no change to
5884 // the operation, just stop using the Xor.
5885 if (!XorCST->getValue().isNegative()) {
5886 ICI.setOperand(0, CompareVal);
5887 AddToWorkList(LHSI);
5888 return &ICI;
5889 }
5890
5891 // Was the old condition true if the operand is positive?
5892 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5893
5894 // If so, the new one isn't.
5895 isTrueIfPositive ^= true;
5896
5897 if (isTrueIfPositive)
5898 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5899 else
5900 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5901 }
5902 }
5903 break;
5904 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5905 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5906 LHSI->getOperand(0)->hasOneUse()) {
5907 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5908
5909 // If the LHS is an AND of a truncating cast, we can widen the
5910 // and/compare to be the input width without changing the value
5911 // produced, eliminating a cast.
5912 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5913 // We can do this transformation if either the AND constant does not
5914 // have its sign bit set or if it is an equality comparison.
5915 // Extending a relational comparison when we're checking the sign
5916 // bit would not work.
5917 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005918 (ICI.isEquality() ||
5919 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005920 uint32_t BitWidth =
5921 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5922 APInt NewCST = AndCST->getValue();
5923 NewCST.zext(BitWidth);
5924 APInt NewCI = RHSV;
5925 NewCI.zext(BitWidth);
5926 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005927 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005928 ConstantInt::get(NewCST),LHSI->getName());
5929 InsertNewInstBefore(NewAnd, ICI);
5930 return new ICmpInst(ICI.getPredicate(), NewAnd,
5931 ConstantInt::get(NewCI));
5932 }
5933 }
5934
5935 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5936 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5937 // happens a LOT in code produced by the C front-end, for bitfield
5938 // access.
5939 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5940 if (Shift && !Shift->isShift())
5941 Shift = 0;
5942
5943 ConstantInt *ShAmt;
5944 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5945 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5946 const Type *AndTy = AndCST->getType(); // Type of the and.
5947
5948 // We can fold this as long as we can't shift unknown bits
5949 // into the mask. This can only happen with signed shift
5950 // rights, as they sign-extend.
5951 if (ShAmt) {
5952 bool CanFold = Shift->isLogicalShift();
5953 if (!CanFold) {
5954 // To test for the bad case of the signed shr, see if any
5955 // of the bits shifted in could be tested after the mask.
5956 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5957 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5958
5959 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5960 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5961 AndCST->getValue()) == 0)
5962 CanFold = true;
5963 }
5964
5965 if (CanFold) {
5966 Constant *NewCst;
5967 if (Shift->getOpcode() == Instruction::Shl)
5968 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5969 else
5970 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5971
5972 // Check to see if we are shifting out any of the bits being
5973 // compared.
5974 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5975 // If we shifted bits out, the fold is not going to work out.
5976 // As a special case, check to see if this means that the
5977 // result is always true or false now.
5978 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5979 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5980 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5981 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5982 } else {
5983 ICI.setOperand(1, NewCst);
5984 Constant *NewAndCST;
5985 if (Shift->getOpcode() == Instruction::Shl)
5986 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5987 else
5988 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5989 LHSI->setOperand(1, NewAndCST);
5990 LHSI->setOperand(0, Shift->getOperand(0));
5991 AddToWorkList(Shift); // Shift is dead.
5992 AddUsesToWorkList(ICI);
5993 return &ICI;
5994 }
5995 }
5996 }
5997
5998 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5999 // preferable because it allows the C<<Y expression to be hoisted out
6000 // of a loop if Y is invariant and X is not.
6001 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6002 ICI.isEquality() && !Shift->isArithmeticShift() &&
6003 isa<Instruction>(Shift->getOperand(0))) {
6004 // Compute C << Y.
6005 Value *NS;
6006 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006007 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006008 Shift->getOperand(1), "tmp");
6009 } else {
6010 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006011 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006012 Shift->getOperand(1), "tmp");
6013 }
6014 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6015
6016 // Compute X & (C << Y).
6017 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006018 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006019 InsertNewInstBefore(NewAnd, ICI);
6020
6021 ICI.setOperand(0, NewAnd);
6022 return &ICI;
6023 }
6024 }
6025 break;
6026
6027 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6028 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6029 if (!ShAmt) break;
6030
6031 uint32_t TypeBits = RHSV.getBitWidth();
6032
6033 // Check that the shift amount is in range. If not, don't perform
6034 // undefined shifts. When the shift is visited it will be
6035 // simplified.
6036 if (ShAmt->uge(TypeBits))
6037 break;
6038
6039 if (ICI.isEquality()) {
6040 // If we are comparing against bits always shifted out, the
6041 // comparison cannot succeed.
6042 Constant *Comp =
6043 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6044 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6045 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6046 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6047 return ReplaceInstUsesWith(ICI, Cst);
6048 }
6049
6050 if (LHSI->hasOneUse()) {
6051 // Otherwise strength reduce the shift into an and.
6052 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6053 Constant *Mask =
6054 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6055
6056 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006057 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006058 Mask, LHSI->getName()+".mask");
6059 Value *And = InsertNewInstBefore(AndI, ICI);
6060 return new ICmpInst(ICI.getPredicate(), And,
6061 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6062 }
6063 }
6064
6065 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6066 bool TrueIfSigned = false;
6067 if (LHSI->hasOneUse() &&
6068 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6069 // (X << 31) <s 0 --> (X&1) != 0
6070 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6071 (TypeBits-ShAmt->getZExtValue()-1));
6072 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006073 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006074 Mask, LHSI->getName()+".mask");
6075 Value *And = InsertNewInstBefore(AndI, ICI);
6076
6077 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6078 And, Constant::getNullValue(And->getType()));
6079 }
6080 break;
6081 }
6082
6083 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6084 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006085 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006086 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006087 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006088
Chris Lattner5ee84f82008-03-21 05:19:58 +00006089 // Check that the shift amount is in range. If not, don't perform
6090 // undefined shifts. When the shift is visited it will be
6091 // simplified.
6092 uint32_t TypeBits = RHSV.getBitWidth();
6093 if (ShAmt->uge(TypeBits))
6094 break;
6095
6096 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006097
Chris Lattner5ee84f82008-03-21 05:19:58 +00006098 // If we are comparing against bits always shifted out, the
6099 // comparison cannot succeed.
6100 APInt Comp = RHSV << ShAmtVal;
6101 if (LHSI->getOpcode() == Instruction::LShr)
6102 Comp = Comp.lshr(ShAmtVal);
6103 else
6104 Comp = Comp.ashr(ShAmtVal);
6105
6106 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6107 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6108 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6109 return ReplaceInstUsesWith(ICI, Cst);
6110 }
6111
6112 // Otherwise, check to see if the bits shifted out are known to be zero.
6113 // If so, we can compare against the unshifted value:
6114 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006115 if (LHSI->hasOneUse() &&
6116 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006117 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6118 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6119 ConstantExpr::getShl(RHS, ShAmt));
6120 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006121
Evan Chengfb9292a2008-04-23 00:38:06 +00006122 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006123 // Otherwise strength reduce the shift into an and.
6124 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6125 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006126
Chris Lattner5ee84f82008-03-21 05:19:58 +00006127 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006128 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006129 Mask, LHSI->getName()+".mask");
6130 Value *And = InsertNewInstBefore(AndI, ICI);
6131 return new ICmpInst(ICI.getPredicate(), And,
6132 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006133 }
6134 break;
6135 }
6136
6137 case Instruction::SDiv:
6138 case Instruction::UDiv:
6139 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6140 // Fold this div into the comparison, producing a range check.
6141 // Determine, based on the divide type, what the range is being
6142 // checked. If there is an overflow on the low or high side, remember
6143 // it, otherwise compute the range [low, hi) bounding the new value.
6144 // See: InsertRangeTest above for the kinds of replacements possible.
6145 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6146 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6147 DivRHS))
6148 return R;
6149 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006150
6151 case Instruction::Add:
6152 // Fold: icmp pred (add, X, C1), C2
6153
6154 if (!ICI.isEquality()) {
6155 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6156 if (!LHSC) break;
6157 const APInt &LHSV = LHSC->getValue();
6158
6159 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6160 .subtract(LHSV);
6161
6162 if (ICI.isSignedPredicate()) {
6163 if (CR.getLower().isSignBit()) {
6164 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6165 ConstantInt::get(CR.getUpper()));
6166 } else if (CR.getUpper().isSignBit()) {
6167 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6168 ConstantInt::get(CR.getLower()));
6169 }
6170 } else {
6171 if (CR.getLower().isMinValue()) {
6172 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6173 ConstantInt::get(CR.getUpper()));
6174 } else if (CR.getUpper().isMinValue()) {
6175 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6176 ConstantInt::get(CR.getLower()));
6177 }
6178 }
6179 }
6180 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006181 }
6182
6183 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6184 if (ICI.isEquality()) {
6185 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6186
6187 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6188 // the second operand is a constant, simplify a bit.
6189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6190 switch (BO->getOpcode()) {
6191 case Instruction::SRem:
6192 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6193 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6194 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6195 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6196 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006197 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006198 BO->getName());
6199 InsertNewInstBefore(NewRem, ICI);
6200 return new ICmpInst(ICI.getPredicate(), NewRem,
6201 Constant::getNullValue(BO->getType()));
6202 }
6203 }
6204 break;
6205 case Instruction::Add:
6206 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6207 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6208 if (BO->hasOneUse())
6209 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6210 Subtract(RHS, BOp1C));
6211 } else if (RHSV == 0) {
6212 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6213 // efficiently invertible, or if the add has just this one use.
6214 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6215
6216 if (Value *NegVal = dyn_castNegVal(BOp1))
6217 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6218 else if (Value *NegVal = dyn_castNegVal(BOp0))
6219 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6220 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006221 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006222 InsertNewInstBefore(Neg, ICI);
6223 Neg->takeName(BO);
6224 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6225 }
6226 }
6227 break;
6228 case Instruction::Xor:
6229 // For the xor case, we can xor two constants together, eliminating
6230 // the explicit xor.
6231 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6232 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6233 ConstantExpr::getXor(RHS, BOC));
6234
6235 // FALLTHROUGH
6236 case Instruction::Sub:
6237 // Replace (([sub|xor] A, B) != 0) with (A != B)
6238 if (RHSV == 0)
6239 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6240 BO->getOperand(1));
6241 break;
6242
6243 case Instruction::Or:
6244 // If bits are being or'd in that are not present in the constant we
6245 // are comparing against, then the comparison could never succeed!
6246 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6247 Constant *NotCI = ConstantExpr::getNot(RHS);
6248 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6249 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6250 isICMP_NE));
6251 }
6252 break;
6253
6254 case Instruction::And:
6255 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6256 // If bits are being compared against that are and'd out, then the
6257 // comparison can never succeed!
6258 if ((RHSV & ~BOC->getValue()) != 0)
6259 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6260 isICMP_NE));
6261
6262 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6263 if (RHS == BOC && RHSV.isPowerOf2())
6264 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6265 ICmpInst::ICMP_NE, LHSI,
6266 Constant::getNullValue(RHS->getType()));
6267
6268 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00006269 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006270 Value *X = BO->getOperand(0);
6271 Constant *Zero = Constant::getNullValue(X->getType());
6272 ICmpInst::Predicate pred = isICMP_NE ?
6273 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6274 return new ICmpInst(pred, X, Zero);
6275 }
6276
6277 // ((X & ~7) == 0) --> X < 8
6278 if (RHSV == 0 && isHighOnes(BOC)) {
6279 Value *X = BO->getOperand(0);
6280 Constant *NegX = ConstantExpr::getNeg(BOC);
6281 ICmpInst::Predicate pred = isICMP_NE ?
6282 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6283 return new ICmpInst(pred, X, NegX);
6284 }
6285 }
6286 default: break;
6287 }
6288 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6289 // Handle icmp {eq|ne} <intrinsic>, intcst.
6290 if (II->getIntrinsicID() == Intrinsic::bswap) {
6291 AddToWorkList(II);
6292 ICI.setOperand(0, II->getOperand(1));
6293 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6294 return &ICI;
6295 }
6296 }
6297 } else { // Not a ICMP_EQ/ICMP_NE
6298 // If the LHS is a cast from an integral value of the same size,
6299 // then since we know the RHS is a constant, try to simlify.
6300 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6301 Value *CastOp = Cast->getOperand(0);
6302 const Type *SrcTy = CastOp->getType();
6303 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6304 if (SrcTy->isInteger() &&
6305 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6306 // If this is an unsigned comparison, try to make the comparison use
6307 // smaller constant values.
6308 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6309 // X u< 128 => X s> -1
6310 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6311 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6312 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6313 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6314 // X u> 127 => X s< 0
6315 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6316 Constant::getNullValue(SrcTy));
6317 }
6318 }
6319 }
6320 }
6321 return 0;
6322}
6323
6324/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6325/// We only handle extending casts so far.
6326///
6327Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6328 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6329 Value *LHSCIOp = LHSCI->getOperand(0);
6330 const Type *SrcTy = LHSCIOp->getType();
6331 const Type *DestTy = LHSCI->getType();
6332 Value *RHSCIOp;
6333
6334 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6335 // integer type is the same size as the pointer type.
6336 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6337 getTargetData().getPointerSizeInBits() ==
6338 cast<IntegerType>(DestTy)->getBitWidth()) {
6339 Value *RHSOp = 0;
6340 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6341 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6342 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6343 RHSOp = RHSC->getOperand(0);
6344 // If the pointer types don't match, insert a bitcast.
6345 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006346 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006347 }
6348
6349 if (RHSOp)
6350 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6351 }
6352
6353 // The code below only handles extension cast instructions, so far.
6354 // Enforce this.
6355 if (LHSCI->getOpcode() != Instruction::ZExt &&
6356 LHSCI->getOpcode() != Instruction::SExt)
6357 return 0;
6358
6359 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6360 bool isSignedCmp = ICI.isSignedPredicate();
6361
6362 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6363 // Not an extension from the same type?
6364 RHSCIOp = CI->getOperand(0);
6365 if (RHSCIOp->getType() != LHSCIOp->getType())
6366 return 0;
6367
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006368 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006369 // and the other is a zext), then we can't handle this.
6370 if (CI->getOpcode() != LHSCI->getOpcode())
6371 return 0;
6372
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006373 // Deal with equality cases early.
6374 if (ICI.isEquality())
6375 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6376
6377 // A signed comparison of sign extended values simplifies into a
6378 // signed comparison.
6379 if (isSignedCmp && isSignedExt)
6380 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6381
6382 // The other three cases all fold into an unsigned comparison.
6383 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006384 }
6385
6386 // If we aren't dealing with a constant on the RHS, exit early
6387 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6388 if (!CI)
6389 return 0;
6390
6391 // Compute the constant that would happen if we truncated to SrcTy then
6392 // reextended to DestTy.
6393 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6394 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6395
6396 // If the re-extended constant didn't change...
6397 if (Res2 == CI) {
6398 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6399 // For example, we might have:
6400 // %A = sext short %X to uint
6401 // %B = icmp ugt uint %A, 1330
6402 // It is incorrect to transform this into
6403 // %B = icmp ugt short %X, 1330
6404 // because %A may have negative value.
6405 //
Chris Lattner3d816532008-07-11 04:09:09 +00006406 // However, we allow this when the compare is EQ/NE, because they are
6407 // signless.
6408 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006409 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00006410 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006411 }
6412
6413 // The re-extended constant changed so the constant cannot be represented
6414 // in the shorter type. Consequently, we cannot emit a simple comparison.
6415
6416 // First, handle some easy cases. We know the result cannot be equal at this
6417 // point so handle the ICI.isEquality() cases
6418 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6419 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6420 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6421 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6422
6423 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6424 // should have been folded away previously and not enter in here.
6425 Value *Result;
6426 if (isSignedCmp) {
6427 // We're performing a signed comparison.
6428 if (cast<ConstantInt>(CI)->getValue().isNegative())
6429 Result = ConstantInt::getFalse(); // X < (small) --> false
6430 else
6431 Result = ConstantInt::getTrue(); // X < (large) --> true
6432 } else {
6433 // We're performing an unsigned comparison.
6434 if (isSignedExt) {
6435 // We're performing an unsigned comp with a sign extended value.
6436 // This is true if the input is >= 0. [aka >s -1]
6437 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6438 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6439 NegOne, ICI.getName()), ICI);
6440 } else {
6441 // Unsigned extend & unsigned compare -> always true.
6442 Result = ConstantInt::getTrue();
6443 }
6444 }
6445
6446 // Finally, return the value computed.
6447 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00006448 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006449 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00006450
6451 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6452 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6453 "ICmp should be folded!");
6454 if (Constant *CI = dyn_cast<Constant>(Result))
6455 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6456 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006457}
6458
6459Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6460 return commonShiftTransforms(I);
6461}
6462
6463Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6464 return commonShiftTransforms(I);
6465}
6466
6467Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006468 if (Instruction *R = commonShiftTransforms(I))
6469 return R;
6470
6471 Value *Op0 = I.getOperand(0);
6472
6473 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6474 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6475 if (CSI->isAllOnesValue())
6476 return ReplaceInstUsesWith(I, CSI);
6477
6478 // See if we can turn a signed shr into an unsigned shr.
Nate Begemanbb1ce942008-07-29 15:49:41 +00006479 if (!isa<VectorType>(I.getType()) &&
6480 MaskedValueIsZero(Op0,
Chris Lattnere3c504f2007-12-06 01:59:46 +00006481 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006482 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006483
6484 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006485}
6486
6487Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6488 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6490
6491 // shl X, 0 == X and shr X, 0 == X
6492 // shl 0, X == 0 and shr 0, X == 0
6493 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6494 Op0 == Constant::getNullValue(Op0->getType()))
6495 return ReplaceInstUsesWith(I, Op0);
6496
6497 if (isa<UndefValue>(Op0)) {
6498 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6499 return ReplaceInstUsesWith(I, Op0);
6500 else // undef << X -> 0, undef >>u X -> 0
6501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6502 }
6503 if (isa<UndefValue>(Op1)) {
6504 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6505 return ReplaceInstUsesWith(I, Op0);
6506 else // X << undef, X >>u undef -> 0
6507 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6508 }
6509
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006510 // Try to fold constant and into select arguments.
6511 if (isa<Constant>(Op0))
6512 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6513 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6514 return R;
6515
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006516 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6517 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6518 return Res;
6519 return 0;
6520}
6521
6522Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6523 BinaryOperator &I) {
6524 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6525
6526 // See if we can simplify any instructions used by the instruction whose sole
6527 // purpose is to compute bits we don't care about.
6528 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6529 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6530 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6531 KnownZero, KnownOne))
6532 return &I;
6533
6534 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6535 // of a signed value.
6536 //
6537 if (Op1->uge(TypeBits)) {
6538 if (I.getOpcode() != Instruction::AShr)
6539 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6540 else {
6541 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6542 return &I;
6543 }
6544 }
6545
6546 // ((X*C1) << C2) == (X * (C1 << C2))
6547 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6548 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6549 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006550 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006551 ConstantExpr::getShl(BOOp, Op1));
6552
6553 // Try to fold constant and into select arguments.
6554 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6555 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6556 return R;
6557 if (isa<PHINode>(Op0))
6558 if (Instruction *NV = FoldOpIntoPhi(I))
6559 return NV;
6560
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006561 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6562 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6563 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6564 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6565 // place. Don't try to do this transformation in this case. Also, we
6566 // require that the input operand is a shift-by-constant so that we have
6567 // confidence that the shifts will get folded together. We could do this
6568 // xform in more cases, but it is unlikely to be profitable.
6569 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6570 isa<ConstantInt>(TrOp->getOperand(1))) {
6571 // Okay, we'll do this xform. Make the shift of shift.
6572 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006573 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006574 I.getName());
6575 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6576
6577 // For logical shifts, the truncation has the effect of making the high
6578 // part of the register be zeros. Emulate this by inserting an AND to
6579 // clear the top bits as needed. This 'and' will usually be zapped by
6580 // other xforms later if dead.
6581 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6582 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6583 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6584
6585 // The mask we constructed says what the trunc would do if occurring
6586 // between the shifts. We want to know the effect *after* the second
6587 // shift. We know that it is a logical shift by a constant, so adjust the
6588 // mask as appropriate.
6589 if (I.getOpcode() == Instruction::Shl)
6590 MaskV <<= Op1->getZExtValue();
6591 else {
6592 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6593 MaskV = MaskV.lshr(Op1->getZExtValue());
6594 }
6595
Gabor Greifa645dd32008-05-16 19:29:10 +00006596 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006597 TI->getName());
6598 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6599
6600 // Return the value truncated to the interesting size.
6601 return new TruncInst(And, I.getType());
6602 }
6603 }
6604
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006605 if (Op0->hasOneUse()) {
6606 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6607 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6608 Value *V1, *V2;
6609 ConstantInt *CC;
6610 switch (Op0BO->getOpcode()) {
6611 default: break;
6612 case Instruction::Add:
6613 case Instruction::And:
6614 case Instruction::Or:
6615 case Instruction::Xor: {
6616 // These operators commute.
6617 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6618 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6619 match(Op0BO->getOperand(1),
6620 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006621 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006622 Op0BO->getOperand(0), Op1,
6623 Op0BO->getName());
6624 InsertNewInstBefore(YS, I); // (Y << C)
6625 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006626 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006627 Op0BO->getOperand(1)->getName());
6628 InsertNewInstBefore(X, I); // (X + (Y << C))
6629 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006630 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006631 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6632 }
6633
6634 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6635 Value *Op0BOOp1 = Op0BO->getOperand(1);
6636 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6637 match(Op0BOOp1,
6638 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6639 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6640 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006641 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006642 Op0BO->getOperand(0), Op1,
6643 Op0BO->getName());
6644 InsertNewInstBefore(YS, I); // (Y << C)
6645 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006646 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006647 V1->getName()+".mask");
6648 InsertNewInstBefore(XM, I); // X & (CC << C)
6649
Gabor Greifa645dd32008-05-16 19:29:10 +00006650 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006651 }
6652 }
6653
6654 // FALL THROUGH.
6655 case Instruction::Sub: {
6656 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6657 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6658 match(Op0BO->getOperand(0),
6659 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006660 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006661 Op0BO->getOperand(1), Op1,
6662 Op0BO->getName());
6663 InsertNewInstBefore(YS, I); // (Y << C)
6664 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006665 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006666 Op0BO->getOperand(0)->getName());
6667 InsertNewInstBefore(X, I); // (X + (Y << C))
6668 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006669 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6671 }
6672
6673 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6674 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6675 match(Op0BO->getOperand(0),
6676 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6677 m_ConstantInt(CC))) && V2 == Op1 &&
6678 cast<BinaryOperator>(Op0BO->getOperand(0))
6679 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006680 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006681 Op0BO->getOperand(1), Op1,
6682 Op0BO->getName());
6683 InsertNewInstBefore(YS, I); // (Y << C)
6684 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006685 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006686 V1->getName()+".mask");
6687 InsertNewInstBefore(XM, I); // X & (CC << C)
6688
Gabor Greifa645dd32008-05-16 19:29:10 +00006689 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006690 }
6691
6692 break;
6693 }
6694 }
6695
6696
6697 // If the operand is an bitwise operator with a constant RHS, and the
6698 // shift is the only use, we can pull it out of the shift.
6699 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6700 bool isValid = true; // Valid only for And, Or, Xor
6701 bool highBitSet = false; // Transform if high bit of constant set?
6702
6703 switch (Op0BO->getOpcode()) {
6704 default: isValid = false; break; // Do not perform transform!
6705 case Instruction::Add:
6706 isValid = isLeftShift;
6707 break;
6708 case Instruction::Or:
6709 case Instruction::Xor:
6710 highBitSet = false;
6711 break;
6712 case Instruction::And:
6713 highBitSet = true;
6714 break;
6715 }
6716
6717 // If this is a signed shift right, and the high bit is modified
6718 // by the logical operation, do not perform the transformation.
6719 // The highBitSet boolean indicates the value of the high bit of
6720 // the constant which would cause it to be modified for this
6721 // operation.
6722 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006723 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006724 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006725
6726 if (isValid) {
6727 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6728
6729 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006730 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006731 InsertNewInstBefore(NewShift, I);
6732 NewShift->takeName(Op0BO);
6733
Gabor Greifa645dd32008-05-16 19:29:10 +00006734 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006735 NewRHS);
6736 }
6737 }
6738 }
6739 }
6740
6741 // Find out if this is a shift of a shift by a constant.
6742 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6743 if (ShiftOp && !ShiftOp->isShift())
6744 ShiftOp = 0;
6745
6746 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6747 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6748 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6749 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6750 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6751 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6752 Value *X = ShiftOp->getOperand(0);
6753
6754 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6755 if (AmtSum > TypeBits)
6756 AmtSum = TypeBits;
6757
6758 const IntegerType *Ty = cast<IntegerType>(I.getType());
6759
6760 // Check for (X << c1) << c2 and (X >> c1) >> c2
6761 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006762 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006763 ConstantInt::get(Ty, AmtSum));
6764 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6765 I.getOpcode() == Instruction::AShr) {
6766 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006767 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006768 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6769 I.getOpcode() == Instruction::LShr) {
6770 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6771 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006772 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006773 InsertNewInstBefore(Shift, I);
6774
6775 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006776 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006777 }
6778
6779 // Okay, if we get here, one shift must be left, and the other shift must be
6780 // right. See if the amounts are equal.
6781 if (ShiftAmt1 == ShiftAmt2) {
6782 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6783 if (I.getOpcode() == Instruction::Shl) {
6784 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006785 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006786 }
6787 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6788 if (I.getOpcode() == Instruction::LShr) {
6789 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006790 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006791 }
6792 // We can simplify ((X << C) >>s C) into a trunc + sext.
6793 // NOTE: we could do this for any C, but that would make 'unusual' integer
6794 // types. For now, just stick to ones well-supported by the code
6795 // generators.
6796 const Type *SExtType = 0;
6797 switch (Ty->getBitWidth() - ShiftAmt1) {
6798 case 1 :
6799 case 8 :
6800 case 16 :
6801 case 32 :
6802 case 64 :
6803 case 128:
6804 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6805 break;
6806 default: break;
6807 }
6808 if (SExtType) {
6809 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6810 InsertNewInstBefore(NewTrunc, I);
6811 return new SExtInst(NewTrunc, Ty);
6812 }
6813 // Otherwise, we can't handle it yet.
6814 } else if (ShiftAmt1 < ShiftAmt2) {
6815 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6816
6817 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6818 if (I.getOpcode() == Instruction::Shl) {
6819 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6820 ShiftOp->getOpcode() == Instruction::AShr);
6821 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006822 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006823 InsertNewInstBefore(Shift, I);
6824
6825 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006826 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006827 }
6828
6829 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6830 if (I.getOpcode() == Instruction::LShr) {
6831 assert(ShiftOp->getOpcode() == Instruction::Shl);
6832 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006833 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006834 InsertNewInstBefore(Shift, I);
6835
6836 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006837 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006838 }
6839
6840 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6841 } else {
6842 assert(ShiftAmt2 < ShiftAmt1);
6843 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6844
6845 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6846 if (I.getOpcode() == Instruction::Shl) {
6847 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6848 ShiftOp->getOpcode() == Instruction::AShr);
6849 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006850 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006851 ConstantInt::get(Ty, ShiftDiff));
6852 InsertNewInstBefore(Shift, I);
6853
6854 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006855 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006856 }
6857
6858 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6859 if (I.getOpcode() == Instruction::LShr) {
6860 assert(ShiftOp->getOpcode() == Instruction::Shl);
6861 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006862 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006863 InsertNewInstBefore(Shift, I);
6864
6865 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006866 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006867 }
6868
6869 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6870 }
6871 }
6872 return 0;
6873}
6874
6875
6876/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6877/// expression. If so, decompose it, returning some value X, such that Val is
6878/// X*Scale+Offset.
6879///
6880static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6881 int &Offset) {
6882 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6883 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6884 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006885 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006886 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006887 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6888 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6889 if (I->getOpcode() == Instruction::Shl) {
6890 // This is a value scaled by '1 << the shift amt'.
6891 Scale = 1U << RHS->getZExtValue();
6892 Offset = 0;
6893 return I->getOperand(0);
6894 } else if (I->getOpcode() == Instruction::Mul) {
6895 // This value is scaled by 'RHS'.
6896 Scale = RHS->getZExtValue();
6897 Offset = 0;
6898 return I->getOperand(0);
6899 } else if (I->getOpcode() == Instruction::Add) {
6900 // We have X+C. Check to see if we really have (X*C2)+C1,
6901 // where C1 is divisible by C2.
6902 unsigned SubScale;
6903 Value *SubVal =
6904 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6905 Offset += RHS->getZExtValue();
6906 Scale = SubScale;
6907 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006908 }
6909 }
6910 }
6911
6912 // Otherwise, we can't look past this.
6913 Scale = 1;
6914 Offset = 0;
6915 return Val;
6916}
6917
6918
6919/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6920/// try to eliminate the cast by moving the type information into the alloc.
6921Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6922 AllocationInst &AI) {
6923 const PointerType *PTy = cast<PointerType>(CI.getType());
6924
6925 // Remove any uses of AI that are dead.
6926 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6927
6928 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6929 Instruction *User = cast<Instruction>(*UI++);
6930 if (isInstructionTriviallyDead(User)) {
6931 while (UI != E && *UI == User)
6932 ++UI; // If this instruction uses AI more than once, don't break UI.
6933
6934 ++NumDeadInst;
6935 DOUT << "IC: DCE: " << *User;
6936 EraseInstFromFunction(*User);
6937 }
6938 }
6939
6940 // Get the type really allocated and the type casted to.
6941 const Type *AllocElTy = AI.getAllocatedType();
6942 const Type *CastElTy = PTy->getElementType();
6943 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6944
6945 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6946 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6947 if (CastElTyAlign < AllocElTyAlign) return 0;
6948
6949 // If the allocation has multiple uses, only promote it if we are strictly
6950 // increasing the alignment of the resultant allocation. If we keep it the
6951 // same, we open the door to infinite loops of various kinds.
6952 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6953
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006954 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6955 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006956 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6957
6958 // See if we can satisfy the modulus by pulling a scale out of the array
6959 // size argument.
6960 unsigned ArraySizeScale;
6961 int ArrayOffset;
6962 Value *NumElements = // See if the array size is a decomposable linear expr.
6963 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6964
6965 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6966 // do the xform.
6967 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6968 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6969
6970 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6971 Value *Amt = 0;
6972 if (Scale == 1) {
6973 Amt = NumElements;
6974 } else {
6975 // If the allocation size is constant, form a constant mul expression
6976 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6977 if (isa<ConstantInt>(NumElements))
6978 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6979 // otherwise multiply the amount and the number of elements
6980 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006981 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006982 Amt = InsertNewInstBefore(Tmp, AI);
6983 }
6984 }
6985
6986 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6987 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00006988 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006989 Amt = InsertNewInstBefore(Tmp, AI);
6990 }
6991
6992 AllocationInst *New;
6993 if (isa<MallocInst>(AI))
6994 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6995 else
6996 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6997 InsertNewInstBefore(New, AI);
6998 New->takeName(&AI);
6999
7000 // If the allocation has multiple uses, insert a cast and change all things
7001 // that used it to use the new cast. This will also hack on CI, but it will
7002 // die soon.
7003 if (!AI.hasOneUse()) {
7004 AddUsesToWorkList(AI);
7005 // New is the allocation instruction, pointer typed. AI is the original
7006 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7007 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7008 InsertNewInstBefore(NewCast, AI);
7009 AI.replaceAllUsesWith(NewCast);
7010 }
7011 return ReplaceInstUsesWith(CI, New);
7012}
7013
7014/// CanEvaluateInDifferentType - Return true if we can take the specified value
7015/// and return it as type Ty without inserting any new casts and without
7016/// changing the computed value. This is used by code that tries to decide
7017/// whether promoting or shrinking integer operations to wider or smaller types
7018/// will allow us to eliminate a truncate or extend.
7019///
7020/// This is a truncation operation if Ty is smaller than V->getType(), or an
7021/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007022///
7023/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7024/// should return true if trunc(V) can be computed by computing V in the smaller
7025/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7026/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7027/// efficiently truncated.
7028///
7029/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7030/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7031/// the final result.
Dan Gohman2d648bb2008-04-10 18:43:06 +00007032bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7033 unsigned CastOpc,
7034 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007035 // We can always evaluate constants in another type.
7036 if (isa<ConstantInt>(V))
7037 return true;
7038
7039 Instruction *I = dyn_cast<Instruction>(V);
7040 if (!I) return false;
7041
7042 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7043
Chris Lattneref70bb82007-08-02 06:11:14 +00007044 // If this is an extension or truncate, we can often eliminate it.
7045 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7046 // If this is a cast from the destination type, we can trivially eliminate
7047 // it, and this will remove a cast overall.
7048 if (I->getOperand(0)->getType() == Ty) {
7049 // If the first operand is itself a cast, and is eliminable, do not count
7050 // this as an eliminable cast. We would prefer to eliminate those two
7051 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007052 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007053 ++NumCastsRemoved;
7054 return true;
7055 }
7056 }
7057
7058 // We can't extend or shrink something that has multiple uses: doing so would
7059 // require duplicating the instruction in general, which isn't profitable.
7060 if (!I->hasOneUse()) return false;
7061
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007062 switch (I->getOpcode()) {
7063 case Instruction::Add:
7064 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007065 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007066 case Instruction::And:
7067 case Instruction::Or:
7068 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007069 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007070 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7071 NumCastsRemoved) &&
7072 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7073 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007074
7075 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007076 // If we are truncating the result of this SHL, and if it's a shift of a
7077 // constant amount, we can always perform a SHL in a smaller type.
7078 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7079 uint32_t BitWidth = Ty->getBitWidth();
7080 if (BitWidth < OrigTy->getBitWidth() &&
7081 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007082 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7083 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007084 }
7085 break;
7086 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007087 // If this is a truncate of a logical shr, we can truncate it to a smaller
7088 // lshr iff we know that the bits we would otherwise be shifting in are
7089 // already zeros.
7090 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7091 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7092 uint32_t BitWidth = Ty->getBitWidth();
7093 if (BitWidth < OrigBitWidth &&
7094 MaskedValueIsZero(I->getOperand(0),
7095 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7096 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007097 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7098 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007099 }
7100 }
7101 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007102 case Instruction::ZExt:
7103 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007104 case Instruction::Trunc:
7105 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007106 // can safely replace it. Note that replacing it does not reduce the number
7107 // of casts in the input.
7108 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007109 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007110 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007111 case Instruction::Select: {
7112 SelectInst *SI = cast<SelectInst>(I);
7113 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7114 NumCastsRemoved) &&
7115 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7116 NumCastsRemoved);
7117 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007118 case Instruction::PHI: {
7119 // We can change a phi if we can change all operands.
7120 PHINode *PN = cast<PHINode>(I);
7121 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7122 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7123 NumCastsRemoved))
7124 return false;
7125 return true;
7126 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007127 default:
7128 // TODO: Can handle more cases here.
7129 break;
7130 }
7131
7132 return false;
7133}
7134
7135/// EvaluateInDifferentType - Given an expression that
7136/// CanEvaluateInDifferentType returns true for, actually insert the code to
7137/// evaluate the expression.
7138Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7139 bool isSigned) {
7140 if (Constant *C = dyn_cast<Constant>(V))
7141 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7142
7143 // Otherwise, it must be an instruction.
7144 Instruction *I = cast<Instruction>(V);
7145 Instruction *Res = 0;
7146 switch (I->getOpcode()) {
7147 case Instruction::Add:
7148 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007149 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007150 case Instruction::And:
7151 case Instruction::Or:
7152 case Instruction::Xor:
7153 case Instruction::AShr:
7154 case Instruction::LShr:
7155 case Instruction::Shl: {
7156 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7157 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007158 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner4200c2062008-06-18 04:00:49 +00007159 LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007160 break;
7161 }
7162 case Instruction::Trunc:
7163 case Instruction::ZExt:
7164 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007165 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007166 // just return the source. There's no need to insert it because it is not
7167 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007168 if (I->getOperand(0)->getType() == Ty)
7169 return I->getOperand(0);
7170
Chris Lattner4200c2062008-06-18 04:00:49 +00007171 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007172 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007173 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007174 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007175 case Instruction::Select: {
7176 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7177 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7178 Res = SelectInst::Create(I->getOperand(0), True, False);
7179 break;
7180 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007181 case Instruction::PHI: {
7182 PHINode *OPN = cast<PHINode>(I);
7183 PHINode *NPN = PHINode::Create(Ty);
7184 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7185 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7186 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7187 }
7188 Res = NPN;
7189 break;
7190 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007191 default:
7192 // TODO: Can handle more cases here.
7193 assert(0 && "Unreachable!");
7194 break;
7195 }
7196
Chris Lattner4200c2062008-06-18 04:00:49 +00007197 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007198 return InsertNewInstBefore(Res, *I);
7199}
7200
7201/// @brief Implement the transforms common to all CastInst visitors.
7202Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7203 Value *Src = CI.getOperand(0);
7204
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007205 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7206 // eliminate it now.
7207 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7208 if (Instruction::CastOps opc =
7209 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7210 // The first cast (CSrc) is eliminable so we need to fix up or replace
7211 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007212 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007213 }
7214 }
7215
7216 // If we are casting a select then fold the cast into the select
7217 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7218 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7219 return NV;
7220
7221 // If we are casting a PHI then fold the cast into the PHI
7222 if (isa<PHINode>(Src))
7223 if (Instruction *NV = FoldOpIntoPhi(CI))
7224 return NV;
7225
7226 return 0;
7227}
7228
7229/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7230Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7231 Value *Src = CI.getOperand(0);
7232
7233 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7234 // If casting the result of a getelementptr instruction with no offset, turn
7235 // this into a cast of the original pointer!
7236 if (GEP->hasAllZeroIndices()) {
7237 // Changing the cast operand is usually not a good idea but it is safe
7238 // here because the pointer operand is being replaced with another
7239 // pointer operand so the opcode doesn't need to change.
7240 AddToWorkList(GEP);
7241 CI.setOperand(0, GEP->getOperand(0));
7242 return &CI;
7243 }
7244
7245 // If the GEP has a single use, and the base pointer is a bitcast, and the
7246 // GEP computes a constant offset, see if we can convert these three
7247 // instructions into fewer. This typically happens with unions and other
7248 // non-type-safe code.
7249 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7250 if (GEP->hasAllConstantIndices()) {
7251 // We are guaranteed to get a constant from EmitGEPOffset.
7252 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7253 int64_t Offset = OffsetV->getSExtValue();
7254
7255 // Get the base pointer input of the bitcast, and the type it points to.
7256 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7257 const Type *GEPIdxTy =
7258 cast<PointerType>(OrigBase->getType())->getElementType();
7259 if (GEPIdxTy->isSized()) {
7260 SmallVector<Value*, 8> NewIndices;
7261
7262 // Start with the index over the outer type. Note that the type size
7263 // might be zero (even if the offset isn't zero) if the indexed type
7264 // is something like [0 x {int, int}]
7265 const Type *IntPtrTy = TD->getIntPtrType();
7266 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007267 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007268 FirstIdx = Offset/TySize;
7269 Offset %= TySize;
7270
7271 // Handle silly modulus not returning values values [0..TySize).
7272 if (Offset < 0) {
7273 --FirstIdx;
7274 Offset += TySize;
7275 assert(Offset >= 0);
7276 }
7277 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7278 }
7279
7280 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7281
7282 // Index into the types. If we fail, set OrigBase to null.
7283 while (Offset) {
7284 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7285 const StructLayout *SL = TD->getStructLayout(STy);
7286 if (Offset < (int64_t)SL->getSizeInBytes()) {
7287 unsigned Elt = SL->getElementContainingOffset(Offset);
7288 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7289
7290 Offset -= SL->getElementOffset(Elt);
7291 GEPIdxTy = STy->getElementType(Elt);
7292 } else {
7293 // Otherwise, we can't index into this, bail out.
7294 Offset = 0;
7295 OrigBase = 0;
7296 }
7297 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7298 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007299 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007300 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7301 Offset %= EltSize;
7302 } else {
7303 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7304 }
7305 GEPIdxTy = STy->getElementType();
7306 } else {
7307 // Otherwise, we can't index into this, bail out.
7308 Offset = 0;
7309 OrigBase = 0;
7310 }
7311 }
7312 if (OrigBase) {
7313 // If we were able to index down into an element, create the GEP
7314 // and bitcast the result. This eliminates one bitcast, potentially
7315 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007316 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7317 NewIndices.begin(),
7318 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007319 InsertNewInstBefore(NGEP, CI);
7320 NGEP->takeName(GEP);
7321
7322 if (isa<BitCastInst>(CI))
7323 return new BitCastInst(NGEP, CI.getType());
7324 assert(isa<PtrToIntInst>(CI));
7325 return new PtrToIntInst(NGEP, CI.getType());
7326 }
7327 }
7328 }
7329 }
7330 }
7331
7332 return commonCastTransforms(CI);
7333}
7334
7335
7336
7337/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7338/// integer types. This function implements the common transforms for all those
7339/// cases.
7340/// @brief Implement the transforms common to CastInst with integer operands
7341Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7342 if (Instruction *Result = commonCastTransforms(CI))
7343 return Result;
7344
7345 Value *Src = CI.getOperand(0);
7346 const Type *SrcTy = Src->getType();
7347 const Type *DestTy = CI.getType();
7348 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7349 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7350
7351 // See if we can simplify any instructions used by the LHS whose sole
7352 // purpose is to compute bits we don't care about.
7353 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7354 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7355 KnownZero, KnownOne))
7356 return &CI;
7357
7358 // If the source isn't an instruction or has more than one use then we
7359 // can't do anything more.
7360 Instruction *SrcI = dyn_cast<Instruction>(Src);
7361 if (!SrcI || !Src->hasOneUse())
7362 return 0;
7363
7364 // Attempt to propagate the cast into the instruction for int->int casts.
7365 int NumCastsRemoved = 0;
7366 if (!isa<BitCastInst>(CI) &&
7367 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007368 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007369 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007370 // eliminates the cast, so it is always a win. If this is a zero-extension,
7371 // we need to do an AND to maintain the clear top-part of the computation,
7372 // so we require that the input have eliminated at least one cast. If this
7373 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007374 // require that two casts have been eliminated.
7375 bool DoXForm;
7376 switch (CI.getOpcode()) {
7377 default:
7378 // All the others use floating point so we shouldn't actually
7379 // get here because of the check above.
7380 assert(0 && "Unknown cast type");
7381 case Instruction::Trunc:
7382 DoXForm = true;
7383 break;
7384 case Instruction::ZExt:
7385 DoXForm = NumCastsRemoved >= 1;
7386 break;
7387 case Instruction::SExt:
7388 DoXForm = NumCastsRemoved >= 2;
7389 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390 }
7391
7392 if (DoXForm) {
7393 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7394 CI.getOpcode() == Instruction::SExt);
7395 assert(Res->getType() == DestTy);
7396 switch (CI.getOpcode()) {
7397 default: assert(0 && "Unknown cast type!");
7398 case Instruction::Trunc:
7399 case Instruction::BitCast:
7400 // Just replace this cast with the result.
7401 return ReplaceInstUsesWith(CI, Res);
7402 case Instruction::ZExt: {
7403 // We need to emit an AND to clear the high bits.
7404 assert(SrcBitSize < DestBitSize && "Not a zext?");
7405 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7406 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007407 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007408 }
7409 case Instruction::SExt:
7410 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007411 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007412 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7413 CI), DestTy);
7414 }
7415 }
7416 }
7417
7418 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7419 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7420
7421 switch (SrcI->getOpcode()) {
7422 case Instruction::Add:
7423 case Instruction::Mul:
7424 case Instruction::And:
7425 case Instruction::Or:
7426 case Instruction::Xor:
7427 // If we are discarding information, rewrite.
7428 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7429 // Don't insert two casts if they cannot be eliminated. We allow
7430 // two casts to be inserted if the sizes are the same. This could
7431 // only be converting signedness, which is a noop.
7432 if (DestBitSize == SrcBitSize ||
7433 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7434 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7435 Instruction::CastOps opcode = CI.getOpcode();
7436 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7437 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007438 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007439 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7440 }
7441 }
7442
7443 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7444 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7445 SrcI->getOpcode() == Instruction::Xor &&
7446 Op1 == ConstantInt::getTrue() &&
7447 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7448 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007449 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007450 }
7451 break;
7452 case Instruction::SDiv:
7453 case Instruction::UDiv:
7454 case Instruction::SRem:
7455 case Instruction::URem:
7456 // If we are just changing the sign, rewrite.
7457 if (DestBitSize == SrcBitSize) {
7458 // Don't insert two casts if they cannot be eliminated. We allow
7459 // two casts to be inserted if the sizes are the same. This could
7460 // only be converting signedness, which is a noop.
7461 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7462 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7463 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7464 Op0, DestTy, SrcI);
7465 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7466 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007467 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007468 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7469 }
7470 }
7471 break;
7472
7473 case Instruction::Shl:
7474 // Allow changing the sign of the source operand. Do not allow
7475 // changing the size of the shift, UNLESS the shift amount is a
7476 // constant. We must not change variable sized shifts to a smaller
7477 // size, because it is undefined to shift more bits out than exist
7478 // in the value.
7479 if (DestBitSize == SrcBitSize ||
7480 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7481 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7482 Instruction::BitCast : Instruction::Trunc);
7483 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7484 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007485 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007486 }
7487 break;
7488 case Instruction::AShr:
7489 // If this is a signed shr, and if all bits shifted in are about to be
7490 // truncated off, turn it into an unsigned shr to allow greater
7491 // simplifications.
7492 if (DestBitSize < SrcBitSize &&
7493 isa<ConstantInt>(Op1)) {
7494 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7495 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7496 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007497 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007498 }
7499 }
7500 break;
7501 }
7502 return 0;
7503}
7504
7505Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7506 if (Instruction *Result = commonIntCastTransforms(CI))
7507 return Result;
7508
7509 Value *Src = CI.getOperand(0);
7510 const Type *Ty = CI.getType();
7511 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7512 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7513
7514 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7515 switch (SrcI->getOpcode()) {
7516 default: break;
7517 case Instruction::LShr:
7518 // We can shrink lshr to something smaller if we know the bits shifted in
7519 // are already zeros.
7520 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7521 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7522
7523 // Get a mask for the bits shifting in.
7524 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7525 Value* SrcIOp0 = SrcI->getOperand(0);
7526 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7527 if (ShAmt >= DestBitWidth) // All zeros.
7528 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7529
7530 // Okay, we can shrink this. Truncate the input, then return a new
7531 // shift.
7532 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7533 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7534 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007535 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007536 }
7537 } else { // This is a variable shr.
7538
7539 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7540 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7541 // loop-invariant and CSE'd.
7542 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7543 Value *One = ConstantInt::get(SrcI->getType(), 1);
7544
7545 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007546 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007547 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007548 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007549 SrcI->getOperand(0),
7550 "tmp"), CI);
7551 Value *Zero = Constant::getNullValue(V->getType());
7552 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7553 }
7554 }
7555 break;
7556 }
7557 }
7558
7559 return 0;
7560}
7561
Evan Chenge3779cf2008-03-24 00:21:34 +00007562/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7563/// in order to eliminate the icmp.
7564Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7565 bool DoXform) {
7566 // If we are just checking for a icmp eq of a single bit and zext'ing it
7567 // to an integer, then shift the bit to the appropriate place and then
7568 // cast to integer to avoid the comparison.
7569 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7570 const APInt &Op1CV = Op1C->getValue();
7571
7572 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7573 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7574 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7575 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7576 if (!DoXform) return ICI;
7577
7578 Value *In = ICI->getOperand(0);
7579 Value *Sh = ConstantInt::get(In->getType(),
7580 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007581 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007582 In->getName()+".lobit"),
7583 CI);
7584 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007585 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007586 false/*ZExt*/, "tmp", &CI);
7587
7588 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7589 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007590 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007591 In->getName()+".not"),
7592 CI);
7593 }
7594
7595 return ReplaceInstUsesWith(CI, In);
7596 }
7597
7598
7599
7600 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7601 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7602 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7603 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7604 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7605 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7606 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7607 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7608 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7609 // This only works for EQ and NE
7610 ICI->isEquality()) {
7611 // If Op1C some other power of two, convert:
7612 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7613 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7614 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7615 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7616
7617 APInt KnownZeroMask(~KnownZero);
7618 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7619 if (!DoXform) return ICI;
7620
7621 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7622 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7623 // (X&4) == 2 --> false
7624 // (X&4) != 2 --> true
7625 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7626 Res = ConstantExpr::getZExt(Res, CI.getType());
7627 return ReplaceInstUsesWith(CI, Res);
7628 }
7629
7630 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7631 Value *In = ICI->getOperand(0);
7632 if (ShiftAmt) {
7633 // Perform a logical shr by shiftamt.
7634 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007635 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007636 ConstantInt::get(In->getType(), ShiftAmt),
7637 In->getName()+".lobit"), CI);
7638 }
7639
7640 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7641 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007642 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007643 InsertNewInstBefore(cast<Instruction>(In), CI);
7644 }
7645
7646 if (CI.getType() == In->getType())
7647 return ReplaceInstUsesWith(CI, In);
7648 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007649 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007650 }
7651 }
7652 }
7653
7654 return 0;
7655}
7656
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007657Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7658 // If one of the common conversion will work ..
7659 if (Instruction *Result = commonIntCastTransforms(CI))
7660 return Result;
7661
7662 Value *Src = CI.getOperand(0);
7663
7664 // If this is a cast of a cast
7665 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7666 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7667 // types and if the sizes are just right we can convert this into a logical
7668 // 'and' which will be much cheaper than the pair of casts.
7669 if (isa<TruncInst>(CSrc)) {
7670 // Get the sizes of the types involved
7671 Value *A = CSrc->getOperand(0);
7672 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7673 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7674 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7675 // If we're actually extending zero bits and the trunc is a no-op
7676 if (MidSize < DstSize && SrcSize == DstSize) {
7677 // Replace both of the casts with an And of the type mask.
7678 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7679 Constant *AndConst = ConstantInt::get(AndValue);
7680 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007681 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007682 // Unfortunately, if the type changed, we need to cast it back.
7683 if (And->getType() != CI.getType()) {
7684 And->setName(CSrc->getName()+".mask");
7685 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007686 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007687 }
7688 return And;
7689 }
7690 }
7691 }
7692
Evan Chenge3779cf2008-03-24 00:21:34 +00007693 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7694 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007695
Evan Chenge3779cf2008-03-24 00:21:34 +00007696 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7697 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7698 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7699 // of the (zext icmp) will be transformed.
7700 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7701 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7702 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7703 (transformZExtICmp(LHS, CI, false) ||
7704 transformZExtICmp(RHS, CI, false))) {
7705 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7706 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007707 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007708 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007709 }
7710
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007711 return 0;
7712}
7713
7714Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7715 if (Instruction *I = commonIntCastTransforms(CI))
7716 return I;
7717
7718 Value *Src = CI.getOperand(0);
7719
7720 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7721 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7722 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7723 // If we are just checking for a icmp eq of a single bit and zext'ing it
7724 // to an integer, then shift the bit to the appropriate place and then
7725 // cast to integer to avoid the comparison.
7726 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7727 const APInt &Op1CV = Op1C->getValue();
7728
7729 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7730 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7731 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7732 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7733 Value *In = ICI->getOperand(0);
7734 Value *Sh = ConstantInt::get(In->getType(),
7735 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007736 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007737 In->getName()+".lobit"),
7738 CI);
7739 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007740 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007741 true/*SExt*/, "tmp", &CI);
7742
7743 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007744 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007745 In->getName()+".not"), CI);
7746
7747 return ReplaceInstUsesWith(CI, In);
7748 }
7749 }
7750 }
Dan Gohmanf0f12022008-05-20 21:01:12 +00007751
7752 // See if the value being truncated is already sign extended. If so, just
7753 // eliminate the trunc/sext pair.
7754 if (getOpcode(Src) == Instruction::Trunc) {
7755 Value *Op = cast<User>(Src)->getOperand(0);
7756 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7757 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7758 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7759 unsigned NumSignBits = ComputeNumSignBits(Op);
7760
7761 if (OpBits == DestBits) {
7762 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7763 // bits, it is already ready.
7764 if (NumSignBits > DestBits-MidBits)
7765 return ReplaceInstUsesWith(CI, Op);
7766 } else if (OpBits < DestBits) {
7767 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7768 // bits, just sext from i32.
7769 if (NumSignBits > OpBits-MidBits)
7770 return new SExtInst(Op, CI.getType(), "tmp");
7771 } else {
7772 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7773 // bits, just truncate to i32.
7774 if (NumSignBits > OpBits-MidBits)
7775 return new TruncInst(Op, CI.getType(), "tmp");
7776 }
7777 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00007778
7779 // If the input is a shl/ashr pair of a same constant, then this is a sign
7780 // extension from a smaller value. If we could trust arbitrary bitwidth
7781 // integers, we could turn this into a truncate to the smaller bit and then
7782 // use a sext for the whole extension. Since we don't, look deeper and check
7783 // for a truncate. If the source and dest are the same type, eliminate the
7784 // trunc and extend and just do shifts. For example, turn:
7785 // %a = trunc i32 %i to i8
7786 // %b = shl i8 %a, 6
7787 // %c = ashr i8 %b, 6
7788 // %d = sext i8 %c to i32
7789 // into:
7790 // %a = shl i32 %i, 30
7791 // %d = ashr i32 %a, 30
7792 Value *A = 0;
7793 ConstantInt *BA = 0, *CA = 0;
7794 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7795 m_ConstantInt(CA))) &&
7796 BA == CA && isa<TruncInst>(A)) {
7797 Value *I = cast<TruncInst>(A)->getOperand(0);
7798 if (I->getType() == CI.getType()) {
7799 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7800 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7801 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7802 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7803 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7804 CI.getName()), CI);
7805 return BinaryOperator::CreateAShr(I, ShAmtV);
7806 }
7807 }
7808
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007809 return 0;
7810}
7811
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007812/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7813/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007814static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007815 APFloat F = CFP->getValueAPF();
7816 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007817 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007818 return 0;
7819}
7820
7821/// LookThroughFPExtensions - If this is an fp extension instruction, look
7822/// through it until we get the source value.
7823static Value *LookThroughFPExtensions(Value *V) {
7824 if (Instruction *I = dyn_cast<Instruction>(V))
7825 if (I->getOpcode() == Instruction::FPExt)
7826 return LookThroughFPExtensions(I->getOperand(0));
7827
7828 // If this value is a constant, return the constant in the smallest FP type
7829 // that can accurately represent it. This allows us to turn
7830 // (float)((double)X+2.0) into x+2.0f.
7831 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7832 if (CFP->getType() == Type::PPC_FP128Ty)
7833 return V; // No constant folding of this.
7834 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007835 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007836 return V;
7837 if (CFP->getType() == Type::DoubleTy)
7838 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007839 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007840 return V;
7841 // Don't try to shrink to various long double types.
7842 }
7843
7844 return V;
7845}
7846
7847Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7848 if (Instruction *I = commonCastTransforms(CI))
7849 return I;
7850
7851 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7852 // smaller than the destination type, we can eliminate the truncate by doing
7853 // the add as the smaller type. This applies to add/sub/mul/div as well as
7854 // many builtins (sqrt, etc).
7855 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7856 if (OpI && OpI->hasOneUse()) {
7857 switch (OpI->getOpcode()) {
7858 default: break;
7859 case Instruction::Add:
7860 case Instruction::Sub:
7861 case Instruction::Mul:
7862 case Instruction::FDiv:
7863 case Instruction::FRem:
7864 const Type *SrcTy = OpI->getType();
7865 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7866 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7867 if (LHSTrunc->getType() != SrcTy &&
7868 RHSTrunc->getType() != SrcTy) {
7869 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7870 // If the source types were both smaller than the destination type of
7871 // the cast, do this xform.
7872 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7873 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7874 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7875 CI.getType(), CI);
7876 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7877 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007878 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007879 }
7880 }
7881 break;
7882 }
7883 }
7884 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007885}
7886
7887Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7888 return commonCastTransforms(CI);
7889}
7890
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007891Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00007892 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7893 if (OpI == 0)
7894 return commonCastTransforms(FI);
7895
7896 // fptoui(uitofp(X)) --> X
7897 // fptoui(sitofp(X)) --> X
7898 // This is safe if the intermediate type has enough bits in its mantissa to
7899 // accurately represent all values of X. For example, do not do this with
7900 // i64->float->i64. This is also safe for sitofp case, because any negative
7901 // 'X' value would cause an undefined result for the fptoui.
7902 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7903 OpI->getOperand(0)->getType() == FI.getType() &&
7904 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7905 OpI->getType()->getFPMantissaWidth())
7906 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007907
7908 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007909}
7910
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007911Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00007912 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7913 if (OpI == 0)
7914 return commonCastTransforms(FI);
7915
7916 // fptosi(sitofp(X)) --> X
7917 // fptosi(uitofp(X)) --> X
7918 // This is safe if the intermediate type has enough bits in its mantissa to
7919 // accurately represent all values of X. For example, do not do this with
7920 // i64->float->i64. This is also safe for sitofp case, because any negative
7921 // 'X' value would cause an undefined result for the fptoui.
7922 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7923 OpI->getOperand(0)->getType() == FI.getType() &&
7924 (int)FI.getType()->getPrimitiveSizeInBits() <=
7925 OpI->getType()->getFPMantissaWidth())
7926 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007927
7928 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007929}
7930
7931Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7932 return commonCastTransforms(CI);
7933}
7934
7935Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7936 return commonCastTransforms(CI);
7937}
7938
7939Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7940 return commonPointerCastTransforms(CI);
7941}
7942
Chris Lattner7c1626482008-01-08 07:23:51 +00007943Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7944 if (Instruction *I = commonCastTransforms(CI))
7945 return I;
7946
7947 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7948 if (!DestPointee->isSized()) return 0;
7949
7950 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7951 ConstantInt *Cst;
7952 Value *X;
7953 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7954 m_ConstantInt(Cst)))) {
7955 // If the source and destination operands have the same type, see if this
7956 // is a single-index GEP.
7957 if (X->getType() == CI.getType()) {
7958 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007959 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007960
7961 // Convert the constant to intptr type.
7962 APInt Offset = Cst->getValue();
7963 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7964
7965 // If Offset is evenly divisible by Size, we can do this xform.
7966 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7967 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00007968 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00007969 }
7970 }
7971 // TODO: Could handle other cases, e.g. where add is indexing into field of
7972 // struct etc.
7973 } else if (CI.getOperand(0)->hasOneUse() &&
7974 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7975 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7976 // "inttoptr+GEP" instead of "add+intptr".
7977
7978 // Get the size of the pointee type.
7979 uint64_t Size = TD->getABITypeSize(DestPointee);
7980
7981 // Convert the constant to intptr type.
7982 APInt Offset = Cst->getValue();
7983 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7984
7985 // If Offset is evenly divisible by Size, we can do this xform.
7986 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7987 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7988
7989 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7990 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007991 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00007992 }
7993 }
7994 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007995}
7996
7997Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7998 // If the operands are integer typed then apply the integer transforms,
7999 // otherwise just apply the common ones.
8000 Value *Src = CI.getOperand(0);
8001 const Type *SrcTy = Src->getType();
8002 const Type *DestTy = CI.getType();
8003
8004 if (SrcTy->isInteger() && DestTy->isInteger()) {
8005 if (Instruction *Result = commonIntCastTransforms(CI))
8006 return Result;
8007 } else if (isa<PointerType>(SrcTy)) {
8008 if (Instruction *I = commonPointerCastTransforms(CI))
8009 return I;
8010 } else {
8011 if (Instruction *Result = commonCastTransforms(CI))
8012 return Result;
8013 }
8014
8015
8016 // Get rid of casts from one type to the same type. These are useless and can
8017 // be replaced by the operand.
8018 if (DestTy == Src->getType())
8019 return ReplaceInstUsesWith(CI, Src);
8020
8021 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8022 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8023 const Type *DstElTy = DstPTy->getElementType();
8024 const Type *SrcElTy = SrcPTy->getElementType();
8025
Nate Begemandf5b3612008-03-31 00:22:16 +00008026 // If the address spaces don't match, don't eliminate the bitcast, which is
8027 // required for changing types.
8028 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8029 return 0;
8030
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008031 // If we are casting a malloc or alloca to a pointer to a type of the same
8032 // size, rewrite the allocation instruction to allocate the "right" type.
8033 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8034 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8035 return V;
8036
8037 // If the source and destination are pointers, and this cast is equivalent
8038 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8039 // This can enhance SROA and other transforms that want type-safe pointers.
8040 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8041 unsigned NumZeros = 0;
8042 while (SrcElTy != DstElTy &&
8043 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8044 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8045 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8046 ++NumZeros;
8047 }
8048
8049 // If we found a path from the src to dest, create the getelementptr now.
8050 if (SrcElTy == DstElTy) {
8051 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008052 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8053 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008054 }
8055 }
8056
8057 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8058 if (SVI->hasOneUse()) {
8059 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8060 // a bitconvert to a vector with the same # elts.
8061 if (isa<VectorType>(DestTy) &&
8062 cast<VectorType>(DestTy)->getNumElements() ==
8063 SVI->getType()->getNumElements()) {
8064 CastInst *Tmp;
8065 // If either of the operands is a cast from CI.getType(), then
8066 // evaluating the shuffle in the casted destination's type will allow
8067 // us to eliminate at least one cast.
8068 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8069 Tmp->getOperand(0)->getType() == DestTy) ||
8070 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8071 Tmp->getOperand(0)->getType() == DestTy)) {
8072 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8073 SVI->getOperand(0), DestTy, &CI);
8074 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8075 SVI->getOperand(1), DestTy, &CI);
8076 // Return a new shuffle vector. Use the same element ID's, as we
8077 // know the vector types match #elts.
8078 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8079 }
8080 }
8081 }
8082 }
8083 return 0;
8084}
8085
8086/// GetSelectFoldableOperands - We want to turn code that looks like this:
8087/// %C = or %A, %B
8088/// %D = select %cond, %C, %A
8089/// into:
8090/// %C = select %cond, %B, 0
8091/// %D = or %A, %C
8092///
8093/// Assuming that the specified instruction is an operand to the select, return
8094/// a bitmask indicating which operands of this instruction are foldable if they
8095/// equal the other incoming value of the select.
8096///
8097static unsigned GetSelectFoldableOperands(Instruction *I) {
8098 switch (I->getOpcode()) {
8099 case Instruction::Add:
8100 case Instruction::Mul:
8101 case Instruction::And:
8102 case Instruction::Or:
8103 case Instruction::Xor:
8104 return 3; // Can fold through either operand.
8105 case Instruction::Sub: // Can only fold on the amount subtracted.
8106 case Instruction::Shl: // Can only fold on the shift amount.
8107 case Instruction::LShr:
8108 case Instruction::AShr:
8109 return 1;
8110 default:
8111 return 0; // Cannot fold
8112 }
8113}
8114
8115/// GetSelectFoldableConstant - For the same transformation as the previous
8116/// function, return the identity constant that goes into the select.
8117static Constant *GetSelectFoldableConstant(Instruction *I) {
8118 switch (I->getOpcode()) {
8119 default: assert(0 && "This cannot happen!"); abort();
8120 case Instruction::Add:
8121 case Instruction::Sub:
8122 case Instruction::Or:
8123 case Instruction::Xor:
8124 case Instruction::Shl:
8125 case Instruction::LShr:
8126 case Instruction::AShr:
8127 return Constant::getNullValue(I->getType());
8128 case Instruction::And:
8129 return Constant::getAllOnesValue(I->getType());
8130 case Instruction::Mul:
8131 return ConstantInt::get(I->getType(), 1);
8132 }
8133}
8134
8135/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8136/// have the same opcode and only one use each. Try to simplify this.
8137Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8138 Instruction *FI) {
8139 if (TI->getNumOperands() == 1) {
8140 // If this is a non-volatile load or a cast from the same type,
8141 // merge.
8142 if (TI->isCast()) {
8143 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8144 return 0;
8145 } else {
8146 return 0; // unknown unary op.
8147 }
8148
8149 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008150 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8151 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008152 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008153 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008154 TI->getType());
8155 }
8156
8157 // Only handle binary operators here.
8158 if (!isa<BinaryOperator>(TI))
8159 return 0;
8160
8161 // Figure out if the operations have any operands in common.
8162 Value *MatchOp, *OtherOpT, *OtherOpF;
8163 bool MatchIsOpZero;
8164 if (TI->getOperand(0) == FI->getOperand(0)) {
8165 MatchOp = TI->getOperand(0);
8166 OtherOpT = TI->getOperand(1);
8167 OtherOpF = FI->getOperand(1);
8168 MatchIsOpZero = true;
8169 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8170 MatchOp = TI->getOperand(1);
8171 OtherOpT = TI->getOperand(0);
8172 OtherOpF = FI->getOperand(0);
8173 MatchIsOpZero = false;
8174 } else if (!TI->isCommutative()) {
8175 return 0;
8176 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8177 MatchOp = TI->getOperand(0);
8178 OtherOpT = TI->getOperand(1);
8179 OtherOpF = FI->getOperand(0);
8180 MatchIsOpZero = true;
8181 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8182 MatchOp = TI->getOperand(1);
8183 OtherOpT = TI->getOperand(0);
8184 OtherOpF = FI->getOperand(1);
8185 MatchIsOpZero = true;
8186 } else {
8187 return 0;
8188 }
8189
8190 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008191 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8192 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008193 InsertNewInstBefore(NewSI, SI);
8194
8195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8196 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008197 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008198 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008199 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008200 }
8201 assert(0 && "Shouldn't get here");
8202 return 0;
8203}
8204
Dan Gohman58c09632008-09-16 18:46:06 +00008205/// visitSelectInstWithICmp - Visit a SelectInst that has an
8206/// ICmpInst as its first operand.
8207///
8208Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8209 ICmpInst *ICI) {
8210 bool Changed = false;
8211 ICmpInst::Predicate Pred = ICI->getPredicate();
8212 Value *CmpLHS = ICI->getOperand(0);
8213 Value *CmpRHS = ICI->getOperand(1);
8214 Value *TrueVal = SI.getTrueValue();
8215 Value *FalseVal = SI.getFalseValue();
8216
8217 // Check cases where the comparison is with a constant that
8218 // can be adjusted to fit the min/max idiom. We may edit ICI in
8219 // place here, so make sure the select is the only user.
8220 if (ICI->hasOneUse())
8221 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
8222 switch (Pred) {
8223 default: break;
8224 case ICmpInst::ICMP_ULT:
8225 case ICmpInst::ICMP_SLT: {
8226 // X < MIN ? T : F --> F
8227 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8228 return ReplaceInstUsesWith(SI, FalseVal);
8229 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8230 Constant *AdjustedRHS = SubOne(CI);
8231 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8232 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8233 Pred = ICmpInst::getSwappedPredicate(Pred);
8234 CmpRHS = AdjustedRHS;
8235 std::swap(FalseVal, TrueVal);
8236 ICI->setPredicate(Pred);
8237 ICI->setOperand(1, CmpRHS);
8238 SI.setOperand(1, TrueVal);
8239 SI.setOperand(2, FalseVal);
8240 Changed = true;
8241 }
8242 break;
8243 }
8244 case ICmpInst::ICMP_UGT:
8245 case ICmpInst::ICMP_SGT: {
8246 // X > MAX ? T : F --> F
8247 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8248 return ReplaceInstUsesWith(SI, FalseVal);
8249 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8250 Constant *AdjustedRHS = AddOne(CI);
8251 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8252 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8253 Pred = ICmpInst::getSwappedPredicate(Pred);
8254 CmpRHS = AdjustedRHS;
8255 std::swap(FalseVal, TrueVal);
8256 ICI->setPredicate(Pred);
8257 ICI->setOperand(1, CmpRHS);
8258 SI.setOperand(1, TrueVal);
8259 SI.setOperand(2, FalseVal);
8260 Changed = true;
8261 }
8262 break;
8263 }
8264 }
8265
8266 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8267 // Transform (X == Y) ? X : Y -> Y
8268 if (Pred == ICmpInst::ICMP_EQ)
8269 return ReplaceInstUsesWith(SI, FalseVal);
8270 // Transform (X != Y) ? X : Y -> X
8271 if (Pred == ICmpInst::ICMP_NE)
8272 return ReplaceInstUsesWith(SI, TrueVal);
8273 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8274
8275 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8276 // Transform (X == Y) ? Y : X -> X
8277 if (Pred == ICmpInst::ICMP_EQ)
8278 return ReplaceInstUsesWith(SI, FalseVal);
8279 // Transform (X != Y) ? Y : X -> Y
8280 if (Pred == ICmpInst::ICMP_NE)
8281 return ReplaceInstUsesWith(SI, TrueVal);
8282 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8283 }
8284
8285 /// NOTE: if we wanted to, this is where to detect integer ABS
8286
8287 return Changed ? &SI : 0;
8288}
8289
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008290Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8291 Value *CondVal = SI.getCondition();
8292 Value *TrueVal = SI.getTrueValue();
8293 Value *FalseVal = SI.getFalseValue();
8294
8295 // select true, X, Y -> X
8296 // select false, X, Y -> Y
8297 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8298 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8299
8300 // select C, X, X -> X
8301 if (TrueVal == FalseVal)
8302 return ReplaceInstUsesWith(SI, TrueVal);
8303
8304 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8305 return ReplaceInstUsesWith(SI, FalseVal);
8306 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8307 return ReplaceInstUsesWith(SI, TrueVal);
8308 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8309 if (isa<Constant>(TrueVal))
8310 return ReplaceInstUsesWith(SI, TrueVal);
8311 else
8312 return ReplaceInstUsesWith(SI, FalseVal);
8313 }
8314
8315 if (SI.getType() == Type::Int1Ty) {
8316 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8317 if (C->getZExtValue()) {
8318 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008319 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008320 } else {
8321 // Change: A = select B, false, C --> A = and !B, C
8322 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008323 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008324 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008325 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008326 }
8327 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8328 if (C->getZExtValue() == false) {
8329 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008330 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008331 } else {
8332 // Change: A = select B, C, true --> A = or !B, C
8333 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008334 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008335 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008336 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008337 }
8338 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008339
8340 // select a, b, a -> a&b
8341 // select a, a, b -> a|b
8342 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008343 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008344 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008345 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008346 }
8347
8348 // Selecting between two integer constants?
8349 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8350 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8351 // select C, 1, 0 -> zext C to int
8352 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008353 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008354 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8355 // select C, 0, 1 -> zext !C to int
8356 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008357 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008358 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008359 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008360 }
8361
8362 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8363
8364 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8365
8366 // (x <s 0) ? -1 : 0 -> ashr x, 31
8367 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8368 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8369 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8370 // The comparison constant and the result are not neccessarily the
8371 // same width. Make an all-ones value by inserting a AShr.
8372 Value *X = IC->getOperand(0);
8373 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8374 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008375 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008376 ShAmt, "ones");
8377 InsertNewInstBefore(SRA, SI);
8378
8379 // Finally, convert to the type of the select RHS. We figure out
8380 // if this requires a SExt, Trunc or BitCast based on the sizes.
8381 Instruction::CastOps opc = Instruction::BitCast;
8382 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8383 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8384 if (SRASize < SISize)
8385 opc = Instruction::SExt;
8386 else if (SRASize > SISize)
8387 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008388 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008389 }
8390 }
8391
8392
8393 // If one of the constants is zero (we know they can't both be) and we
8394 // have an icmp instruction with zero, and we have an 'and' with the
8395 // non-constant value, eliminate this whole mess. This corresponds to
8396 // cases like this: ((X & 27) ? 27 : 0)
8397 if (TrueValC->isZero() || FalseValC->isZero())
8398 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8399 cast<Constant>(IC->getOperand(1))->isNullValue())
8400 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8401 if (ICA->getOpcode() == Instruction::And &&
8402 isa<ConstantInt>(ICA->getOperand(1)) &&
8403 (ICA->getOperand(1) == TrueValC ||
8404 ICA->getOperand(1) == FalseValC) &&
8405 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8406 // Okay, now we know that everything is set up, we just don't
8407 // know whether we have a icmp_ne or icmp_eq and whether the
8408 // true or false val is the zero.
8409 bool ShouldNotVal = !TrueValC->isZero();
8410 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8411 Value *V = ICA;
8412 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008413 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008414 Instruction::Xor, V, ICA->getOperand(1)), SI);
8415 return ReplaceInstUsesWith(SI, V);
8416 }
8417 }
8418 }
8419
8420 // See if we are selecting two values based on a comparison of the two values.
8421 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8422 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8423 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008424 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8425 // This is not safe in general for floating point:
8426 // consider X== -0, Y== +0.
8427 // It becomes safe if either operand is a nonzero constant.
8428 ConstantFP *CFPt, *CFPf;
8429 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8430 !CFPt->getValueAPF().isZero()) ||
8431 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8432 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008434 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008435 // Transform (X != Y) ? X : Y -> X
8436 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8437 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00008438 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008439
8440 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8441 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008442 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8443 // This is not safe in general for floating point:
8444 // consider X== -0, Y== +0.
8445 // It becomes safe if either operand is a nonzero constant.
8446 ConstantFP *CFPt, *CFPf;
8447 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8448 !CFPt->getValueAPF().isZero()) ||
8449 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8450 !CFPf->getValueAPF().isZero()))
8451 return ReplaceInstUsesWith(SI, FalseVal);
8452 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008453 // Transform (X != Y) ? Y : X -> Y
8454 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8455 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00008456 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008457 }
Dan Gohman58c09632008-09-16 18:46:06 +00008458 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008459 }
8460
8461 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00008462 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8463 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8464 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008465
8466 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8467 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8468 if (TI->hasOneUse() && FI->hasOneUse()) {
8469 Instruction *AddOp = 0, *SubOp = 0;
8470
8471 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8472 if (TI->getOpcode() == FI->getOpcode())
8473 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8474 return IV;
8475
8476 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8477 // even legal for FP.
8478 if (TI->getOpcode() == Instruction::Sub &&
8479 FI->getOpcode() == Instruction::Add) {
8480 AddOp = FI; SubOp = TI;
8481 } else if (FI->getOpcode() == Instruction::Sub &&
8482 TI->getOpcode() == Instruction::Add) {
8483 AddOp = TI; SubOp = FI;
8484 }
8485
8486 if (AddOp) {
8487 Value *OtherAddOp = 0;
8488 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8489 OtherAddOp = AddOp->getOperand(1);
8490 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8491 OtherAddOp = AddOp->getOperand(0);
8492 }
8493
8494 if (OtherAddOp) {
8495 // So at this point we know we have (Y -> OtherAddOp):
8496 // select C, (add X, Y), (sub X, Z)
8497 Value *NegVal; // Compute -Z
8498 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8499 NegVal = ConstantExpr::getNeg(C);
8500 } else {
8501 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008502 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008503 }
8504
8505 Value *NewTrueOp = OtherAddOp;
8506 Value *NewFalseOp = NegVal;
8507 if (AddOp != TI)
8508 std::swap(NewTrueOp, NewFalseOp);
8509 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008510 SelectInst::Create(CondVal, NewTrueOp,
8511 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008512
8513 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008514 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008515 }
8516 }
8517 }
8518
8519 // See if we can fold the select into one of our operands.
8520 if (SI.getType()->isInteger()) {
8521 // See the comment above GetSelectFoldableOperands for a description of the
8522 // transformation we are doing here.
8523 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8524 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8525 !isa<Constant>(FalseVal))
8526 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8527 unsigned OpToFold = 0;
8528 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8529 OpToFold = 1;
8530 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8531 OpToFold = 2;
8532 }
8533
8534 if (OpToFold) {
8535 Constant *C = GetSelectFoldableConstant(TVI);
8536 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008537 SelectInst::Create(SI.getCondition(),
8538 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008539 InsertNewInstBefore(NewSel, SI);
8540 NewSel->takeName(TVI);
8541 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008542 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008543 else {
8544 assert(0 && "Unknown instruction!!");
8545 }
8546 }
8547 }
8548
8549 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8550 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8551 !isa<Constant>(TrueVal))
8552 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8553 unsigned OpToFold = 0;
8554 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8555 OpToFold = 1;
8556 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8557 OpToFold = 2;
8558 }
8559
8560 if (OpToFold) {
8561 Constant *C = GetSelectFoldableConstant(FVI);
8562 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008563 SelectInst::Create(SI.getCondition(), C,
8564 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008565 InsertNewInstBefore(NewSel, SI);
8566 NewSel->takeName(FVI);
8567 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008568 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008569 else
8570 assert(0 && "Unknown instruction!!");
8571 }
8572 }
8573 }
8574
8575 if (BinaryOperator::isNot(CondVal)) {
8576 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8577 SI.setOperand(1, FalseVal);
8578 SI.setOperand(2, TrueVal);
8579 return &SI;
8580 }
8581
8582 return 0;
8583}
8584
Dan Gohman2d648bb2008-04-10 18:43:06 +00008585/// EnforceKnownAlignment - If the specified pointer points to an object that
8586/// we control, modify the object's alignment to PrefAlign. This isn't
8587/// often possible though. If alignment is important, a more reliable approach
8588/// is to simply align all global variables and allocation instructions to
8589/// their preferred alignment from the beginning.
8590///
8591static unsigned EnforceKnownAlignment(Value *V,
8592 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008593
Dan Gohman2d648bb2008-04-10 18:43:06 +00008594 User *U = dyn_cast<User>(V);
8595 if (!U) return Align;
8596
8597 switch (getOpcode(U)) {
8598 default: break;
8599 case Instruction::BitCast:
8600 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8601 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008602 // If all indexes are zero, it is just the alignment of the base pointer.
8603 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00008604 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00008605 if (!isa<Constant>(*i) ||
8606 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008607 AllZeroOperands = false;
8608 break;
8609 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008610
8611 if (AllZeroOperands) {
8612 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008613 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008614 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008615 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008616 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008617 }
8618
8619 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8620 // If there is a large requested alignment and we can, bump up the alignment
8621 // of the global.
8622 if (!GV->isDeclaration()) {
8623 GV->setAlignment(PrefAlign);
8624 Align = PrefAlign;
8625 }
8626 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8627 // If there is a requested alignment and if this is an alloca, round up. We
8628 // don't do this for malloc, because some systems can't respect the request.
8629 if (isa<AllocaInst>(AI)) {
8630 AI->setAlignment(PrefAlign);
8631 Align = PrefAlign;
8632 }
8633 }
8634
8635 return Align;
8636}
8637
8638/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8639/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8640/// and it is more than the alignment of the ultimate object, see if we can
8641/// increase the alignment of the ultimate object, making this check succeed.
8642unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8643 unsigned PrefAlign) {
8644 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8645 sizeof(PrefAlign) * CHAR_BIT;
8646 APInt Mask = APInt::getAllOnesValue(BitWidth);
8647 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8648 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8649 unsigned TrailZ = KnownZero.countTrailingOnes();
8650 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8651
8652 if (PrefAlign > Align)
8653 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8654
8655 // We don't need to make any adjustment.
8656 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008657}
8658
Chris Lattner00ae5132008-01-13 23:50:23 +00008659Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008660 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8661 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008662 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8663 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8664
8665 if (CopyAlign < MinAlign) {
8666 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8667 return MI;
8668 }
8669
8670 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8671 // load/store.
8672 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8673 if (MemOpLength == 0) return 0;
8674
Chris Lattnerc669fb62008-01-14 00:28:35 +00008675 // Source and destination pointer types are always "i8*" for intrinsic. See
8676 // if the size is something we can handle with a single primitive load/store.
8677 // A single load+store correctly handles overlapping memory in the memmove
8678 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008679 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008680 if (Size == 0) return MI; // Delete this mem transfer.
8681
8682 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008683 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008684
Chris Lattnerc669fb62008-01-14 00:28:35 +00008685 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008686 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008687
8688 // Memcpy forces the use of i8* for the source and destination. That means
8689 // that if you're using memcpy to move one double around, you'll get a cast
8690 // from double* to i8*. We'd much rather use a double load+store rather than
8691 // an i64 load+store, here because this improves the odds that the source or
8692 // dest address will be promotable. See if we can find a better type than the
8693 // integer datatype.
8694 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8695 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8696 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8697 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8698 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008699 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00008700 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8701 if (STy->getNumElements() == 1)
8702 SrcETy = STy->getElementType(0);
8703 else
8704 break;
8705 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8706 if (ATy->getNumElements() == 1)
8707 SrcETy = ATy->getElementType();
8708 else
8709 break;
8710 } else
8711 break;
8712 }
8713
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008714 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00008715 NewPtrTy = PointerType::getUnqual(SrcETy);
8716 }
8717 }
8718
8719
Chris Lattner00ae5132008-01-13 23:50:23 +00008720 // If the memcpy/memmove provides better alignment info than we can
8721 // infer, use it.
8722 SrcAlign = std::max(SrcAlign, CopyAlign);
8723 DstAlign = std::max(DstAlign, CopyAlign);
8724
8725 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8726 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008727 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8728 InsertNewInstBefore(L, *MI);
8729 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8730
8731 // Set the size of the copy to 0, it will be deleted on the next iteration.
8732 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8733 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008734}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008735
Chris Lattner5af8a912008-04-30 06:39:11 +00008736Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8737 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8738 if (MI->getAlignment()->getZExtValue() < Alignment) {
8739 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8740 return MI;
8741 }
8742
8743 // Extract the length and alignment and fill if they are constant.
8744 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8745 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8746 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8747 return 0;
8748 uint64_t Len = LenC->getZExtValue();
8749 Alignment = MI->getAlignment()->getZExtValue();
8750
8751 // If the length is zero, this is a no-op
8752 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8753
8754 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8755 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8756 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8757
8758 Value *Dest = MI->getDest();
8759 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8760
8761 // Alignment 0 is identity for alignment 1 for memset, but not store.
8762 if (Alignment == 0) Alignment = 1;
8763
8764 // Extract the fill value and store.
8765 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8766 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8767 Alignment), *MI);
8768
8769 // Set the size of the copy to 0, it will be deleted on the next iteration.
8770 MI->setLength(Constant::getNullValue(LenC->getType()));
8771 return MI;
8772 }
8773
8774 return 0;
8775}
8776
8777
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008778/// visitCallInst - CallInst simplification. This mostly only handles folding
8779/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8780/// the heavy lifting.
8781///
8782Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8783 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8784 if (!II) return visitCallSite(&CI);
8785
8786 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8787 // visitCallSite.
8788 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8789 bool Changed = false;
8790
8791 // memmove/cpy/set of zero bytes is a noop.
8792 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8793 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8794
8795 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8796 if (CI->getZExtValue() == 1) {
8797 // Replace the instruction with just byte operations. We would
8798 // transform other cases to loads/stores, but we don't know if
8799 // alignment is sufficient.
8800 }
8801 }
8802
8803 // If we have a memmove and the source operation is a constant global,
8804 // then the source and dest pointers can't alias, so we can change this
8805 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008806 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008807 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8808 if (GVSrc->isConstant()) {
8809 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008810 Intrinsic::ID MemCpyID;
8811 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8812 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008813 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008814 MemCpyID = Intrinsic::memcpy_i64;
8815 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008816 Changed = true;
8817 }
Chris Lattner59b27d92008-05-28 05:30:41 +00008818
8819 // memmove(x,x,size) -> noop.
8820 if (MMI->getSource() == MMI->getDest())
8821 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008822 }
8823
8824 // If we can determine a pointer alignment that is bigger than currently
8825 // set, update the alignment.
8826 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008827 if (Instruction *I = SimplifyMemTransfer(MI))
8828 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008829 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8830 if (Instruction *I = SimplifyMemSet(MSI))
8831 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008832 }
8833
8834 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00008835 }
8836
8837 switch (II->getIntrinsicID()) {
8838 default: break;
8839 case Intrinsic::bswap:
8840 // bswap(bswap(x)) -> x
8841 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8842 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8843 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8844 break;
8845 case Intrinsic::ppc_altivec_lvx:
8846 case Intrinsic::ppc_altivec_lvxl:
8847 case Intrinsic::x86_sse_loadu_ps:
8848 case Intrinsic::x86_sse2_loadu_pd:
8849 case Intrinsic::x86_sse2_loadu_dq:
8850 // Turn PPC lvx -> load if the pointer is known aligned.
8851 // Turn X86 loadups -> load if the pointer is known aligned.
8852 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8853 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8854 PointerType::getUnqual(II->getType()),
8855 CI);
8856 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008857 }
Chris Lattner989ba312008-06-18 04:33:20 +00008858 break;
8859 case Intrinsic::ppc_altivec_stvx:
8860 case Intrinsic::ppc_altivec_stvxl:
8861 // Turn stvx -> store if the pointer is known aligned.
8862 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8863 const Type *OpPtrTy =
8864 PointerType::getUnqual(II->getOperand(1)->getType());
8865 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8866 return new StoreInst(II->getOperand(1), Ptr);
8867 }
8868 break;
8869 case Intrinsic::x86_sse_storeu_ps:
8870 case Intrinsic::x86_sse2_storeu_pd:
8871 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00008872 // Turn X86 storeu -> store if the pointer is known aligned.
8873 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8874 const Type *OpPtrTy =
8875 PointerType::getUnqual(II->getOperand(2)->getType());
8876 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8877 return new StoreInst(II->getOperand(2), Ptr);
8878 }
8879 break;
8880
8881 case Intrinsic::x86_sse_cvttss2si: {
8882 // These intrinsics only demands the 0th element of its input vector. If
8883 // we can simplify the input based on that, do so now.
8884 uint64_t UndefElts;
8885 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8886 UndefElts)) {
8887 II->setOperand(1, V);
8888 return II;
8889 }
8890 break;
8891 }
8892
8893 case Intrinsic::ppc_altivec_vperm:
8894 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8895 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8896 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008897
Chris Lattner989ba312008-06-18 04:33:20 +00008898 // Check that all of the elements are integer constants or undefs.
8899 bool AllEltsOk = true;
8900 for (unsigned i = 0; i != 16; ++i) {
8901 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8902 !isa<UndefValue>(Mask->getOperand(i))) {
8903 AllEltsOk = false;
8904 break;
8905 }
8906 }
8907
8908 if (AllEltsOk) {
8909 // Cast the input vectors to byte vectors.
8910 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8911 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8912 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008913
Chris Lattner989ba312008-06-18 04:33:20 +00008914 // Only extract each element once.
8915 Value *ExtractedElts[32];
8916 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8917
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008918 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00008919 if (isa<UndefValue>(Mask->getOperand(i)))
8920 continue;
8921 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8922 Idx &= 31; // Match the hardware behavior.
8923
8924 if (ExtractedElts[Idx] == 0) {
8925 Instruction *Elt =
8926 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8927 InsertNewInstBefore(Elt, CI);
8928 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008929 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008930
Chris Lattner989ba312008-06-18 04:33:20 +00008931 // Insert this value into the result vector.
8932 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8933 i, "tmp");
8934 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008935 }
Chris Lattner989ba312008-06-18 04:33:20 +00008936 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008937 }
Chris Lattner989ba312008-06-18 04:33:20 +00008938 }
8939 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008940
Chris Lattner989ba312008-06-18 04:33:20 +00008941 case Intrinsic::stackrestore: {
8942 // If the save is right next to the restore, remove the restore. This can
8943 // happen when variable allocas are DCE'd.
8944 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8945 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8946 BasicBlock::iterator BI = SS;
8947 if (&*++BI == II)
8948 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008949 }
Chris Lattner989ba312008-06-18 04:33:20 +00008950 }
8951
8952 // Scan down this block to see if there is another stack restore in the
8953 // same block without an intervening call/alloca.
8954 BasicBlock::iterator BI = II;
8955 TerminatorInst *TI = II->getParent()->getTerminator();
8956 bool CannotRemove = false;
8957 for (++BI; &*BI != TI; ++BI) {
8958 if (isa<AllocaInst>(BI)) {
8959 CannotRemove = true;
8960 break;
8961 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00008962 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8963 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8964 // If there is a stackrestore below this one, remove this one.
8965 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8966 return EraseInstFromFunction(CI);
8967 // Otherwise, ignore the intrinsic.
8968 } else {
8969 // If we found a non-intrinsic call, we can't remove the stack
8970 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00008971 CannotRemove = true;
8972 break;
8973 }
Chris Lattner989ba312008-06-18 04:33:20 +00008974 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008975 }
Chris Lattner989ba312008-06-18 04:33:20 +00008976
8977 // If the stack restore is in a return/unwind block and if there are no
8978 // allocas or calls between the restore and the return, nuke the restore.
8979 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8980 return EraseInstFromFunction(CI);
8981 break;
8982 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008983 }
8984
8985 return visitCallSite(II);
8986}
8987
8988// InvokeInst simplification
8989//
8990Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8991 return visitCallSite(&II);
8992}
8993
Dale Johannesen96021832008-04-25 21:16:07 +00008994/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8995/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008996static bool isSafeToEliminateVarargsCast(const CallSite CS,
8997 const CastInst * const CI,
8998 const TargetData * const TD,
8999 const int ix) {
9000 if (!CI->isLosslessCast())
9001 return false;
9002
9003 // The size of ByVal arguments is derived from the type, so we
9004 // can't change to a type with a different size. If the size were
9005 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009006 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009007 return true;
9008
9009 const Type* SrcTy =
9010 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9011 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9012 if (!SrcTy->isSized() || !DstTy->isSized())
9013 return false;
9014 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9015 return false;
9016 return true;
9017}
9018
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009019// visitCallSite - Improvements for call and invoke instructions.
9020//
9021Instruction *InstCombiner::visitCallSite(CallSite CS) {
9022 bool Changed = false;
9023
9024 // If the callee is a constexpr cast of a function, attempt to move the cast
9025 // to the arguments of the call/invoke.
9026 if (transformConstExprCastCall(CS)) return 0;
9027
9028 Value *Callee = CS.getCalledValue();
9029
9030 if (Function *CalleeF = dyn_cast<Function>(Callee))
9031 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9032 Instruction *OldCall = CS.getInstruction();
9033 // If the call and callee calling conventions don't match, this call must
9034 // be unreachable, as the call is undefined.
9035 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009036 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9037 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009038 if (!OldCall->use_empty())
9039 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9040 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9041 return EraseInstFromFunction(*OldCall);
9042 return 0;
9043 }
9044
9045 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9046 // This instruction is not reachable, just remove it. We insert a store to
9047 // undef so that we know that this code is not reachable, despite the fact
9048 // that we can't modify the CFG here.
9049 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009050 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009051 CS.getInstruction());
9052
9053 if (!CS.getInstruction()->use_empty())
9054 CS.getInstruction()->
9055 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9056
9057 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9058 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009059 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9060 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009061 }
9062 return EraseInstFromFunction(*CS.getInstruction());
9063 }
9064
Duncan Sands74833f22007-09-17 10:26:40 +00009065 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9066 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9067 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9068 return transformCallThroughTrampoline(CS);
9069
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009070 const PointerType *PTy = cast<PointerType>(Callee->getType());
9071 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9072 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009073 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009074 // See if we can optimize any arguments passed through the varargs area of
9075 // the call.
9076 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009077 E = CS.arg_end(); I != E; ++I, ++ix) {
9078 CastInst *CI = dyn_cast<CastInst>(*I);
9079 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9080 *I = CI->getOperand(0);
9081 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009082 }
Dale Johannesen35615462008-04-23 18:34:37 +00009083 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009084 }
9085
Duncan Sands2937e352007-12-19 21:13:37 +00009086 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009087 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009088 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009089 Changed = true;
9090 }
9091
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009092 return Changed ? CS.getInstruction() : 0;
9093}
9094
9095// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9096// attempt to move the cast to the arguments of the call/invoke.
9097//
9098bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9099 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9100 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9101 if (CE->getOpcode() != Instruction::BitCast ||
9102 !isa<Function>(CE->getOperand(0)))
9103 return false;
9104 Function *Callee = cast<Function>(CE->getOperand(0));
9105 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00009106 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009107
9108 // Okay, this is a cast from a function to a different type. Unless doing so
9109 // would cause a type conversion of one of our arguments, change this call to
9110 // be a direct call with arguments casted to the appropriate types.
9111 //
9112 const FunctionType *FT = Callee->getFunctionType();
9113 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00009114 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009115
Duncan Sands7901ce12008-06-01 07:38:42 +00009116 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00009117 return false; // TODO: Handle multiple return values.
9118
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009119 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00009120 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009121 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00009122 // Conversion is ok if changing from one pointer type to another or from
9123 // a pointer to an integer of the same size.
9124 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +00009125 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009126 return false; // Cannot transform this return value.
9127
Duncan Sands5c489582008-01-06 10:12:28 +00009128 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009129 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00009130 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009131 return false; // Cannot transform this return value.
9132
Chris Lattner1c8733e2008-03-12 17:45:29 +00009133 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00009134 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00009135 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009136 return false; // Attribute not compatible with transformed value.
9137 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009138
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009139 // If the callsite is an invoke instruction, and the return value is used by
9140 // a PHI node in a successor, we cannot change the return type of the call
9141 // because there is no place to put the cast instruction (without breaking
9142 // the critical edge). Bail out in this case.
9143 if (!Caller->use_empty())
9144 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9145 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9146 UI != E; ++UI)
9147 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9148 if (PN->getParent() == II->getNormalDest() ||
9149 PN->getParent() == II->getUnwindDest())
9150 return false;
9151 }
9152
9153 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9154 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9155
9156 CallSite::arg_iterator AI = CS.arg_begin();
9157 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9158 const Type *ParamTy = FT->getParamType(i);
9159 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009160
9161 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009162 return false; // Cannot transform this parameter value.
9163
Devang Patelf2a4a922008-09-26 22:53:05 +00009164 if (CallerPAL.getParamAttributes(i + 1)
9165 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +00009166 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009167
Duncan Sands7901ce12008-06-01 07:38:42 +00009168 // Converting from one pointer type to another or between a pointer and an
9169 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009170 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00009171 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9172 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009173 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009174 }
9175
9176 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9177 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009178 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009179
Chris Lattner1c8733e2008-03-12 17:45:29 +00009180 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9181 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009182 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009183 // won't be dropping them. Check that these extra arguments have attributes
9184 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009185 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9186 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009187 break;
Devang Patele480dfa2008-09-23 23:03:40 +00009188 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +00009189 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +00009190 return false;
9191 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009192
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009193 // Okay, we decided that this is a safe thing to do: go ahead and start
9194 // inserting cast instructions as necessary...
9195 std::vector<Value*> Args;
9196 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +00009197 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009198 attrVec.reserve(NumCommonArgs);
9199
9200 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009201 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +00009202
9203 // If the return value is not being used, the type may not be compatible
9204 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +00009205 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00009206
9207 // Add the new return attributes.
9208 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +00009209 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009210
9211 AI = CS.arg_begin();
9212 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9213 const Type *ParamTy = FT->getParamType(i);
9214 if ((*AI)->getType() == ParamTy) {
9215 Args.push_back(*AI);
9216 } else {
9217 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9218 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009219 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009220 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9221 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009222
9223 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009224 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009225 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009226 }
9227
9228 // If the function takes more arguments than the call was taking, add them
9229 // now...
9230 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9231 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9232
9233 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009234 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009235 if (!FT->isVarArg()) {
9236 cerr << "WARNING: While resolving call to function '"
9237 << Callee->getName() << "' arguments were dropped!\n";
9238 } else {
9239 // Add all of the arguments in their promoted form to the arg list...
9240 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9241 const Type *PTy = getPromotedType((*AI)->getType());
9242 if (PTy != (*AI)->getType()) {
9243 // Must promote to pass through va_arg area!
9244 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9245 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009246 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009247 InsertNewInstBefore(Cast, *Caller);
9248 Args.push_back(Cast);
9249 } else {
9250 Args.push_back(*AI);
9251 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009252
Duncan Sands4ced1f82008-01-13 08:02:44 +00009253 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009254 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009255 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +00009256 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009257 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009258 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009259
Devang Patelf2a4a922008-09-26 22:53:05 +00009260 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9261 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9262
Duncan Sands7901ce12008-06-01 07:38:42 +00009263 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009264 Caller->setName(""); // Void type should not have a name.
9265
Devang Pateld222f862008-09-25 21:00:45 +00009266 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009267
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009268 Instruction *NC;
9269 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009270 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009271 Args.begin(), Args.end(),
9272 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009273 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009274 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009275 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009276 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9277 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009278 CallInst *CI = cast<CallInst>(Caller);
9279 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009280 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009281 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009282 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009283 }
9284
9285 // Insert a cast of the return type as necessary.
9286 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009287 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009288 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009289 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009290 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009291 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009292
9293 // If this is an invoke instruction, we should insert it after the first
9294 // non-phi, instruction in the normal successor block.
9295 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00009296 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009297 InsertNewInstBefore(NC, *I);
9298 } else {
9299 // Otherwise, it's a call, just insert cast right after the call instr
9300 InsertNewInstBefore(NC, *Caller);
9301 }
9302 AddUsersToWorkList(*Caller);
9303 } else {
9304 NV = UndefValue::get(Caller->getType());
9305 }
9306 }
9307
9308 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9309 Caller->replaceAllUsesWith(NV);
9310 Caller->eraseFromParent();
9311 RemoveFromWorkList(Caller);
9312 return true;
9313}
9314
Duncan Sands74833f22007-09-17 10:26:40 +00009315// transformCallThroughTrampoline - Turn a call to a function created by the
9316// init_trampoline intrinsic into a direct call to the underlying function.
9317//
9318Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9319 Value *Callee = CS.getCalledValue();
9320 const PointerType *PTy = cast<PointerType>(Callee->getType());
9321 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +00009322 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +00009323
9324 // If the call already has the 'nest' attribute somewhere then give up -
9325 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +00009326 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009327 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009328
9329 IntrinsicInst *Tramp =
9330 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9331
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009332 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009333 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9334 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9335
Devang Pateld222f862008-09-25 21:00:45 +00009336 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009337 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009338 unsigned NestIdx = 1;
9339 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +00009340 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009341
9342 // Look for a parameter marked with the 'nest' attribute.
9343 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9344 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +00009345 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009346 // Record the parameter type and any other attributes.
9347 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +00009348 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009349 break;
9350 }
9351
9352 if (NestTy) {
9353 Instruction *Caller = CS.getInstruction();
9354 std::vector<Value*> NewArgs;
9355 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9356
Devang Pateld222f862008-09-25 21:00:45 +00009357 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009358 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009359
Duncan Sands74833f22007-09-17 10:26:40 +00009360 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009361 // mean appending it. Likewise for attributes.
9362
Devang Patelf2a4a922008-09-26 22:53:05 +00009363 // Add any result attributes.
9364 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +00009365 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009366
Duncan Sands74833f22007-09-17 10:26:40 +00009367 {
9368 unsigned Idx = 1;
9369 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9370 do {
9371 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009372 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009373 Value *NestVal = Tramp->getOperand(3);
9374 if (NestVal->getType() != NestTy)
9375 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9376 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +00009377 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009378 }
9379
9380 if (I == E)
9381 break;
9382
Duncan Sands48b81112008-01-14 19:52:09 +00009383 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009384 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +00009385 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009386 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +00009387 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009388
9389 ++Idx, ++I;
9390 } while (1);
9391 }
9392
Devang Patelf2a4a922008-09-26 22:53:05 +00009393 // Add any function attributes.
9394 if (Attributes Attr = Attrs.getFnAttributes())
9395 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9396
Duncan Sands74833f22007-09-17 10:26:40 +00009397 // The trampoline may have been bitcast to a bogus type (FTy).
9398 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009399 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009400
Duncan Sands74833f22007-09-17 10:26:40 +00009401 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009402 NewTypes.reserve(FTy->getNumParams()+1);
9403
Duncan Sands74833f22007-09-17 10:26:40 +00009404 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009405 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009406 {
9407 unsigned Idx = 1;
9408 FunctionType::param_iterator I = FTy->param_begin(),
9409 E = FTy->param_end();
9410
9411 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009412 if (Idx == NestIdx)
9413 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009414 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009415
9416 if (I == E)
9417 break;
9418
Duncan Sands48b81112008-01-14 19:52:09 +00009419 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009420 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009421
9422 ++Idx, ++I;
9423 } while (1);
9424 }
9425
9426 // Replace the trampoline call with a direct call. Let the generic
9427 // code sort out any function type mismatches.
9428 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009429 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009430 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9431 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +00009432 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009433
9434 Instruction *NewCaller;
9435 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009436 NewCaller = InvokeInst::Create(NewCallee,
9437 II->getNormalDest(), II->getUnwindDest(),
9438 NewArgs.begin(), NewArgs.end(),
9439 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009440 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009441 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009442 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009443 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9444 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009445 if (cast<CallInst>(Caller)->isTailCall())
9446 cast<CallInst>(NewCaller)->setTailCall();
9447 cast<CallInst>(NewCaller)->
9448 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009449 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009450 }
9451 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9452 Caller->replaceAllUsesWith(NewCaller);
9453 Caller->eraseFromParent();
9454 RemoveFromWorkList(Caller);
9455 return 0;
9456 }
9457 }
9458
9459 // Replace the trampoline call with a direct call. Since there is no 'nest'
9460 // parameter, there is no need to adjust the argument list. Let the generic
9461 // code sort out any function type mismatches.
9462 Constant *NewCallee =
9463 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9464 CS.setCalledFunction(NewCallee);
9465 return CS.getInstruction();
9466}
9467
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009468/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9469/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9470/// and a single binop.
9471Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9472 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9473 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9474 isa<CmpInst>(FirstInst));
9475 unsigned Opc = FirstInst->getOpcode();
9476 Value *LHSVal = FirstInst->getOperand(0);
9477 Value *RHSVal = FirstInst->getOperand(1);
9478
9479 const Type *LHSType = LHSVal->getType();
9480 const Type *RHSType = RHSVal->getType();
9481
9482 // Scan to see if all operands are the same opcode, all have one use, and all
9483 // kill their operands (i.e. the operands have one use).
9484 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9485 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9486 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9487 // Verify type of the LHS matches so we don't fold cmp's of different
9488 // types or GEP's with different index types.
9489 I->getOperand(0)->getType() != LHSType ||
9490 I->getOperand(1)->getType() != RHSType)
9491 return 0;
9492
9493 // If they are CmpInst instructions, check their predicates
9494 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9495 if (cast<CmpInst>(I)->getPredicate() !=
9496 cast<CmpInst>(FirstInst)->getPredicate())
9497 return 0;
9498
9499 // Keep track of which operand needs a phi node.
9500 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9501 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9502 }
9503
9504 // Otherwise, this is safe to transform, determine if it is profitable.
9505
9506 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9507 // Indexes are often folded into load/store instructions, so we don't want to
9508 // hide them behind a phi.
9509 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9510 return 0;
9511
9512 Value *InLHS = FirstInst->getOperand(0);
9513 Value *InRHS = FirstInst->getOperand(1);
9514 PHINode *NewLHS = 0, *NewRHS = 0;
9515 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009516 NewLHS = PHINode::Create(LHSType,
9517 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009518 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9519 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9520 InsertNewInstBefore(NewLHS, PN);
9521 LHSVal = NewLHS;
9522 }
9523
9524 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009525 NewRHS = PHINode::Create(RHSType,
9526 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009527 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9528 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9529 InsertNewInstBefore(NewRHS, PN);
9530 RHSVal = NewRHS;
9531 }
9532
9533 // Add all operands to the new PHIs.
9534 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9535 if (NewLHS) {
9536 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9537 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9538 }
9539 if (NewRHS) {
9540 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9541 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9542 }
9543 }
9544
9545 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009546 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009547 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009548 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009549 RHSVal);
9550 else {
9551 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009552 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009553 }
9554}
9555
9556/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9557/// of the block that defines it. This means that it must be obvious the value
9558/// of the load is not changed from the point of the load to the end of the
9559/// block it is in.
9560///
9561/// Finally, it is safe, but not profitable, to sink a load targetting a
9562/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9563/// to a register.
9564static bool isSafeToSinkLoad(LoadInst *L) {
9565 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9566
9567 for (++BBI; BBI != E; ++BBI)
9568 if (BBI->mayWriteToMemory())
9569 return false;
9570
9571 // Check for non-address taken alloca. If not address-taken already, it isn't
9572 // profitable to do this xform.
9573 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9574 bool isAddressTaken = false;
9575 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9576 UI != E; ++UI) {
9577 if (isa<LoadInst>(UI)) continue;
9578 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9579 // If storing TO the alloca, then the address isn't taken.
9580 if (SI->getOperand(1) == AI) continue;
9581 }
9582 isAddressTaken = true;
9583 break;
9584 }
9585
9586 if (!isAddressTaken)
9587 return false;
9588 }
9589
9590 return true;
9591}
9592
9593
9594// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9595// operator and they all are only used by the PHI, PHI together their
9596// inputs, and do the operation once, to the result of the PHI.
9597Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9598 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9599
9600 // Scan the instruction, looking for input operations that can be folded away.
9601 // If all input operands to the phi are the same instruction (e.g. a cast from
9602 // the same type or "+42") we can pull the operation through the PHI, reducing
9603 // code size and simplifying code.
9604 Constant *ConstantOp = 0;
9605 const Type *CastSrcTy = 0;
9606 bool isVolatile = false;
9607 if (isa<CastInst>(FirstInst)) {
9608 CastSrcTy = FirstInst->getOperand(0)->getType();
9609 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9610 // Can fold binop, compare or shift here if the RHS is a constant,
9611 // otherwise call FoldPHIArgBinOpIntoPHI.
9612 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9613 if (ConstantOp == 0)
9614 return FoldPHIArgBinOpIntoPHI(PN);
9615 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9616 isVolatile = LI->isVolatile();
9617 // We can't sink the load if the loaded value could be modified between the
9618 // load and the PHI.
9619 if (LI->getParent() != PN.getIncomingBlock(0) ||
9620 !isSafeToSinkLoad(LI))
9621 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +00009622
9623 // If the PHI is of volatile loads and the load block has multiple
9624 // successors, sinking it would remove a load of the volatile value from
9625 // the path through the other successor.
9626 if (isVolatile &&
9627 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9628 return 0;
9629
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009630 } else if (isa<GetElementPtrInst>(FirstInst)) {
9631 if (FirstInst->getNumOperands() == 2)
9632 return FoldPHIArgBinOpIntoPHI(PN);
9633 // Can't handle general GEPs yet.
9634 return 0;
9635 } else {
9636 return 0; // Cannot fold this operation.
9637 }
9638
9639 // Check to see if all arguments are the same operation.
9640 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9641 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9642 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9643 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9644 return 0;
9645 if (CastSrcTy) {
9646 if (I->getOperand(0)->getType() != CastSrcTy)
9647 return 0; // Cast operation must match.
9648 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9649 // We can't sink the load if the loaded value could be modified between
9650 // the load and the PHI.
9651 if (LI->isVolatile() != isVolatile ||
9652 LI->getParent() != PN.getIncomingBlock(i) ||
9653 !isSafeToSinkLoad(LI))
9654 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009655
Chris Lattner2d9fdd82008-07-08 17:18:32 +00009656 // If the PHI is of volatile loads and the load block has multiple
9657 // successors, sinking it would remove a load of the volatile value from
9658 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +00009659 if (isVolatile &&
9660 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9661 return 0;
9662
9663
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009664 } else if (I->getOperand(1) != ConstantOp) {
9665 return 0;
9666 }
9667 }
9668
9669 // Okay, they are all the same operation. Create a new PHI node of the
9670 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009671 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9672 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009673 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9674
9675 Value *InVal = FirstInst->getOperand(0);
9676 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9677
9678 // Add all operands to the new PHI.
9679 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9680 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9681 if (NewInVal != InVal)
9682 InVal = 0;
9683 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9684 }
9685
9686 Value *PhiVal;
9687 if (InVal) {
9688 // The new PHI unions all of the same values together. This is really
9689 // common, so we handle it intelligently here for compile-time speed.
9690 PhiVal = InVal;
9691 delete NewPN;
9692 } else {
9693 InsertNewInstBefore(NewPN, PN);
9694 PhiVal = NewPN;
9695 }
9696
9697 // Insert and return the new operation.
9698 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009699 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009700 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009701 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009702 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009703 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009704 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009705 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9706
9707 // If this was a volatile load that we are merging, make sure to loop through
9708 // and mark all the input loads as non-volatile. If we don't do this, we will
9709 // insert a new volatile load and the old ones will not be deletable.
9710 if (isVolatile)
9711 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9712 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9713
9714 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009715}
9716
9717/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9718/// that is dead.
9719static bool DeadPHICycle(PHINode *PN,
9720 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9721 if (PN->use_empty()) return true;
9722 if (!PN->hasOneUse()) return false;
9723
9724 // Remember this node, and if we find the cycle, return.
9725 if (!PotentiallyDeadPHIs.insert(PN))
9726 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009727
9728 // Don't scan crazily complex things.
9729 if (PotentiallyDeadPHIs.size() == 16)
9730 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009731
9732 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9733 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9734
9735 return false;
9736}
9737
Chris Lattner27b695d2007-11-06 21:52:06 +00009738/// PHIsEqualValue - Return true if this phi node is always equal to
9739/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9740/// z = some value; x = phi (y, z); y = phi (x, z)
9741static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9742 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9743 // See if we already saw this PHI node.
9744 if (!ValueEqualPHIs.insert(PN))
9745 return true;
9746
9747 // Don't scan crazily complex things.
9748 if (ValueEqualPHIs.size() == 16)
9749 return false;
9750
9751 // Scan the operands to see if they are either phi nodes or are equal to
9752 // the value.
9753 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9754 Value *Op = PN->getIncomingValue(i);
9755 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9756 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9757 return false;
9758 } else if (Op != NonPhiInVal)
9759 return false;
9760 }
9761
9762 return true;
9763}
9764
9765
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009766// PHINode simplification
9767//
9768Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9769 // If LCSSA is around, don't mess with Phi nodes
9770 if (MustPreserveLCSSA) return 0;
9771
9772 if (Value *V = PN.hasConstantValue())
9773 return ReplaceInstUsesWith(PN, V);
9774
9775 // If all PHI operands are the same operation, pull them through the PHI,
9776 // reducing code size.
9777 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9778 PN.getIncomingValue(0)->hasOneUse())
9779 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9780 return Result;
9781
9782 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9783 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9784 // PHI)... break the cycle.
9785 if (PN.hasOneUse()) {
9786 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9787 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9788 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9789 PotentiallyDeadPHIs.insert(&PN);
9790 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9791 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9792 }
9793
9794 // If this phi has a single use, and if that use just computes a value for
9795 // the next iteration of a loop, delete the phi. This occurs with unused
9796 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9797 // common case here is good because the only other things that catch this
9798 // are induction variable analysis (sometimes) and ADCE, which is only run
9799 // late.
9800 if (PHIUser->hasOneUse() &&
9801 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9802 PHIUser->use_back() == &PN) {
9803 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9804 }
9805 }
9806
Chris Lattner27b695d2007-11-06 21:52:06 +00009807 // We sometimes end up with phi cycles that non-obviously end up being the
9808 // same value, for example:
9809 // z = some value; x = phi (y, z); y = phi (x, z)
9810 // where the phi nodes don't necessarily need to be in the same block. Do a
9811 // quick check to see if the PHI node only contains a single non-phi value, if
9812 // so, scan to see if the phi cycle is actually equal to that value.
9813 {
9814 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9815 // Scan for the first non-phi operand.
9816 while (InValNo != NumOperandVals &&
9817 isa<PHINode>(PN.getIncomingValue(InValNo)))
9818 ++InValNo;
9819
9820 if (InValNo != NumOperandVals) {
9821 Value *NonPhiInVal = PN.getOperand(InValNo);
9822
9823 // Scan the rest of the operands to see if there are any conflicts, if so
9824 // there is no need to recursively scan other phis.
9825 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9826 Value *OpVal = PN.getIncomingValue(InValNo);
9827 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9828 break;
9829 }
9830
9831 // If we scanned over all operands, then we have one unique value plus
9832 // phi values. Scan PHI nodes to see if they all merge in each other or
9833 // the value.
9834 if (InValNo == NumOperandVals) {
9835 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9836 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9837 return ReplaceInstUsesWith(PN, NonPhiInVal);
9838 }
9839 }
9840 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009841 return 0;
9842}
9843
9844static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9845 Instruction *InsertPoint,
9846 InstCombiner *IC) {
9847 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9848 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9849 // We must cast correctly to the pointer type. Ensure that we
9850 // sign extend the integer value if it is smaller as this is
9851 // used for address computation.
9852 Instruction::CastOps opcode =
9853 (VTySize < PtrSize ? Instruction::SExt :
9854 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9855 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9856}
9857
9858
9859Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9860 Value *PtrOp = GEP.getOperand(0);
9861 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9862 // If so, eliminate the noop.
9863 if (GEP.getNumOperands() == 1)
9864 return ReplaceInstUsesWith(GEP, PtrOp);
9865
9866 if (isa<UndefValue>(GEP.getOperand(0)))
9867 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9868
9869 bool HasZeroPointerIndex = false;
9870 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9871 HasZeroPointerIndex = C->isNullValue();
9872
9873 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9874 return ReplaceInstUsesWith(GEP, PtrOp);
9875
9876 // Eliminate unneeded casts for indices.
9877 bool MadeChange = false;
9878
9879 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009880 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9881 i != e; ++i, ++GTI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009882 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +00009883 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009884 if (CI->getOpcode() == Instruction::ZExt ||
9885 CI->getOpcode() == Instruction::SExt) {
9886 const Type *SrcTy = CI->getOperand(0)->getType();
9887 // We can eliminate a cast from i32 to i64 iff the target
9888 // is a 32-bit pointer target.
9889 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9890 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +00009891 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009892 }
9893 }
9894 }
9895 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +00009896 // to what we need. If narrower, sign-extend it to what we need.
9897 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009898 // insert it. This explicit cast can make subsequent optimizations more
9899 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +00009900 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009901 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009902 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +00009903 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009904 MadeChange = true;
9905 } else {
9906 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9907 GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009908 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009909 MadeChange = true;
9910 }
Dan Gohman5d639ed2008-09-11 23:06:38 +00009911 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
9912 if (Constant *C = dyn_cast<Constant>(Op)) {
9913 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
9914 MadeChange = true;
9915 } else {
9916 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
9917 GEP);
9918 *i = Op;
9919 MadeChange = true;
9920 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009921 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009922 }
9923 }
9924 if (MadeChange) return &GEP;
9925
9926 // If this GEP instruction doesn't move the pointer, and if the input operand
9927 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9928 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009929 if (GEP.hasAllZeroIndices()) {
9930 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9931 // If the bitcast is of an allocation, and the allocation will be
9932 // converted to match the type of the cast, don't touch this.
9933 if (isa<AllocationInst>(BCI->getOperand(0))) {
9934 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009935 if (Instruction *I = visitBitCast(*BCI)) {
9936 if (I != BCI) {
9937 I->takeName(BCI);
9938 BCI->getParent()->getInstList().insert(BCI, I);
9939 ReplaceInstUsesWith(*BCI, I);
9940 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009941 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009942 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009943 }
9944 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9945 }
9946 }
9947
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009948 // Combine Indices - If the source pointer to this getelementptr instruction
9949 // is a getelementptr instruction, combine the indices of the two
9950 // getelementptr instructions into a single instruction.
9951 //
9952 SmallVector<Value*, 8> SrcGEPOperands;
9953 if (User *Src = dyn_castGetElementPtr(PtrOp))
9954 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9955
9956 if (!SrcGEPOperands.empty()) {
9957 // Note that if our source is a gep chain itself that we wait for that
9958 // chain to be resolved before we perform this transformation. This
9959 // avoids us creating a TON of code in some cases.
9960 //
9961 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9962 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9963 return 0; // Wait until our source is folded to completion.
9964
9965 SmallVector<Value*, 8> Indices;
9966
9967 // Find out whether the last index in the source GEP is a sequential idx.
9968 bool EndsWithSequential = false;
9969 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9970 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9971 EndsWithSequential = !isa<StructType>(*I);
9972
9973 // Can we combine the two pointer arithmetics offsets?
9974 if (EndsWithSequential) {
9975 // Replace: gep (gep %P, long B), long A, ...
9976 // With: T = long A+B; gep %P, T, ...
9977 //
9978 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9979 if (SO1 == Constant::getNullValue(SO1->getType())) {
9980 Sum = GO1;
9981 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9982 Sum = SO1;
9983 } else {
9984 // If they aren't the same type, convert both to an integer of the
9985 // target's pointer size.
9986 if (SO1->getType() != GO1->getType()) {
9987 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9988 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9989 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9990 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9991 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009992 unsigned PS = TD->getPointerSizeInBits();
9993 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009994 // Convert GO1 to SO1's type.
9995 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9996
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009997 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009998 // Convert SO1 to GO1's type.
9999 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10000 } else {
10001 const Type *PT = TD->getIntPtrType();
10002 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10003 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10004 }
10005 }
10006 }
10007 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10008 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10009 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000010010 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010011 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10012 }
10013 }
10014
10015 // Recycle the GEP we already have if possible.
10016 if (SrcGEPOperands.size() == 2) {
10017 GEP.setOperand(0, SrcGEPOperands[0]);
10018 GEP.setOperand(1, Sum);
10019 return &GEP;
10020 } else {
10021 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10022 SrcGEPOperands.end()-1);
10023 Indices.push_back(Sum);
10024 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10025 }
10026 } else if (isa<Constant>(*GEP.idx_begin()) &&
10027 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10028 SrcGEPOperands.size() != 1) {
10029 // Otherwise we can do the fold if the first index of the GEP is a zero
10030 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10031 SrcGEPOperands.end());
10032 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10033 }
10034
10035 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010036 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10037 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010038
10039 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10040 // GEP of global variable. If all of the indices for this GEP are
10041 // constants, we can promote this to a constexpr instead of an instruction.
10042
10043 // Scan for nonconstants...
10044 SmallVector<Constant*, 8> Indices;
10045 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10046 for (; I != E && isa<Constant>(*I); ++I)
10047 Indices.push_back(cast<Constant>(*I));
10048
10049 if (I == E) { // If they are all constants...
10050 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10051 &Indices[0],Indices.size());
10052
10053 // Replace all uses of the GEP with the new constexpr...
10054 return ReplaceInstUsesWith(GEP, CE);
10055 }
10056 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10057 if (!isa<PointerType>(X->getType())) {
10058 // Not interesting. Source pointer must be a cast from pointer.
10059 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010060 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10061 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010062 //
10063 // This occurs when the program declares an array extern like "int X[];"
10064 //
10065 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10066 const PointerType *XTy = cast<PointerType>(X->getType());
10067 if (const ArrayType *XATy =
10068 dyn_cast<ArrayType>(XTy->getElementType()))
10069 if (const ArrayType *CATy =
10070 dyn_cast<ArrayType>(CPTy->getElementType()))
10071 if (CATy->getElementType() == XATy->getElementType()) {
10072 // At this point, we know that the cast source type is a pointer
10073 // to an array of the same type as the destination pointer
10074 // array. Because the array type is never stepped over (there
10075 // is a leading zero) we can fold the cast into this GEP.
10076 GEP.setOperand(0, X);
10077 return &GEP;
10078 }
10079 } else if (GEP.getNumOperands() == 2) {
10080 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010081 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10082 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010083 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10084 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10085 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010086 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10087 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010088 Value *Idx[2];
10089 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10090 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010091 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010092 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010093 // V and GEP are both pointer types --> BitCast
10094 return new BitCastInst(V, GEP.getType());
10095 }
10096
10097 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010098 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010099 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010100 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010101
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010102 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010103 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010104 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010105
10106 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10107 // allow either a mul, shift, or constant here.
10108 Value *NewIdx = 0;
10109 ConstantInt *Scale = 0;
10110 if (ArrayEltSize == 1) {
10111 NewIdx = GEP.getOperand(1);
10112 Scale = ConstantInt::get(NewIdx->getType(), 1);
10113 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10114 NewIdx = ConstantInt::get(CI->getType(), 1);
10115 Scale = CI;
10116 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10117 if (Inst->getOpcode() == Instruction::Shl &&
10118 isa<ConstantInt>(Inst->getOperand(1))) {
10119 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10120 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10121 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10122 NewIdx = Inst->getOperand(0);
10123 } else if (Inst->getOpcode() == Instruction::Mul &&
10124 isa<ConstantInt>(Inst->getOperand(1))) {
10125 Scale = cast<ConstantInt>(Inst->getOperand(1));
10126 NewIdx = Inst->getOperand(0);
10127 }
10128 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010129
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010130 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010131 // out, perform the transformation. Note, we don't know whether Scale is
10132 // signed or not. We'll use unsigned version of division/modulo
10133 // operation after making sure Scale doesn't have the sign bit set.
10134 if (Scale && Scale->getSExtValue() >= 0LL &&
10135 Scale->getZExtValue() % ArrayEltSize == 0) {
10136 Scale = ConstantInt::get(Scale->getType(),
10137 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010138 if (Scale->getZExtValue() != 1) {
10139 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010140 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010141 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010142 NewIdx = InsertNewInstBefore(Sc, GEP);
10143 }
10144
10145 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010146 Value *Idx[2];
10147 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10148 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010149 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010150 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010151 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10152 // The NewGEP must be pointer typed, so must the old one -> BitCast
10153 return new BitCastInst(NewGEP, GEP.getType());
10154 }
10155 }
10156 }
10157 }
10158
10159 return 0;
10160}
10161
10162Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10163 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010164 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010165 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10166 const Type *NewTy =
10167 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10168 AllocationInst *New = 0;
10169
10170 // Create and insert the replacement instruction...
10171 if (isa<MallocInst>(AI))
10172 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10173 else {
10174 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10175 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10176 }
10177
10178 InsertNewInstBefore(New, AI);
10179
10180 // Scan to the end of the allocation instructions, to skip over a block of
10181 // allocas if possible...
10182 //
10183 BasicBlock::iterator It = New;
10184 while (isa<AllocationInst>(*It)) ++It;
10185
10186 // Now that I is pointing to the first non-allocation-inst in the block,
10187 // insert our getelementptr instruction...
10188 //
10189 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010190 Value *Idx[2];
10191 Idx[0] = NullIdx;
10192 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010193 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10194 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010195
10196 // Now make everything use the getelementptr instead of the original
10197 // allocation.
10198 return ReplaceInstUsesWith(AI, V);
10199 } else if (isa<UndefValue>(AI.getArraySize())) {
10200 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10201 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010202 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010203
10204 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10205 // Note that we only do this for alloca's, because malloc should allocate and
10206 // return a unique pointer, even for a zero byte allocation.
10207 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010208 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010209 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10210
10211 return 0;
10212}
10213
10214Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10215 Value *Op = FI.getOperand(0);
10216
10217 // free undef -> unreachable.
10218 if (isa<UndefValue>(Op)) {
10219 // Insert a new store to null because we cannot modify the CFG here.
10220 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010221 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010222 return EraseInstFromFunction(FI);
10223 }
10224
10225 // If we have 'free null' delete the instruction. This can happen in stl code
10226 // when lots of inlining happens.
10227 if (isa<ConstantPointerNull>(Op))
10228 return EraseInstFromFunction(FI);
10229
10230 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10231 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10232 FI.setOperand(0, CI->getOperand(0));
10233 return &FI;
10234 }
10235
10236 // Change free (gep X, 0,0,0,0) into free(X)
10237 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10238 if (GEPI->hasAllZeroIndices()) {
10239 AddToWorkList(GEPI);
10240 FI.setOperand(0, GEPI->getOperand(0));
10241 return &FI;
10242 }
10243 }
10244
10245 // Change free(malloc) into nothing, if the malloc has a single use.
10246 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10247 if (MI->hasOneUse()) {
10248 EraseInstFromFunction(FI);
10249 return EraseInstFromFunction(*MI);
10250 }
10251
10252 return 0;
10253}
10254
10255
10256/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010257static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010258 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010259 User *CI = cast<User>(LI.getOperand(0));
10260 Value *CastOp = CI->getOperand(0);
10261
Devang Patela0f8ea82007-10-18 19:52:32 +000010262 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10263 // Instead of loading constant c string, use corresponding integer value
10264 // directly if string length is small enough.
Evan Cheng833501d2008-06-30 07:31:25 +000010265 std::string Str;
10266 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010267 unsigned len = Str.length();
10268 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10269 unsigned numBits = Ty->getPrimitiveSizeInBits();
10270 // Replace LI with immediate integer store.
10271 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010272 APInt StrVal(numBits, 0);
10273 APInt SingleChar(numBits, 0);
10274 if (TD->isLittleEndian()) {
10275 for (signed i = len-1; i >= 0; i--) {
10276 SingleChar = (uint64_t) Str[i];
10277 StrVal = (StrVal << 8) | SingleChar;
10278 }
10279 } else {
10280 for (unsigned i = 0; i < len; i++) {
10281 SingleChar = (uint64_t) Str[i];
10282 StrVal = (StrVal << 8) | SingleChar;
10283 }
10284 // Append NULL at the end.
10285 SingleChar = 0;
10286 StrVal = (StrVal << 8) | SingleChar;
10287 }
10288 Value *NL = ConstantInt::get(StrVal);
10289 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010290 }
10291 }
10292 }
10293
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010294 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10295 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10296 const Type *SrcPTy = SrcTy->getElementType();
10297
10298 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10299 isa<VectorType>(DestPTy)) {
10300 // If the source is an array, the code below will not succeed. Check to
10301 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10302 // constants.
10303 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10304 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10305 if (ASrcTy->getNumElements() != 0) {
10306 Value *Idxs[2];
10307 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10308 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10309 SrcTy = cast<PointerType>(CastOp->getType());
10310 SrcPTy = SrcTy->getElementType();
10311 }
10312
10313 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10314 isa<VectorType>(SrcPTy)) &&
10315 // Do not allow turning this into a load of an integer, which is then
10316 // casted to a pointer, this pessimizes pointer analysis a lot.
10317 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10318 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10319 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10320
10321 // Okay, we are casting from one integer or pointer type to another of
10322 // the same size. Instead of casting the pointer before the load, cast
10323 // the result of the loaded value.
10324 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10325 CI->getName(),
10326 LI.isVolatile()),LI);
10327 // Now cast the result of the load.
10328 return new BitCastInst(NewLoad, LI.getType());
10329 }
10330 }
10331 }
10332 return 0;
10333}
10334
10335/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10336/// from this value cannot trap. If it is not obviously safe to load from the
10337/// specified pointer, we do a quick local scan of the basic block containing
10338/// ScanFrom, to determine if the address is already accessed.
10339static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010340 // If it is an alloca it is always safe to load from.
10341 if (isa<AllocaInst>(V)) return true;
10342
Duncan Sandse40a94a2007-09-19 10:25:38 +000010343 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010344 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010345 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010346 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010347
10348 // Otherwise, be a little bit agressive by scanning the local block where we
10349 // want to check to see if the pointer is already being loaded or stored
10350 // from/to. If so, the previous load or store would have already trapped,
10351 // so there is no harm doing an extra load (also, CSE will later eliminate
10352 // the load entirely).
10353 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10354
10355 while (BBI != E) {
10356 --BBI;
10357
Chris Lattner476983a2008-06-20 05:12:56 +000010358 // If we see a free or a call (which might do a free) the pointer could be
10359 // marked invalid.
10360 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10361 return false;
10362
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010363 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10364 if (LI->getOperand(0) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010365 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010366 if (SI->getOperand(1) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010367 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010368
10369 }
10370 return false;
10371}
10372
10373Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10374 Value *Op = LI.getOperand(0);
10375
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010376 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010377 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10378 if (KnownAlign >
10379 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10380 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010381 LI.setAlignment(KnownAlign);
10382
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010383 // load (cast X) --> cast (load X) iff safe
10384 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010385 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010386 return Res;
10387
10388 // None of the following transforms are legal for volatile loads.
10389 if (LI.isVolatile()) return 0;
10390
10391 if (&LI.getParent()->front() != &LI) {
10392 BasicBlock::iterator BBI = &LI; --BBI;
10393 // If the instruction immediately before this is a store to the same
10394 // address, do a simple form of store->load forwarding.
10395 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10396 if (SI->getOperand(1) == LI.getOperand(0))
10397 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10398 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10399 if (LIB->getOperand(0) == LI.getOperand(0))
10400 return ReplaceInstUsesWith(LI, LIB);
10401 }
10402
Christopher Lamb2c175392007-12-29 07:56:53 +000010403 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10404 const Value *GEPI0 = GEPI->getOperand(0);
10405 // TODO: Consider a target hook for valid address spaces for this xform.
10406 if (isa<ConstantPointerNull>(GEPI0) &&
10407 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010408 // Insert a new store to null instruction before the load to indicate
10409 // that this code is not reachable. We do this instead of inserting
10410 // an unreachable instruction directly because we cannot modify the
10411 // CFG.
10412 new StoreInst(UndefValue::get(LI.getType()),
10413 Constant::getNullValue(Op->getType()), &LI);
10414 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10415 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010416 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010417
10418 if (Constant *C = dyn_cast<Constant>(Op)) {
10419 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010420 // TODO: Consider a target hook for valid address spaces for this xform.
10421 if (isa<UndefValue>(C) || (C->isNullValue() &&
10422 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010423 // Insert a new store to null instruction before the load to indicate that
10424 // this code is not reachable. We do this instead of inserting an
10425 // unreachable instruction directly because we cannot modify the CFG.
10426 new StoreInst(UndefValue::get(LI.getType()),
10427 Constant::getNullValue(Op->getType()), &LI);
10428 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10429 }
10430
10431 // Instcombine load (constant global) into the value loaded.
10432 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10433 if (GV->isConstant() && !GV->isDeclaration())
10434 return ReplaceInstUsesWith(LI, GV->getInitializer());
10435
10436 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010437 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010438 if (CE->getOpcode() == Instruction::GetElementPtr) {
10439 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10440 if (GV->isConstant() && !GV->isDeclaration())
10441 if (Constant *V =
10442 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10443 return ReplaceInstUsesWith(LI, V);
10444 if (CE->getOperand(0)->isNullValue()) {
10445 // Insert a new store to null instruction before the load to indicate
10446 // that this code is not reachable. We do this instead of inserting
10447 // an unreachable instruction directly because we cannot modify the
10448 // CFG.
10449 new StoreInst(UndefValue::get(LI.getType()),
10450 Constant::getNullValue(Op->getType()), &LI);
10451 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10452 }
10453
10454 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010455 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010456 return Res;
10457 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010458 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010459 }
Chris Lattner0270a112007-08-11 18:48:48 +000010460
10461 // If this load comes from anywhere in a constant global, and if the global
10462 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000010463 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner0270a112007-08-11 18:48:48 +000010464 if (GV->isConstant() && GV->hasInitializer()) {
10465 if (GV->getInitializer()->isNullValue())
10466 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10467 else if (isa<UndefValue>(GV->getInitializer()))
10468 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10469 }
10470 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010471
10472 if (Op->hasOneUse()) {
10473 // Change select and PHI nodes to select values instead of addresses: this
10474 // helps alias analysis out a lot, allows many others simplifications, and
10475 // exposes redundancy in the code.
10476 //
10477 // Note that we cannot do the transformation unless we know that the
10478 // introduced loads cannot trap! Something like this is valid as long as
10479 // the condition is always false: load (select bool %C, int* null, int* %G),
10480 // but it would not be valid if we transformed it to load from null
10481 // unconditionally.
10482 //
10483 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10484 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10485 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10486 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10487 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10488 SI->getOperand(1)->getName()+".val"), LI);
10489 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10490 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010491 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010492 }
10493
10494 // load (select (cond, null, P)) -> load P
10495 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10496 if (C->isNullValue()) {
10497 LI.setOperand(0, SI->getOperand(2));
10498 return &LI;
10499 }
10500
10501 // load (select (cond, P, null)) -> load P
10502 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10503 if (C->isNullValue()) {
10504 LI.setOperand(0, SI->getOperand(1));
10505 return &LI;
10506 }
10507 }
10508 }
10509 return 0;
10510}
10511
10512/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10513/// when possible.
10514static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10515 User *CI = cast<User>(SI.getOperand(1));
10516 Value *CastOp = CI->getOperand(0);
10517
10518 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10519 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10520 const Type *SrcPTy = SrcTy->getElementType();
10521
10522 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10523 // If the source is an array, the code below will not succeed. Check to
10524 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10525 // constants.
10526 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10527 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10528 if (ASrcTy->getNumElements() != 0) {
10529 Value* Idxs[2];
10530 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10531 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10532 SrcTy = cast<PointerType>(CastOp->getType());
10533 SrcPTy = SrcTy->getElementType();
10534 }
10535
10536 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10537 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10538 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10539
10540 // Okay, we are casting from one integer or pointer type to another of
10541 // the same size. Instead of casting the pointer before
10542 // the store, cast the value to be stored.
10543 Value *NewCast;
10544 Value *SIOp0 = SI.getOperand(0);
10545 Instruction::CastOps opcode = Instruction::BitCast;
10546 const Type* CastSrcTy = SIOp0->getType();
10547 const Type* CastDstTy = SrcPTy;
10548 if (isa<PointerType>(CastDstTy)) {
10549 if (CastSrcTy->isInteger())
10550 opcode = Instruction::IntToPtr;
10551 } else if (isa<IntegerType>(CastDstTy)) {
10552 if (isa<PointerType>(SIOp0->getType()))
10553 opcode = Instruction::PtrToInt;
10554 }
10555 if (Constant *C = dyn_cast<Constant>(SIOp0))
10556 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10557 else
10558 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010559 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010560 SI);
10561 return new StoreInst(NewCast, CastOp);
10562 }
10563 }
10564 }
10565 return 0;
10566}
10567
10568Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10569 Value *Val = SI.getOperand(0);
10570 Value *Ptr = SI.getOperand(1);
10571
10572 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10573 EraseInstFromFunction(SI);
10574 ++NumCombined;
10575 return 0;
10576 }
10577
10578 // If the RHS is an alloca with a single use, zapify the store, making the
10579 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010580 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010581 if (isa<AllocaInst>(Ptr)) {
10582 EraseInstFromFunction(SI);
10583 ++NumCombined;
10584 return 0;
10585 }
10586
10587 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10588 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10589 GEP->getOperand(0)->hasOneUse()) {
10590 EraseInstFromFunction(SI);
10591 ++NumCombined;
10592 return 0;
10593 }
10594 }
10595
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010596 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010597 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10598 if (KnownAlign >
10599 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10600 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010601 SI.setAlignment(KnownAlign);
10602
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010603 // Do really simple DSE, to catch cases where there are several consequtive
10604 // stores to the same location, separated by a few arithmetic operations. This
10605 // situation often occurs with bitfield accesses.
10606 BasicBlock::iterator BBI = &SI;
10607 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10608 --ScanInsts) {
10609 --BBI;
10610
10611 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10612 // Prev store isn't volatile, and stores to the same location?
10613 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10614 ++NumDeadStore;
10615 ++BBI;
10616 EraseInstFromFunction(*PrevSI);
10617 continue;
10618 }
10619 break;
10620 }
10621
10622 // If this is a load, we have to stop. However, if the loaded value is from
10623 // the pointer we're loading and is producing the pointer we're storing,
10624 // then *this* store is dead (X = load P; store X -> P).
10625 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010626 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010627 EraseInstFromFunction(SI);
10628 ++NumCombined;
10629 return 0;
10630 }
10631 // Otherwise, this is a load from some other location. Stores before it
10632 // may not be dead.
10633 break;
10634 }
10635
10636 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010637 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010638 break;
10639 }
10640
10641
10642 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10643
10644 // store X, null -> turns into 'unreachable' in SimplifyCFG
10645 if (isa<ConstantPointerNull>(Ptr)) {
10646 if (!isa<UndefValue>(Val)) {
10647 SI.setOperand(0, UndefValue::get(Val->getType()));
10648 if (Instruction *U = dyn_cast<Instruction>(Val))
10649 AddToWorkList(U); // Dropped a use.
10650 ++NumCombined;
10651 }
10652 return 0; // Do not modify these!
10653 }
10654
10655 // store undef, Ptr -> noop
10656 if (isa<UndefValue>(Val)) {
10657 EraseInstFromFunction(SI);
10658 ++NumCombined;
10659 return 0;
10660 }
10661
10662 // If the pointer destination is a cast, see if we can fold the cast into the
10663 // source instead.
10664 if (isa<CastInst>(Ptr))
10665 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10666 return Res;
10667 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10668 if (CE->isCast())
10669 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10670 return Res;
10671
10672
10673 // If this store is the last instruction in the basic block, and if the block
10674 // ends with an unconditional branch, try to move it to the successor block.
10675 BBI = &SI; ++BBI;
10676 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10677 if (BI->isUnconditional())
10678 if (SimplifyStoreAtEndOfBlock(SI))
10679 return 0; // xform done!
10680
10681 return 0;
10682}
10683
10684/// SimplifyStoreAtEndOfBlock - Turn things like:
10685/// if () { *P = v1; } else { *P = v2 }
10686/// into a phi node with a store in the successor.
10687///
10688/// Simplify things like:
10689/// *P = v1; if () { *P = v2; }
10690/// into a phi node with a store in the successor.
10691///
10692bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10693 BasicBlock *StoreBB = SI.getParent();
10694
10695 // Check to see if the successor block has exactly two incoming edges. If
10696 // so, see if the other predecessor contains a store to the same location.
10697 // if so, insert a PHI node (if needed) and move the stores down.
10698 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10699
10700 // Determine whether Dest has exactly two predecessors and, if so, compute
10701 // the other predecessor.
10702 pred_iterator PI = pred_begin(DestBB);
10703 BasicBlock *OtherBB = 0;
10704 if (*PI != StoreBB)
10705 OtherBB = *PI;
10706 ++PI;
10707 if (PI == pred_end(DestBB))
10708 return false;
10709
10710 if (*PI != StoreBB) {
10711 if (OtherBB)
10712 return false;
10713 OtherBB = *PI;
10714 }
10715 if (++PI != pred_end(DestBB))
10716 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000010717
10718 // Bail out if all the relevant blocks aren't distinct (this can happen,
10719 // for example, if SI is in an infinite loop)
10720 if (StoreBB == DestBB || OtherBB == DestBB)
10721 return false;
10722
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010723 // Verify that the other block ends in a branch and is not otherwise empty.
10724 BasicBlock::iterator BBI = OtherBB->getTerminator();
10725 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10726 if (!OtherBr || BBI == OtherBB->begin())
10727 return false;
10728
10729 // If the other block ends in an unconditional branch, check for the 'if then
10730 // else' case. there is an instruction before the branch.
10731 StoreInst *OtherStore = 0;
10732 if (OtherBr->isUnconditional()) {
10733 // If this isn't a store, or isn't a store to the same location, bail out.
10734 --BBI;
10735 OtherStore = dyn_cast<StoreInst>(BBI);
10736 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10737 return false;
10738 } else {
10739 // Otherwise, the other block ended with a conditional branch. If one of the
10740 // destinations is StoreBB, then we have the if/then case.
10741 if (OtherBr->getSuccessor(0) != StoreBB &&
10742 OtherBr->getSuccessor(1) != StoreBB)
10743 return false;
10744
10745 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10746 // if/then triangle. See if there is a store to the same ptr as SI that
10747 // lives in OtherBB.
10748 for (;; --BBI) {
10749 // Check to see if we find the matching store.
10750 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10751 if (OtherStore->getOperand(1) != SI.getOperand(1))
10752 return false;
10753 break;
10754 }
Eli Friedman3a311d52008-06-13 22:02:12 +000010755 // If we find something that may be using or overwriting the stored
10756 // value, or if we run out of instructions, we can't do the xform.
10757 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010758 BBI == OtherBB->begin())
10759 return false;
10760 }
10761
10762 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000010763 // make sure nothing reads or overwrites the stored value in
10764 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010765 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10766 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000010767 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010768 return false;
10769 }
10770 }
10771
10772 // Insert a PHI node now if we need it.
10773 Value *MergedVal = OtherStore->getOperand(0);
10774 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010775 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010776 PN->reserveOperandSpace(2);
10777 PN->addIncoming(SI.getOperand(0), SI.getParent());
10778 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10779 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10780 }
10781
10782 // Advance to a place where it is safe to insert the new store and
10783 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000010784 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010785 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10786 OtherStore->isVolatile()), *BBI);
10787
10788 // Nuke the old stores.
10789 EraseInstFromFunction(SI);
10790 EraseInstFromFunction(*OtherStore);
10791 ++NumCombined;
10792 return true;
10793}
10794
10795
10796Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10797 // Change br (not X), label True, label False to: br X, label False, True
10798 Value *X = 0;
10799 BasicBlock *TrueDest;
10800 BasicBlock *FalseDest;
10801 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10802 !isa<Constant>(X)) {
10803 // Swap Destinations and condition...
10804 BI.setCondition(X);
10805 BI.setSuccessor(0, FalseDest);
10806 BI.setSuccessor(1, TrueDest);
10807 return &BI;
10808 }
10809
10810 // Cannonicalize fcmp_one -> fcmp_oeq
10811 FCmpInst::Predicate FPred; Value *Y;
10812 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10813 TrueDest, FalseDest)))
10814 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10815 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10816 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10817 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10818 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10819 NewSCC->takeName(I);
10820 // Swap Destinations and condition...
10821 BI.setCondition(NewSCC);
10822 BI.setSuccessor(0, FalseDest);
10823 BI.setSuccessor(1, TrueDest);
10824 RemoveFromWorkList(I);
10825 I->eraseFromParent();
10826 AddToWorkList(NewSCC);
10827 return &BI;
10828 }
10829
10830 // Cannonicalize icmp_ne -> icmp_eq
10831 ICmpInst::Predicate IPred;
10832 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10833 TrueDest, FalseDest)))
10834 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10835 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10836 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10837 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10838 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10839 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10840 NewSCC->takeName(I);
10841 // Swap Destinations and condition...
10842 BI.setCondition(NewSCC);
10843 BI.setSuccessor(0, FalseDest);
10844 BI.setSuccessor(1, TrueDest);
10845 RemoveFromWorkList(I);
10846 I->eraseFromParent();;
10847 AddToWorkList(NewSCC);
10848 return &BI;
10849 }
10850
10851 return 0;
10852}
10853
10854Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10855 Value *Cond = SI.getCondition();
10856 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10857 if (I->getOpcode() == Instruction::Add)
10858 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10859 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10860 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10861 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10862 AddRHS));
10863 SI.setOperand(0, I->getOperand(0));
10864 AddToWorkList(I);
10865 return &SI;
10866 }
10867 }
10868 return 0;
10869}
10870
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010871Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000010872 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010873
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000010874 if (!EV.hasIndices())
10875 return ReplaceInstUsesWith(EV, Agg);
10876
10877 if (Constant *C = dyn_cast<Constant>(Agg)) {
10878 if (isa<UndefValue>(C))
10879 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10880
10881 if (isa<ConstantAggregateZero>(C))
10882 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10883
10884 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10885 // Extract the element indexed by the first index out of the constant
10886 Value *V = C->getOperand(*EV.idx_begin());
10887 if (EV.getNumIndices() > 1)
10888 // Extract the remaining indices out of the constant indexed by the
10889 // first index
10890 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10891 else
10892 return ReplaceInstUsesWith(EV, V);
10893 }
10894 return 0; // Can't handle other constants
10895 }
10896 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10897 // We're extracting from an insertvalue instruction, compare the indices
10898 const unsigned *exti, *exte, *insi, *inse;
10899 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10900 exte = EV.idx_end(), inse = IV->idx_end();
10901 exti != exte && insi != inse;
10902 ++exti, ++insi) {
10903 if (*insi != *exti)
10904 // The insert and extract both reference distinctly different elements.
10905 // This means the extract is not influenced by the insert, and we can
10906 // replace the aggregate operand of the extract with the aggregate
10907 // operand of the insert. i.e., replace
10908 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10909 // %E = extractvalue { i32, { i32 } } %I, 0
10910 // with
10911 // %E = extractvalue { i32, { i32 } } %A, 0
10912 return ExtractValueInst::Create(IV->getAggregateOperand(),
10913 EV.idx_begin(), EV.idx_end());
10914 }
10915 if (exti == exte && insi == inse)
10916 // Both iterators are at the end: Index lists are identical. Replace
10917 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10918 // %C = extractvalue { i32, { i32 } } %B, 1, 0
10919 // with "i32 42"
10920 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10921 if (exti == exte) {
10922 // The extract list is a prefix of the insert list. i.e. replace
10923 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10924 // %E = extractvalue { i32, { i32 } } %I, 1
10925 // with
10926 // %X = extractvalue { i32, { i32 } } %A, 1
10927 // %E = insertvalue { i32 } %X, i32 42, 0
10928 // by switching the order of the insert and extract (though the
10929 // insertvalue should be left in, since it may have other uses).
10930 Value *NewEV = InsertNewInstBefore(
10931 ExtractValueInst::Create(IV->getAggregateOperand(),
10932 EV.idx_begin(), EV.idx_end()),
10933 EV);
10934 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10935 insi, inse);
10936 }
10937 if (insi == inse)
10938 // The insert list is a prefix of the extract list
10939 // We can simply remove the common indices from the extract and make it
10940 // operate on the inserted value instead of the insertvalue result.
10941 // i.e., replace
10942 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10943 // %E = extractvalue { i32, { i32 } } %I, 1, 0
10944 // with
10945 // %E extractvalue { i32 } { i32 42 }, 0
10946 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
10947 exti, exte);
10948 }
10949 // Can't simplify extracts from other values. Note that nested extracts are
10950 // already simplified implicitely by the above (extract ( extract (insert) )
10951 // will be translated into extract ( insert ( extract ) ) first and then just
10952 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010953 return 0;
10954}
10955
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010956/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10957/// is to leave as a vector operation.
10958static bool CheapToScalarize(Value *V, bool isConstant) {
10959 if (isa<ConstantAggregateZero>(V))
10960 return true;
10961 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10962 if (isConstant) return true;
10963 // If all elts are the same, we can extract.
10964 Constant *Op0 = C->getOperand(0);
10965 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10966 if (C->getOperand(i) != Op0)
10967 return false;
10968 return true;
10969 }
10970 Instruction *I = dyn_cast<Instruction>(V);
10971 if (!I) return false;
10972
10973 // Insert element gets simplified to the inserted element or is deleted if
10974 // this is constant idx extract element and its a constant idx insertelt.
10975 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10976 isa<ConstantInt>(I->getOperand(2)))
10977 return true;
10978 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10979 return true;
10980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10981 if (BO->hasOneUse() &&
10982 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10983 CheapToScalarize(BO->getOperand(1), isConstant)))
10984 return true;
10985 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10986 if (CI->hasOneUse() &&
10987 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10988 CheapToScalarize(CI->getOperand(1), isConstant)))
10989 return true;
10990
10991 return false;
10992}
10993
10994/// Read and decode a shufflevector mask.
10995///
10996/// It turns undef elements into values that are larger than the number of
10997/// elements in the input.
10998static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10999 unsigned NElts = SVI->getType()->getNumElements();
11000 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11001 return std::vector<unsigned>(NElts, 0);
11002 if (isa<UndefValue>(SVI->getOperand(2)))
11003 return std::vector<unsigned>(NElts, 2*NElts);
11004
11005 std::vector<unsigned> Result;
11006 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000011007 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11008 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011009 Result.push_back(NElts*2); // undef -> 8
11010 else
Gabor Greif17396002008-06-12 21:37:33 +000011011 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011012 return Result;
11013}
11014
11015/// FindScalarElement - Given a vector and an element number, see if the scalar
11016/// value is already around as a register, for example if it were inserted then
11017/// extracted from the vector.
11018static Value *FindScalarElement(Value *V, unsigned EltNo) {
11019 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11020 const VectorType *PTy = cast<VectorType>(V->getType());
11021 unsigned Width = PTy->getNumElements();
11022 if (EltNo >= Width) // Out of range access.
11023 return UndefValue::get(PTy->getElementType());
11024
11025 if (isa<UndefValue>(V))
11026 return UndefValue::get(PTy->getElementType());
11027 else if (isa<ConstantAggregateZero>(V))
11028 return Constant::getNullValue(PTy->getElementType());
11029 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11030 return CP->getOperand(EltNo);
11031 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11032 // If this is an insert to a variable element, we don't know what it is.
11033 if (!isa<ConstantInt>(III->getOperand(2)))
11034 return 0;
11035 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11036
11037 // If this is an insert to the element we are looking for, return the
11038 // inserted value.
11039 if (EltNo == IIElt)
11040 return III->getOperand(1);
11041
11042 // Otherwise, the insertelement doesn't modify the value, recurse on its
11043 // vector input.
11044 return FindScalarElement(III->getOperand(0), EltNo);
11045 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11046 unsigned InEl = getShuffleMask(SVI)[EltNo];
11047 if (InEl < Width)
11048 return FindScalarElement(SVI->getOperand(0), InEl);
11049 else if (InEl < Width*2)
11050 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11051 else
11052 return UndefValue::get(PTy->getElementType());
11053 }
11054
11055 // Otherwise, we don't know.
11056 return 0;
11057}
11058
11059Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011060 // If vector val is undef, replace extract with scalar undef.
11061 if (isa<UndefValue>(EI.getOperand(0)))
11062 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11063
11064 // If vector val is constant 0, replace extract with scalar 0.
11065 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11066 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11067
11068 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000011069 // If vector val is constant with all elements the same, replace EI with
11070 // that element. When the elements are not identical, we cannot replace yet
11071 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011072 Constant *op0 = C->getOperand(0);
11073 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11074 if (C->getOperand(i) != op0) {
11075 op0 = 0;
11076 break;
11077 }
11078 if (op0)
11079 return ReplaceInstUsesWith(EI, op0);
11080 }
11081
11082 // If extracting a specified index from the vector, see if we can recursively
11083 // find a previously computed scalar that was inserted into the vector.
11084 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11085 unsigned IndexVal = IdxC->getZExtValue();
11086 unsigned VectorWidth =
11087 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11088
11089 // If this is extracting an invalid index, turn this into undef, to avoid
11090 // crashing the code below.
11091 if (IndexVal >= VectorWidth)
11092 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11093
11094 // This instruction only demands the single element from the input vector.
11095 // If the input vector has a single use, simplify it based on this use
11096 // property.
11097 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11098 uint64_t UndefElts;
11099 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11100 1 << IndexVal,
11101 UndefElts)) {
11102 EI.setOperand(0, V);
11103 return &EI;
11104 }
11105 }
11106
11107 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11108 return ReplaceInstUsesWith(EI, Elt);
11109
11110 // If the this extractelement is directly using a bitcast from a vector of
11111 // the same number of elements, see if we can find the source element from
11112 // it. In this case, we will end up needing to bitcast the scalars.
11113 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11114 if (const VectorType *VT =
11115 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11116 if (VT->getNumElements() == VectorWidth)
11117 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11118 return new BitCastInst(Elt, EI.getType());
11119 }
11120 }
11121
11122 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11123 if (I->hasOneUse()) {
11124 // Push extractelement into predecessor operation if legal and
11125 // profitable to do so
11126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11127 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11128 if (CheapToScalarize(BO, isConstantElt)) {
11129 ExtractElementInst *newEI0 =
11130 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11131 EI.getName()+".lhs");
11132 ExtractElementInst *newEI1 =
11133 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11134 EI.getName()+".rhs");
11135 InsertNewInstBefore(newEI0, EI);
11136 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011137 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011138 }
11139 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011140 unsigned AS =
11141 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011142 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11143 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011144 GetElementPtrInst *GEP =
11145 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011146 InsertNewInstBefore(GEP, EI);
11147 return new LoadInst(GEP);
11148 }
11149 }
11150 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11151 // Extracting the inserted element?
11152 if (IE->getOperand(2) == EI.getOperand(1))
11153 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11154 // If the inserted and extracted elements are constants, they must not
11155 // be the same value, extract from the pre-inserted value instead.
11156 if (isa<Constant>(IE->getOperand(2)) &&
11157 isa<Constant>(EI.getOperand(1))) {
11158 AddUsesToWorkList(EI);
11159 EI.setOperand(0, IE->getOperand(0));
11160 return &EI;
11161 }
11162 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11163 // If this is extracting an element from a shufflevector, figure out where
11164 // it came from and extract from the appropriate input element instead.
11165 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11166 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11167 Value *Src;
11168 if (SrcIdx < SVI->getType()->getNumElements())
11169 Src = SVI->getOperand(0);
11170 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11171 SrcIdx -= SVI->getType()->getNumElements();
11172 Src = SVI->getOperand(1);
11173 } else {
11174 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11175 }
11176 return new ExtractElementInst(Src, SrcIdx);
11177 }
11178 }
11179 }
11180 return 0;
11181}
11182
11183/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11184/// elements from either LHS or RHS, return the shuffle mask and true.
11185/// Otherwise, return false.
11186static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11187 std::vector<Constant*> &Mask) {
11188 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11189 "Invalid CollectSingleShuffleElements");
11190 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11191
11192 if (isa<UndefValue>(V)) {
11193 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11194 return true;
11195 } else if (V == LHS) {
11196 for (unsigned i = 0; i != NumElts; ++i)
11197 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11198 return true;
11199 } else if (V == RHS) {
11200 for (unsigned i = 0; i != NumElts; ++i)
11201 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11202 return true;
11203 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11204 // If this is an insert of an extract from some other vector, include it.
11205 Value *VecOp = IEI->getOperand(0);
11206 Value *ScalarOp = IEI->getOperand(1);
11207 Value *IdxOp = IEI->getOperand(2);
11208
11209 if (!isa<ConstantInt>(IdxOp))
11210 return false;
11211 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11212
11213 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11214 // Okay, we can handle this if the vector we are insertinting into is
11215 // transitively ok.
11216 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11217 // If so, update the mask to reflect the inserted undef.
11218 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11219 return true;
11220 }
11221 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11222 if (isa<ConstantInt>(EI->getOperand(1)) &&
11223 EI->getOperand(0)->getType() == V->getType()) {
11224 unsigned ExtractedIdx =
11225 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11226
11227 // This must be extracting from either LHS or RHS.
11228 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11229 // Okay, we can handle this if the vector we are insertinting into is
11230 // transitively ok.
11231 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11232 // If so, update the mask to reflect the inserted value.
11233 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000011234 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011235 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11236 } else {
11237 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011238 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011239 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11240
11241 }
11242 return true;
11243 }
11244 }
11245 }
11246 }
11247 }
11248 // TODO: Handle shufflevector here!
11249
11250 return false;
11251}
11252
11253/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11254/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11255/// that computes V and the LHS value of the shuffle.
11256static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11257 Value *&RHS) {
11258 assert(isa<VectorType>(V->getType()) &&
11259 (RHS == 0 || V->getType() == RHS->getType()) &&
11260 "Invalid shuffle!");
11261 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11262
11263 if (isa<UndefValue>(V)) {
11264 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11265 return V;
11266 } else if (isa<ConstantAggregateZero>(V)) {
11267 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11268 return V;
11269 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11270 // If this is an insert of an extract from some other vector, include it.
11271 Value *VecOp = IEI->getOperand(0);
11272 Value *ScalarOp = IEI->getOperand(1);
11273 Value *IdxOp = IEI->getOperand(2);
11274
11275 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11276 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11277 EI->getOperand(0)->getType() == V->getType()) {
11278 unsigned ExtractedIdx =
11279 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11280 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11281
11282 // Either the extracted from or inserted into vector must be RHSVec,
11283 // otherwise we'd end up with a shuffle of three inputs.
11284 if (EI->getOperand(0) == RHS || RHS == 0) {
11285 RHS = EI->getOperand(0);
11286 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011287 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011288 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11289 return V;
11290 }
11291
11292 if (VecOp == RHS) {
11293 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11294 // Everything but the extracted element is replaced with the RHS.
11295 for (unsigned i = 0; i != NumElts; ++i) {
11296 if (i != InsertedIdx)
11297 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11298 }
11299 return V;
11300 }
11301
11302 // If this insertelement is a chain that comes from exactly these two
11303 // vectors, return the vector and the effective shuffle.
11304 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11305 return EI->getOperand(0);
11306
11307 }
11308 }
11309 }
11310 // TODO: Handle shufflevector here!
11311
11312 // Otherwise, can't do anything fancy. Return an identity vector.
11313 for (unsigned i = 0; i != NumElts; ++i)
11314 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11315 return V;
11316}
11317
11318Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11319 Value *VecOp = IE.getOperand(0);
11320 Value *ScalarOp = IE.getOperand(1);
11321 Value *IdxOp = IE.getOperand(2);
11322
11323 // Inserting an undef or into an undefined place, remove this.
11324 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11325 ReplaceInstUsesWith(IE, VecOp);
11326
11327 // If the inserted element was extracted from some other vector, and if the
11328 // indexes are constant, try to turn this into a shufflevector operation.
11329 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11330 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11331 EI->getOperand(0)->getType() == IE.getType()) {
11332 unsigned NumVectorElts = IE.getType()->getNumElements();
11333 unsigned ExtractedIdx =
11334 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11335 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11336
11337 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11338 return ReplaceInstUsesWith(IE, VecOp);
11339
11340 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11341 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11342
11343 // If we are extracting a value from a vector, then inserting it right
11344 // back into the same place, just use the input vector.
11345 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11346 return ReplaceInstUsesWith(IE, VecOp);
11347
11348 // We could theoretically do this for ANY input. However, doing so could
11349 // turn chains of insertelement instructions into a chain of shufflevector
11350 // instructions, and right now we do not merge shufflevectors. As such,
11351 // only do this in a situation where it is clear that there is benefit.
11352 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11353 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11354 // the values of VecOp, except then one read from EIOp0.
11355 // Build a new shuffle mask.
11356 std::vector<Constant*> Mask;
11357 if (isa<UndefValue>(VecOp))
11358 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11359 else {
11360 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11361 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11362 NumVectorElts));
11363 }
11364 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11365 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11366 ConstantVector::get(Mask));
11367 }
11368
11369 // If this insertelement isn't used by some other insertelement, turn it
11370 // (and any insertelements it points to), into one big shuffle.
11371 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11372 std::vector<Constant*> Mask;
11373 Value *RHS = 0;
11374 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11375 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11376 // We now have a shuffle of LHS, RHS, Mask.
11377 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11378 }
11379 }
11380 }
11381
11382 return 0;
11383}
11384
11385
11386Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11387 Value *LHS = SVI.getOperand(0);
11388 Value *RHS = SVI.getOperand(1);
11389 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11390
11391 bool MadeChange = false;
11392
11393 // Undefined shuffle mask -> undefined value.
11394 if (isa<UndefValue>(SVI.getOperand(2)))
11395 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000011396
11397 uint64_t UndefElts;
11398 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11399 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11400 if (VWidth <= 64 &&
Dan Gohman83b702d2008-09-11 22:47:57 +000011401 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11402 LHS = SVI.getOperand(0);
11403 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000011404 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000011405 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011406
11407 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11408 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11409 if (LHS == RHS || isa<UndefValue>(LHS)) {
11410 if (isa<UndefValue>(LHS) && LHS == RHS) {
11411 // shuffle(undef,undef,mask) -> undef.
11412 return ReplaceInstUsesWith(SVI, LHS);
11413 }
11414
11415 // Remap any references to RHS to use LHS.
11416 std::vector<Constant*> Elts;
11417 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11418 if (Mask[i] >= 2*e)
11419 Elts.push_back(UndefValue::get(Type::Int32Ty));
11420 else {
11421 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000011422 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011423 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanbba96b92008-08-06 18:17:32 +000011424 Elts.push_back(UndefValue::get(Type::Int32Ty));
11425 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000011426 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanbba96b92008-08-06 18:17:32 +000011427 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11428 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011429 }
11430 }
11431 SVI.setOperand(0, SVI.getOperand(1));
11432 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11433 SVI.setOperand(2, ConstantVector::get(Elts));
11434 LHS = SVI.getOperand(0);
11435 RHS = SVI.getOperand(1);
11436 MadeChange = true;
11437 }
11438
11439 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11440 bool isLHSID = true, isRHSID = true;
11441
11442 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11443 if (Mask[i] >= e*2) continue; // Ignore undef values.
11444 // Is this an identity shuffle of the LHS value?
11445 isLHSID &= (Mask[i] == i);
11446
11447 // Is this an identity shuffle of the RHS value?
11448 isRHSID &= (Mask[i]-e == i);
11449 }
11450
11451 // Eliminate identity shuffles.
11452 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11453 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11454
11455 // If the LHS is a shufflevector itself, see if we can combine it with this
11456 // one without producing an unusual shuffle. Here we are really conservative:
11457 // we are absolutely afraid of producing a shuffle mask not in the input
11458 // program, because the code gen may not be smart enough to turn a merged
11459 // shuffle into two specific shuffles: it may produce worse code. As such,
11460 // we only merge two shuffles if the result is one of the two input shuffle
11461 // masks. In this case, merging the shuffles just removes one instruction,
11462 // which we know is safe. This is good for things like turning:
11463 // (splat(splat)) -> splat.
11464 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11465 if (isa<UndefValue>(RHS)) {
11466 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11467
11468 std::vector<unsigned> NewMask;
11469 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11470 if (Mask[i] >= 2*e)
11471 NewMask.push_back(2*e);
11472 else
11473 NewMask.push_back(LHSMask[Mask[i]]);
11474
11475 // If the result mask is equal to the src shuffle or this shuffle mask, do
11476 // the replacement.
11477 if (NewMask == LHSMask || NewMask == Mask) {
11478 std::vector<Constant*> Elts;
11479 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11480 if (NewMask[i] >= e*2) {
11481 Elts.push_back(UndefValue::get(Type::Int32Ty));
11482 } else {
11483 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11484 }
11485 }
11486 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11487 LHSSVI->getOperand(1),
11488 ConstantVector::get(Elts));
11489 }
11490 }
11491 }
11492
11493 return MadeChange ? &SVI : 0;
11494}
11495
11496
11497
11498
11499/// TryToSinkInstruction - Try to move the specified instruction from its
11500/// current block into the beginning of DestBlock, which can only happen if it's
11501/// safe to move the instruction past all of the instructions between it and the
11502/// end of its block.
11503static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11504 assert(I->hasOneUse() && "Invariants didn't hold!");
11505
11506 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011507 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11508 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011509
11510 // Do not sink alloca instructions out of the entry block.
11511 if (isa<AllocaInst>(I) && I->getParent() ==
11512 &DestBlock->getParent()->getEntryBlock())
11513 return false;
11514
11515 // We can only sink load instructions if there is nothing between the load and
11516 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011517 if (I->mayReadFromMemory()) {
11518 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011519 Scan != E; ++Scan)
11520 if (Scan->mayWriteToMemory())
11521 return false;
11522 }
11523
Dan Gohman514277c2008-05-23 21:05:58 +000011524 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011525
11526 I->moveBefore(InsertPos);
11527 ++NumSunkInst;
11528 return true;
11529}
11530
11531
11532/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11533/// all reachable code to the worklist.
11534///
11535/// This has a couple of tricks to make the code faster and more powerful. In
11536/// particular, we constant fold and DCE instructions as we go, to avoid adding
11537/// them to the worklist (this significantly speeds up instcombine on code where
11538/// many instructions are dead or constant). Additionally, if we find a branch
11539/// whose condition is a known constant, we only visit the reachable successors.
11540///
11541static void AddReachableCodeToWorklist(BasicBlock *BB,
11542 SmallPtrSet<BasicBlock*, 64> &Visited,
11543 InstCombiner &IC,
11544 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000011545 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011546 Worklist.push_back(BB);
11547
11548 while (!Worklist.empty()) {
11549 BB = Worklist.back();
11550 Worklist.pop_back();
11551
11552 // We have now visited this block! If we've already been here, ignore it.
11553 if (!Visited.insert(BB)) continue;
11554
11555 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11556 Instruction *Inst = BBI++;
11557
11558 // DCE instruction if trivially dead.
11559 if (isInstructionTriviallyDead(Inst)) {
11560 ++NumDeadInst;
11561 DOUT << "IC: DCE: " << *Inst;
11562 Inst->eraseFromParent();
11563 continue;
11564 }
11565
11566 // ConstantProp instruction if trivially constant.
11567 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11568 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11569 Inst->replaceAllUsesWith(C);
11570 ++NumConstProp;
11571 Inst->eraseFromParent();
11572 continue;
11573 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011574
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011575 IC.AddToWorkList(Inst);
11576 }
11577
11578 // Recursively visit successors. If this is a branch or switch on a
11579 // constant, only visit the reachable successor.
11580 TerminatorInst *TI = BB->getTerminator();
11581 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11582 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11583 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011584 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011585 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011586 continue;
11587 }
11588 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11589 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11590 // See if this is an explicit destination.
11591 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11592 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011593 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011594 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011595 continue;
11596 }
11597
11598 // Otherwise it is the default destination.
11599 Worklist.push_back(SI->getSuccessor(0));
11600 continue;
11601 }
11602 }
11603
11604 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11605 Worklist.push_back(TI->getSuccessor(i));
11606 }
11607}
11608
11609bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11610 bool Changed = false;
11611 TD = &getAnalysis<TargetData>();
11612
11613 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11614 << F.getNameStr() << "\n");
11615
11616 {
11617 // Do a depth-first traversal of the function, populate the worklist with
11618 // the reachable instructions. Ignore blocks that are not reachable. Keep
11619 // track of which blocks we visit.
11620 SmallPtrSet<BasicBlock*, 64> Visited;
11621 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11622
11623 // Do a quick scan over the function. If we find any blocks that are
11624 // unreachable, remove any instructions inside of them. This prevents
11625 // the instcombine code from having to deal with some bad special cases.
11626 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11627 if (!Visited.count(BB)) {
11628 Instruction *Term = BB->getTerminator();
11629 while (Term != BB->begin()) { // Remove instrs bottom-up
11630 BasicBlock::iterator I = Term; --I;
11631
11632 DOUT << "IC: DCE: " << *I;
11633 ++NumDeadInst;
11634
11635 if (!I->use_empty())
11636 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11637 I->eraseFromParent();
11638 }
11639 }
11640 }
11641
11642 while (!Worklist.empty()) {
11643 Instruction *I = RemoveOneFromWorkList();
11644 if (I == 0) continue; // skip null values.
11645
11646 // Check to see if we can DCE the instruction.
11647 if (isInstructionTriviallyDead(I)) {
11648 // Add operands to the worklist.
11649 if (I->getNumOperands() < 4)
11650 AddUsesToWorkList(*I);
11651 ++NumDeadInst;
11652
11653 DOUT << "IC: DCE: " << *I;
11654
11655 I->eraseFromParent();
11656 RemoveFromWorkList(I);
11657 continue;
11658 }
11659
11660 // Instruction isn't dead, see if we can constant propagate it.
11661 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11662 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11663
11664 // Add operands to the worklist.
11665 AddUsesToWorkList(*I);
11666 ReplaceInstUsesWith(*I, C);
11667
11668 ++NumConstProp;
11669 I->eraseFromParent();
11670 RemoveFromWorkList(I);
11671 continue;
11672 }
11673
Nick Lewyckyadb67922008-05-25 20:56:15 +000011674 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11675 // See if we can constant fold its operands.
11676 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11677 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11678 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11679 i->set(NewC);
11680 }
11681 }
11682 }
11683
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011684 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000011685 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011686 BasicBlock *BB = I->getParent();
11687 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11688 if (UserParent != BB) {
11689 bool UserIsSuccessor = false;
11690 // See if the user is one of our successors.
11691 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11692 if (*SI == UserParent) {
11693 UserIsSuccessor = true;
11694 break;
11695 }
11696
11697 // If the user is one of our immediate successors, and if that successor
11698 // only has us as a predecessors (we'd have to split the critical edge
11699 // otherwise), we can keep going.
11700 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11701 next(pred_begin(UserParent)) == pred_end(UserParent))
11702 // Okay, the CFG is simple enough, try to sink this instruction.
11703 Changed |= TryToSinkInstruction(I, UserParent);
11704 }
11705 }
11706
11707 // Now that we have an instruction, try combining it to simplify it...
11708#ifndef NDEBUG
11709 std::string OrigI;
11710#endif
11711 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11712 if (Instruction *Result = visit(*I)) {
11713 ++NumCombined;
11714 // Should we replace the old instruction with a new one?
11715 if (Result != I) {
11716 DOUT << "IC: Old = " << *I
11717 << " New = " << *Result;
11718
11719 // Everything uses the new instruction now.
11720 I->replaceAllUsesWith(Result);
11721
11722 // Push the new instruction and any users onto the worklist.
11723 AddToWorkList(Result);
11724 AddUsersToWorkList(*Result);
11725
11726 // Move the name to the new instruction first.
11727 Result->takeName(I);
11728
11729 // Insert the new instruction into the basic block...
11730 BasicBlock *InstParent = I->getParent();
11731 BasicBlock::iterator InsertPos = I;
11732
11733 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11734 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11735 ++InsertPos;
11736
11737 InstParent->getInstList().insert(InsertPos, Result);
11738
11739 // Make sure that we reprocess all operands now that we reduced their
11740 // use counts.
11741 AddUsesToWorkList(*I);
11742
11743 // Instructions can end up on the worklist more than once. Make sure
11744 // we do not process an instruction that has been deleted.
11745 RemoveFromWorkList(I);
11746
11747 // Erase the old instruction.
11748 InstParent->getInstList().erase(I);
11749 } else {
11750#ifndef NDEBUG
11751 DOUT << "IC: Mod = " << OrigI
11752 << " New = " << *I;
11753#endif
11754
11755 // If the instruction was modified, it's possible that it is now dead.
11756 // if so, remove it.
11757 if (isInstructionTriviallyDead(I)) {
11758 // Make sure we process all operands now that we are reducing their
11759 // use counts.
11760 AddUsesToWorkList(*I);
11761
11762 // Instructions may end up in the worklist more than once. Erase all
11763 // occurrences of this instruction.
11764 RemoveFromWorkList(I);
11765 I->eraseFromParent();
11766 } else {
11767 AddToWorkList(I);
11768 AddUsersToWorkList(*I);
11769 }
11770 }
11771 Changed = true;
11772 }
11773 }
11774
11775 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011776
11777 // Do an explicit clear, this shrinks the map if needed.
11778 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011779 return Changed;
11780}
11781
11782
11783bool InstCombiner::runOnFunction(Function &F) {
11784 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11785
11786 bool EverMadeChange = false;
11787
11788 // Iterate while there is work to do.
11789 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011790 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011791 EverMadeChange = true;
11792 return EverMadeChange;
11793}
11794
11795FunctionPass *llvm::createInstructionCombiningPass() {
11796 return new InstCombiner();
11797}
11798
Chris Lattner6297fc72008-08-11 22:06:05 +000011799