blob: 6222d2ae49bf9499c4743b707118fb6bbea9e13f [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"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Support/Debug.h"
49#include "llvm/Support/GetElementPtrTypeIterator.h"
50#include "llvm/Support/InstVisitor.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/PatternMatch.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/STLExtras.h"
59#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000060#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061#include <sstream>
62using namespace llvm;
63using namespace llvm::PatternMatch;
64
65STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71namespace {
72 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
75 // Worklist of all of the instructions that need to be simplified.
76 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
78 TargetData *TD;
79 bool MustPreserveLCSSA;
80 public:
81 static char ID; // Pass identification, replacement for typeid
82 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
108
109
110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
114 void AddUsersToWorkList(Value &I) {
115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116 UI != UE; ++UI)
117 AddToWorkList(cast<Instruction>(*UI));
118 }
119
120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126 AddToWorkList(Op);
127 }
128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140 AddToWorkList(Op);
141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
147
148 public:
149 virtual bool runOnFunction(Function &F);
150
151 bool DoOneIteration(Function &F, unsigned ItNum);
152
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<TargetData>();
155 AU.addPreservedID(LCSSAID);
156 AU.setPreservesCFG();
157 }
158
159 TargetData &getTargetData() const { return *TD; }
160
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
167 //
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
198
199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
202 BinaryOperator &I);
203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
205 Instruction *commonPointerCastTransforms(CastInst &CI);
206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 Instruction *visitBitCast(BitCastInst &CI);
218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
220 Instruction *visitSelectInst(SelectInst &CI);
221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
225 Instruction *visitAllocationInst(AllocationInst &AI);
226 Instruction *visitFreeInst(FreeInst &FI);
227 Instruction *visitLoadInst(LoadInst &LI);
228 Instruction *visitStoreInst(StoreInst &SI);
229 Instruction *visitBranchInst(BranchInst &BI);
230 Instruction *visitSwitchInst(SwitchInst &SI);
231 Instruction *visitInsertElementInst(InsertElementInst &IE);
232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
234
235 // visitInstruction - Specify what to return for unhandled instructions...
236 Instruction *visitInstruction(Instruction &I) { return 0; }
237
238 private:
239 Instruction *visitCallSite(CallSite CS);
240 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000244 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245
246 public:
247 // InsertNewInstBefore - insert an instruction New before instruction Old
248 // in the program. Add the new instruction to the worklist.
249 //
250 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
251 assert(New && New->getParent() == 0 &&
252 "New instruction already inserted into a basic block!");
253 BasicBlock *BB = Old.getParent();
254 BB->getInstList().insert(&Old, New); // Insert inst
255 AddToWorkList(New);
256 return New;
257 }
258
259 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260 /// This also adds the cast to the worklist. Finally, this returns the
261 /// cast.
262 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
263 Instruction &Pos) {
264 if (V->getType() == Ty) return V;
265
266 if (Constant *CV = dyn_cast<Constant>(V))
267 return ConstantExpr::getCast(opc, CV, Ty);
268
Gabor Greifa645dd32008-05-16 19:29:10 +0000269 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 AddToWorkList(C);
271 return C;
272 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000273
274 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
276 }
277
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278
279 // ReplaceInstUsesWith - This method is to be used when an instruction is
280 // found to be dead, replacable with another preexisting expression. Here
281 // we add all uses of I to the worklist, replace all uses of I with the new
282 // value, then return I, so that the inst combiner will know that I was
283 // modified.
284 //
285 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
286 AddUsersToWorkList(I); // Add all modified instrs to worklist
287 if (&I != V) {
288 I.replaceAllUsesWith(V);
289 return &I;
290 } else {
291 // If we are replacing the instruction with itself, this must be in a
292 // segment of unreachable code, so just clobber the instruction.
293 I.replaceAllUsesWith(UndefValue::get(I.getType()));
294 return &I;
295 }
296 }
297
298 // UpdateValueUsesWith - This method is to be used when an value is
299 // found to be replacable with another preexisting expression or was
300 // updated. Here we add all uses of I to the worklist, replace all uses of
301 // I with the new value (unless the instruction was just updated), then
302 // return true, so that the inst combiner will know that I was modified.
303 //
304 bool UpdateValueUsesWith(Value *Old, Value *New) {
305 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
306 if (Old != New)
307 Old->replaceAllUsesWith(New);
308 if (Instruction *I = dyn_cast<Instruction>(Old))
309 AddToWorkList(I);
310 if (Instruction *I = dyn_cast<Instruction>(New))
311 AddToWorkList(I);
312 return true;
313 }
314
315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
318 // this function.
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
322 RemoveFromWorkList(&I);
323 I.eraseFromParent();
324 return 0; // Don't do anything with FI
325 }
326
327 private:
328 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329 /// InsertBefore instruction. This is specialized a bit to avoid inserting
330 /// casts that are known to not do anything...
331 ///
332 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333 Value *V, const Type *DestTy,
334 Instruction *InsertBefore);
335
336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
338 bool SimplifyCommutative(BinaryOperator &I);
339
340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
343
344 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345 /// on the demanded bits.
346 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
348 unsigned Depth = 0);
349
350 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351 uint64_t &UndefElts, unsigned Depth = 0);
352
353 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354 // PHI node as operand #0, see if we can fold the instruction into the PHI
355 // (which is only possible if all operands to the PHI are constants).
356 Instruction *FoldOpIntoPhi(Instruction &I);
357
358 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359 // operator and they all are only used by the PHI, PHI together their
360 // inputs, and do the operation once, to the result of the PHI.
361 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
362 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
363
364
365 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366 ConstantInt *AndRHS, BinaryOperator &TheAnd);
367
368 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
369 bool isSub, Instruction &I);
370 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
371 bool isSigned, bool Inside, Instruction &IB);
372 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
373 Instruction *MatchBSwap(BinaryOperator &I);
374 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000375 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000376 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000377
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378
379 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000380
Chris Lattner3554f972008-05-20 05:46:13 +0000381 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Dan Gohman5d56fd42008-05-19 22:14:15 +0000382 APInt& KnownOne, unsigned Depth = 0) const;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000383 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
Dan Gohman5d56fd42008-05-19 22:14:15 +0000384 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000385 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
386 unsigned CastOpc,
387 int &NumCastsRemoved);
388 unsigned GetOrEnforceKnownAlignment(Value *V,
389 unsigned PrefAlign = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391}
392
Dan Gohman089efff2008-05-13 00:00:25 +0000393char InstCombiner::ID = 0;
394static RegisterPass<InstCombiner>
395X("instcombine", "Combine redundant instructions");
396
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397// getComplexity: Assign a complexity or rank value to LLVM Values...
398// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
399static unsigned getComplexity(Value *V) {
400 if (isa<Instruction>(V)) {
401 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
402 return 3;
403 return 4;
404 }
405 if (isa<Argument>(V)) return 3;
406 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
407}
408
409// isOnlyUse - Return true if this instruction will be deleted if we stop using
410// it.
411static bool isOnlyUse(Value *V) {
412 return V->hasOneUse() || isa<Constant>(V);
413}
414
415// getPromotedType - Return the specified type promoted as it would be to pass
416// though a va_arg area...
417static const Type *getPromotedType(const Type *Ty) {
418 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419 if (ITy->getBitWidth() < 32)
420 return Type::Int32Ty;
421 }
422 return Ty;
423}
424
425/// getBitCastOperand - If the specified operand is a CastInst or a constant
426/// expression bitcast, return the operand value, otherwise return null.
427static Value *getBitCastOperand(Value *V) {
428 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
429 return I->getOperand(0);
430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
431 if (CE->getOpcode() == Instruction::BitCast)
432 return CE->getOperand(0);
433 return 0;
434}
435
436/// This function is a wrapper around CastInst::isEliminableCastPair. It
437/// simply extracts arguments and returns what that function returns.
438static Instruction::CastOps
439isEliminableCastPair(
440 const CastInst *CI, ///< The first cast instruction
441 unsigned opcode, ///< The opcode of the second cast instruction
442 const Type *DstTy, ///< The target type for the second cast instruction
443 TargetData *TD ///< The target data for pointer size
444) {
445
446 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
447 const Type *MidTy = CI->getType(); // B from above
448
449 // Get the opcodes of the two Cast instructions
450 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
452
453 return Instruction::CastOps(
454 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455 DstTy, TD->getIntPtrType()));
456}
457
458/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459/// in any code being generated. It does not require codegen if V is simple
460/// enough or if the cast can be folded into other casts.
461static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
462 const Type *Ty, TargetData *TD) {
463 if (V->getType() == Ty || isa<Constant>(V)) return false;
464
465 // If this is another cast that can be eliminated, it isn't codegen either.
466 if (const CastInst *CI = dyn_cast<CastInst>(V))
467 if (isEliminableCastPair(CI, opcode, Ty, TD))
468 return false;
469 return true;
470}
471
472/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473/// InsertBefore instruction. This is specialized a bit to avoid inserting
474/// casts that are known to not do anything...
475///
476Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477 Value *V, const Type *DestTy,
478 Instruction *InsertBefore) {
479 if (V->getType() == DestTy) return V;
480 if (Constant *C = dyn_cast<Constant>(V))
481 return ConstantExpr::getCast(opcode, C, DestTy);
482
483 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
484}
485
486// SimplifyCommutative - This performs a few simplifications for commutative
487// operators:
488//
489// 1. Order operands such that they are listed from right (least complex) to
490// left (most complex). This puts constants before unary operators before
491// binary operators.
492//
493// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
495//
496bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
497 bool Changed = false;
498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499 Changed = !I.swapOperands();
500
501 if (!I.isAssociative()) return Changed;
502 Instruction::BinaryOps Opcode = I.getOpcode();
503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505 if (isa<Constant>(I.getOperand(1))) {
506 Constant *Folded = ConstantExpr::get(I.getOpcode(),
507 cast<Constant>(I.getOperand(1)),
508 cast<Constant>(Op->getOperand(1)));
509 I.setOperand(0, Op->getOperand(0));
510 I.setOperand(1, Folded);
511 return true;
512 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514 isOnlyUse(Op) && isOnlyUse(Op1)) {
515 Constant *C1 = cast<Constant>(Op->getOperand(1));
516 Constant *C2 = cast<Constant>(Op1->getOperand(1));
517
518 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
519 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000520 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 Op1->getOperand(0),
522 Op1->getName(), &I);
523 AddToWorkList(New);
524 I.setOperand(0, New);
525 I.setOperand(1, Folded);
526 return true;
527 }
528 }
529 return Changed;
530}
531
532/// SimplifyCompare - For a CmpInst this function just orders the operands
533/// so that theyare listed from right (least complex) to left (most complex).
534/// This puts constants before unary operators before binary operators.
535bool InstCombiner::SimplifyCompare(CmpInst &I) {
536 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
537 return false;
538 I.swapOperands();
539 // Compare instructions are not associative so there's nothing else we can do.
540 return true;
541}
542
543// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544// if the LHS is a constant zero (which is the 'negate' form).
545//
546static inline Value *dyn_castNegVal(Value *V) {
547 if (BinaryOperator::isNeg(V))
548 return BinaryOperator::getNegArgument(V);
549
550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000553
554 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555 if (C->getType()->getElementType()->isInteger())
556 return ConstantExpr::getNeg(C);
557
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 return 0;
559}
560
561static inline Value *dyn_castNotVal(Value *V) {
562 if (BinaryOperator::isNot(V))
563 return BinaryOperator::getNotArgument(V);
564
565 // Constants can be considered to be not'ed values...
566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
567 return ConstantInt::get(~C->getValue());
568 return 0;
569}
570
571// dyn_castFoldableMul - If this value is a multiply that can be folded into
572// other computations (because it has a constant operand), return the
573// non-constant operand of the multiply, and set CST to point to the multiplier.
574// Otherwise, return null.
575//
576static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
577 if (V->hasOneUse() && V->getType()->isInteger())
578 if (Instruction *I = dyn_cast<Instruction>(V)) {
579 if (I->getOpcode() == Instruction::Mul)
580 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
581 return I->getOperand(0);
582 if (I->getOpcode() == Instruction::Shl)
583 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
584 // The multiplier is really 1 << CST.
585 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
586 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
587 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
588 return I->getOperand(0);
589 }
590 }
591 return 0;
592}
593
594/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595/// expression, return it.
596static User *dyn_castGetElementPtr(Value *V) {
597 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599 if (CE->getOpcode() == Instruction::GetElementPtr)
600 return cast<User>(V);
601 return false;
602}
603
Dan Gohman2d648bb2008-04-10 18:43:06 +0000604/// getOpcode - If this is an Instruction or a ConstantExpr, return the
605/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000606static unsigned getOpcode(const Value *V) {
607 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000608 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000609 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000610 return CE->getOpcode();
611 // Use UserOp1 to mean there's no opcode.
612 return Instruction::UserOp1;
613}
614
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615/// AddOne - Add one to a ConstantInt
616static ConstantInt *AddOne(ConstantInt *C) {
617 APInt Val(C->getValue());
618 return ConstantInt::get(++Val);
619}
620/// SubOne - Subtract one from a ConstantInt
621static ConstantInt *SubOne(ConstantInt *C) {
622 APInt Val(C->getValue());
623 return ConstantInt::get(--Val);
624}
625/// Add - Add two ConstantInts together
626static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() + C2->getValue());
628}
629/// And - Bitwise AND two ConstantInts together
630static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631 return ConstantInt::get(C1->getValue() & C2->getValue());
632}
633/// Subtract - Subtract one ConstantInt from another
634static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() - C2->getValue());
636}
637/// Multiply - Multiply two ConstantInts together
638static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() * C2->getValue());
640}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663
664/// ComputeMaskedBits - Determine which of the bits specified in Mask are
665/// known to be either zero or one and return them in the KnownZero/KnownOne
666/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
667/// processing.
668/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
669/// we cannot optimize based on the assumption that it is zero without changing
670/// it to be an explicit zero. If we don't change it to zero, other code could
671/// optimized based on the contradictory assumption that it is non-zero.
672/// Because instcombine aggressively folds operations with undef args anyway,
673/// this won't lose us code quality.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000674void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675 APInt& KnownZero, APInt& KnownOne,
Dan Gohman5d56fd42008-05-19 22:14:15 +0000676 unsigned Depth) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 assert(V && "No Value?");
678 assert(Depth <= 6 && "Limit Search Depth");
679 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000680 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681 "Not integer or pointer type!");
682 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683 (!isa<IntegerType>(V->getType()) ||
684 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 KnownZero.getBitWidth() == BitWidth &&
686 KnownOne.getBitWidth() == BitWidth &&
687 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman5d56fd42008-05-19 22:14:15 +0000688
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000689 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690 // We know all of the bits for a constant!
691 KnownOne = CI->getValue() & Mask;
692 KnownZero = ~KnownOne & Mask;
693 return;
694 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000695 // Null is all-zeros.
696 if (isa<ConstantPointerNull>(V)) {
697 KnownOne.clear();
698 KnownZero = Mask;
699 return;
700 }
701 // The address of an aligned GlobalValue has trailing zeros.
702 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703 unsigned Align = GV->getAlignment();
704 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
705 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
706 if (Align > 0)
707 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708 CountTrailingZeros_32(Align));
709 else
710 KnownZero.clear();
711 KnownOne.clear();
712 return;
713 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714
Dan Gohmanbec16052008-04-28 17:02:21 +0000715 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
716
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 if (Depth == 6 || Mask == 0)
718 return; // Limit search depth.
719
Dan Gohman2d648bb2008-04-10 18:43:06 +0000720 User *I = dyn_cast<User>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 if (!I) return;
722
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000724 switch (getOpcode(I)) {
725 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726 case Instruction::And: {
727 // If either the LHS or the RHS are Zero, the result is zero.
728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
729 APInt Mask2(Mask & ~KnownZero);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733
734 // Output known-1 bits are only known if set in both the LHS & RHS.
735 KnownOne &= KnownOne2;
736 // Output known-0 are known to be clear if zero in either the LHS | RHS.
737 KnownZero |= KnownZero2;
738 return;
739 }
740 case Instruction::Or: {
741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
742 APInt Mask2(Mask & ~KnownOne);
743 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746
747 // Output known-0 bits are only known if clear in both the LHS & RHS.
748 KnownZero &= KnownZero2;
749 // Output known-1 are known to be set if set in either the LHS | RHS.
750 KnownOne |= KnownOne2;
751 return;
752 }
753 case Instruction::Xor: {
754 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
758
759 // Output known-0 bits are known if clear or set in both the LHS & RHS.
760 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761 // Output known-1 are known to be set if set in only one of the LHS, RHS.
762 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763 KnownZero = KnownZeroOut;
764 return;
765 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000766 case Instruction::Mul: {
767 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
772
773 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohmanbec16052008-04-28 17:02:21 +0000774 // Also compute a conserative estimate for high known-0 bits.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000775 // More trickiness is possible, but this is sufficient for the
776 // interesting case of alignment computation.
777 KnownOne.clear();
778 unsigned TrailZ = KnownZero.countTrailingOnes() +
779 KnownZero2.countTrailingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +0000780 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman4c451852008-05-07 00:35:55 +0000781 KnownZero2.countLeadingOnes(),
782 BitWidth) - BitWidth;
Dan Gohmanbec16052008-04-28 17:02:21 +0000783
Dan Gohman2d648bb2008-04-10 18:43:06 +0000784 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000785 LeadZ = std::min(LeadZ, BitWidth);
786 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000788 KnownZero &= Mask;
789 return;
790 }
Dan Gohmanbec16052008-04-28 17:02:21 +0000791 case Instruction::UDiv: {
792 // For the purposes of computing leading zeros we can conservatively
793 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000794 // be less than the denominator.
Dan Gohmanbec16052008-04-28 17:02:21 +0000795 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796 ComputeMaskedBits(I->getOperand(0),
797 AllOnes, KnownZero2, KnownOne2, Depth+1);
798 unsigned LeadZ = KnownZero2.countLeadingOnes();
799
800 KnownOne2.clear();
801 KnownZero2.clear();
802 ComputeMaskedBits(I->getOperand(1),
803 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000804 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805 if (RHSUnknownLeadingOnes != BitWidth)
806 LeadZ = std::min(BitWidth,
807 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000808
809 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
810 return;
811 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 case Instruction::Select:
813 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
816 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
817
818 // Only known if known in both the LHS and RHS.
819 KnownOne &= KnownOne2;
820 KnownZero &= KnownZero2;
821 return;
822 case Instruction::FPTrunc:
823 case Instruction::FPExt:
824 case Instruction::FPToUI:
825 case Instruction::FPToSI:
826 case Instruction::SIToFP:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 case Instruction::UIToFP:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000828 return; // Can't work with floating point.
829 case Instruction::PtrToInt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830 case Instruction::IntToPtr:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000831 // We can't handle these if we don't know the pointer size.
832 if (!TD) return;
Chris Lattnere3061db2008-05-19 20:27:56 +0000833 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000834 case Instruction::ZExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 case Instruction::Trunc: {
Chris Lattnere3061db2008-05-19 20:27:56 +0000836 // Note that we handle pointer operands here because of inttoptr/ptrtoint
837 // which fall through here.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000838 const Type *SrcTy = I->getOperand(0)->getType();
839 uint32_t SrcBitWidth = TD ?
840 TD->getTypeSizeInBits(SrcTy) :
841 SrcTy->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 APInt MaskIn(Mask);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000843 MaskIn.zextOrTrunc(SrcBitWidth);
844 KnownZero.zextOrTrunc(SrcBitWidth);
845 KnownOne.zextOrTrunc(SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000847 KnownZero.zextOrTrunc(BitWidth);
848 KnownOne.zextOrTrunc(BitWidth);
849 // Any top bits are known to be zero.
850 if (BitWidth > SrcBitWidth)
851 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 return;
853 }
854 case Instruction::BitCast: {
855 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000856 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
858 return;
859 }
860 break;
861 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 case Instruction::SExt: {
863 // Compute the bits in the result that are not present in the input.
864 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
865 uint32_t SrcBitWidth = SrcTy->getBitWidth();
866
867 APInt MaskIn(Mask);
868 MaskIn.trunc(SrcBitWidth);
869 KnownZero.trunc(SrcBitWidth);
870 KnownOne.trunc(SrcBitWidth);
871 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
873 KnownZero.zext(BitWidth);
874 KnownOne.zext(BitWidth);
875
876 // If the sign bit of the input is known set or clear, then we know the
877 // top bits of the result.
878 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
879 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
880 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
881 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
882 return;
883 }
884 case Instruction::Shl:
885 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
886 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
887 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
888 APInt Mask2(Mask.lshr(ShiftAmt));
889 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
891 KnownZero <<= ShiftAmt;
892 KnownOne <<= ShiftAmt;
893 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
894 return;
895 }
896 break;
897 case Instruction::LShr:
898 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
899 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900 // Compute the new bits that are at the top now.
901 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
902
903 // Unsigned shift right.
904 APInt Mask2(Mask.shl(ShiftAmt));
905 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
906 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
907 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
909 // high bits known zero.
910 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
911 return;
912 }
913 break;
914 case Instruction::AShr:
915 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
916 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917 // Compute the new bits that are at the top now.
918 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
919
920 // Signed shift right.
921 APInt Mask2(Mask.shl(ShiftAmt));
922 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
926
927 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
929 KnownZero |= HighBits;
930 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
931 KnownOne |= HighBits;
932 return;
933 }
934 break;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000935 case Instruction::Sub: {
936 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937 // We know that the top bits of C-X are clear if X contains less bits
938 // than C (i.e. no wrap-around can happen). For example, 20-X is
939 // positive if we can prove that X is >= 0 and < 16.
940 if (!CLHS->getValue().isNegative()) {
941 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942 // NLZ can't be BitWidth with no sign bit
943 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000944 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
945 Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000946
Dan Gohmanbec16052008-04-28 17:02:21 +0000947 // If all of the MaskV bits are known to be zero, then we know the
948 // output top bits are zero, because we now know that the output is
949 // from [0-C].
950 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohman2d648bb2008-04-10 18:43:06 +0000951 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952 // Top bits known zero.
953 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000954 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000955 }
956 }
957 }
958 // fall through
Duncan Sandse71d4482008-03-21 08:32:17 +0000959 case Instruction::Add: {
Chris Lattner5ee84f82008-03-21 05:19:58 +0000960 // Output known-0 bits are known if clear or set in both the low clear bits
961 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
962 // low 3 bits clear.
Dan Gohmanbec16052008-04-28 17:02:21 +0000963 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
966 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
967
968 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 KnownZeroOut = std::min(KnownZeroOut,
971 KnownZero2.countTrailingOnes());
972
973 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner5ee84f82008-03-21 05:19:58 +0000974 return;
Duncan Sandse71d4482008-03-21 08:32:17 +0000975 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000976 case Instruction::SRem:
977 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978 APInt RA = Rem->getValue();
979 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +0000980 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000981 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
983
984 // The sign of a remainder is equal to the sign of the first
985 // operand (zero being positive).
986 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987 KnownZero2 |= ~LowBits;
988 else if (KnownOne2[BitWidth-1])
989 KnownOne2 |= ~LowBits;
990
991 KnownZero |= KnownZero2 & Mask;
992 KnownOne |= KnownOne2 & Mask;
993
994 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
995 }
996 }
997 break;
Dan Gohmanbec16052008-04-28 17:02:21 +0000998 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000999 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001001 if (RA.isPowerOf2()) {
1002 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001003 APInt Mask2 = LowBits & Mask;
1004 KnownZero |= ~LowBits & Mask;
1005 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001007 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001008 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001009 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001010
1011 // Since the result is less than or equal to either operand, any leading
1012 // zero bits in either operand must also exist in the result.
1013 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1015 Depth+1);
1016 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1017 Depth+1);
1018
1019 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020 KnownZero2.countLeadingOnes());
1021 KnownOne.clear();
1022 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001023 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001024 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00001025
1026 case Instruction::Alloca:
1027 case Instruction::Malloc: {
1028 AllocationInst *AI = cast<AllocationInst>(V);
1029 unsigned Align = AI->getAlignment();
1030 if (Align == 0 && TD) {
1031 if (isa<AllocaInst>(AI))
1032 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033 else if (isa<MallocInst>(AI)) {
1034 // Malloc returns maximally aligned memory.
1035 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1036 Align =
1037 std::max(Align,
1038 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1039 Align =
1040 std::max(Align,
1041 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1042 }
1043 }
1044
1045 if (Align > 0)
1046 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047 CountTrailingZeros_32(Align));
1048 break;
1049 }
1050 case Instruction::GetElementPtr: {
1051 // Analyze all of the subscripts of this getelementptr instruction
1052 // to determine if we can prove known low zero bits.
1053 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055 ComputeMaskedBits(I->getOperand(0), LocalMask,
1056 LocalKnownZero, LocalKnownOne, Depth+1);
1057 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1058
1059 gep_type_iterator GTI = gep_type_begin(I);
1060 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061 Value *Index = I->getOperand(i);
1062 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063 // Handle struct member offset arithmetic.
1064 if (!TD) return;
1065 const StructLayout *SL = TD->getStructLayout(STy);
1066 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067 uint64_t Offset = SL->getElementOffset(Idx);
1068 TrailZ = std::min(TrailZ,
1069 CountTrailingZeros_64(Offset));
1070 } else {
1071 // Handle array index arithmetic.
1072 const Type *IndexedTy = GTI.getIndexedType();
1073 if (!IndexedTy->isSized()) return;
1074 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078 ComputeMaskedBits(Index, LocalMask,
1079 LocalKnownZero, LocalKnownOne, Depth+1);
1080 TrailZ = std::min(TrailZ,
1081 CountTrailingZeros_64(TypeSize) +
1082 LocalKnownZero.countTrailingOnes());
1083 }
1084 }
1085
1086 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1087 break;
1088 }
1089 case Instruction::PHI: {
1090 PHINode *P = cast<PHINode>(I);
1091 // Handle the case of a simple two-predecessor recurrence PHI.
1092 // There's a lot more that could theoretically be done here, but
1093 // this is sufficient to catch some interesting cases.
1094 if (P->getNumIncomingValues() == 2) {
1095 for (unsigned i = 0; i != 2; ++i) {
1096 Value *L = P->getIncomingValue(i);
1097 Value *R = P->getIncomingValue(!i);
1098 User *LU = dyn_cast<User>(L);
Matthijs Kooijmana136c992008-05-23 16:17:48 +00001099 if (!LU)
1100 continue;
1101 unsigned Opcode = getOpcode(LU);
Dan Gohman2d648bb2008-04-10 18:43:06 +00001102 // Check for operations that have the property that if
1103 // both their operands have low zero bits, the result
1104 // will have low zero bits.
1105 if (Opcode == Instruction::Add ||
1106 Opcode == Instruction::Sub ||
1107 Opcode == Instruction::And ||
1108 Opcode == Instruction::Or ||
1109 Opcode == Instruction::Mul) {
1110 Value *LL = LU->getOperand(0);
1111 Value *LR = LU->getOperand(1);
1112 // Find a recurrence.
1113 if (LL == I)
1114 L = LR;
1115 else if (LR == I)
1116 L = LL;
1117 else
1118 break;
1119 // Ok, we have a PHI of the form L op= R. Check for low
1120 // zero bits.
1121 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123 Mask2 = APInt::getLowBitsSet(BitWidth,
1124 KnownZero2.countTrailingOnes());
1125 KnownOne2.clear();
1126 KnownZero2.clear();
1127 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1128 KnownZero = Mask &
1129 APInt::getLowBitsSet(BitWidth,
1130 KnownZero2.countTrailingOnes());
1131 break;
1132 }
1133 }
1134 }
1135 break;
1136 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001137 case Instruction::Call:
1138 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139 switch (II->getIntrinsicID()) {
1140 default: break;
1141 case Intrinsic::ctpop:
1142 case Intrinsic::ctlz:
1143 case Intrinsic::cttz: {
1144 unsigned LowBits = Log2_32(BitWidth)+1;
1145 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1146 break;
1147 }
1148 }
1149 }
1150 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151 }
1152}
1153
1154/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1155/// this predicate to simplify operations downstream. Mask is known to be zero
1156/// for bits that V cannot have.
Dan Gohman2d648bb2008-04-10 18:43:06 +00001157bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1158 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1160 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1162 return (KnownZero & Mask) == Mask;
1163}
1164
1165/// ShrinkDemandedConstant - Check to see if the specified operand of the
1166/// specified instruction is a constant integer. If so, check to see if there
1167/// are any bits set in the constant that are not demanded. If so, shrink the
1168/// constant and return true.
1169static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1170 APInt Demanded) {
1171 assert(I && "No instruction?");
1172 assert(OpNo < I->getNumOperands() && "Operand index too large");
1173
1174 // If the operand is not a constant integer, nothing to do.
1175 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176 if (!OpC) return false;
1177
1178 // If there are no bits set that aren't demanded, nothing to do.
1179 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180 if ((~Demanded & OpC->getValue()) == 0)
1181 return false;
1182
1183 // This instruction is producing bits that are not demanded. Shrink the RHS.
1184 Demanded &= OpC->getValue();
1185 I->setOperand(OpNo, ConstantInt::get(Demanded));
1186 return true;
1187}
1188
1189// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1190// set of known zero and one bits, compute the maximum and minimum values that
1191// could have the specified known zero and known one bits, returning them in
1192// min/max.
1193static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1194 const APInt& KnownZero,
1195 const APInt& KnownOne,
1196 APInt& Min, APInt& Max) {
1197 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198 assert(KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1202 APInt UnknownBits = ~(KnownZero|KnownOne);
1203
1204 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205 // bit if it is unknown.
1206 Min = KnownOne;
1207 Max = KnownOne|UnknownBits;
1208
1209 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1210 Min.set(BitWidth-1);
1211 Max.clear(BitWidth-1);
1212 }
1213}
1214
1215// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216// a set of known zero and one bits, compute the maximum and minimum values that
1217// could have the specified known zero and known one bits, returning them in
1218// min/max.
1219static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +00001220 const APInt &KnownZero,
1221 const APInt &KnownOne,
1222 APInt &Min, APInt &Max) {
1223 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 assert(KnownZero.getBitWidth() == BitWidth &&
1225 KnownOne.getBitWidth() == BitWidth &&
1226 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1228 APInt UnknownBits = ~(KnownZero|KnownOne);
1229
1230 // The minimum value is when the unknown bits are all zeros.
1231 Min = KnownOne;
1232 // The maximum value is when the unknown bits are all ones.
1233 Max = KnownOne|UnknownBits;
1234}
1235
1236/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237/// value based on the demanded bits. When this function is called, it is known
1238/// that only the bits set in DemandedMask of the result of V are ever used
1239/// downstream. Consequently, depending on the mask and V, it may be possible
1240/// to replace V with a constant or one of its operands. In such cases, this
1241/// function does the replacement and returns true. In all other cases, it
1242/// returns false after analyzing the expression and setting KnownOne and known
1243/// to be one in the expression. KnownZero contains all the bits that are known
1244/// to be zero in the expression. These are provided to potentially allow the
1245/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246/// the expression. KnownOne and KnownZero always follow the invariant that
1247/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250/// and KnownOne must all be the same.
1251bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252 APInt& KnownZero, APInt& KnownOne,
1253 unsigned Depth) {
1254 assert(V != 0 && "Null pointer of Value???");
1255 assert(Depth <= 6 && "Limit Search Depth");
1256 uint32_t BitWidth = DemandedMask.getBitWidth();
1257 const IntegerType *VTy = cast<IntegerType>(V->getType());
1258 assert(VTy->getBitWidth() == BitWidth &&
1259 KnownZero.getBitWidth() == BitWidth &&
1260 KnownOne.getBitWidth() == BitWidth &&
1261 "Value *V, DemandedMask, KnownZero and KnownOne \
1262 must have same BitWidth");
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264 // We know all of the bits for a constant!
1265 KnownOne = CI->getValue() & DemandedMask;
1266 KnownZero = ~KnownOne & DemandedMask;
1267 return false;
1268 }
1269
1270 KnownZero.clear();
1271 KnownOne.clear();
1272 if (!V->hasOneUse()) { // Other users may use these bits.
1273 if (Depth != 0) { // Not at the root.
1274 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1276 return false;
1277 }
1278 // If this is the root being simplified, allow it to have multiple uses,
1279 // just set the DemandedMask to all bits.
1280 DemandedMask = APInt::getAllOnesValue(BitWidth);
1281 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1282 if (V != UndefValue::get(VTy))
1283 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1284 return false;
1285 } else if (Depth == 6) { // Limit search depth.
1286 return false;
1287 }
1288
1289 Instruction *I = dyn_cast<Instruction>(V);
1290 if (!I) return false; // Only analyze instructions.
1291
1292 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +00001295 default:
1296 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1297 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 case Instruction::And:
1299 // If either the LHS or the RHS are Zero, the result is zero.
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301 RHSKnownZero, RHSKnownOne, Depth+1))
1302 return true;
1303 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1305
1306 // If something is known zero on the RHS, the bits aren't demanded on the
1307 // LHS.
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309 LHSKnownZero, LHSKnownOne, Depth+1))
1310 return true;
1311 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313
1314 // If all of the demanded bits are known 1 on one side, return the other.
1315 // These bits cannot contribute to the result of the 'and'.
1316 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1317 (DemandedMask & ~LHSKnownZero))
1318 return UpdateValueUsesWith(I, I->getOperand(0));
1319 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1320 (DemandedMask & ~RHSKnownZero))
1321 return UpdateValueUsesWith(I, I->getOperand(1));
1322
1323 // If all of the demanded bits in the inputs are known zeros, return zero.
1324 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1326
1327 // If the RHS is a constant, see if we can simplify it.
1328 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329 return UpdateValueUsesWith(I, I);
1330
1331 // Output known-1 bits are only known if set in both the LHS & RHS.
1332 RHSKnownOne &= LHSKnownOne;
1333 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334 RHSKnownZero |= LHSKnownZero;
1335 break;
1336 case Instruction::Or:
1337 // If either the LHS or the RHS are One, the result is One.
1338 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1339 RHSKnownZero, RHSKnownOne, Depth+1))
1340 return true;
1341 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343 // If something is known one on the RHS, the bits aren't demanded on the
1344 // LHS.
1345 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1346 LHSKnownZero, LHSKnownOne, Depth+1))
1347 return true;
1348 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1350
1351 // If all of the demanded bits are known zero on one side, return the other.
1352 // These bits cannot contribute to the result of the 'or'.
1353 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1354 (DemandedMask & ~LHSKnownOne))
1355 return UpdateValueUsesWith(I, I->getOperand(0));
1356 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1357 (DemandedMask & ~RHSKnownOne))
1358 return UpdateValueUsesWith(I, I->getOperand(1));
1359
1360 // If all of the potentially set bits on one side are known to be set on
1361 // the other side, just use the 'other' side.
1362 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1363 (DemandedMask & (~RHSKnownZero)))
1364 return UpdateValueUsesWith(I, I->getOperand(0));
1365 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1366 (DemandedMask & (~LHSKnownZero)))
1367 return UpdateValueUsesWith(I, I->getOperand(1));
1368
1369 // If the RHS is a constant, see if we can simplify it.
1370 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371 return UpdateValueUsesWith(I, I);
1372
1373 // Output known-0 bits are only known if clear in both the LHS & RHS.
1374 RHSKnownZero &= LHSKnownZero;
1375 // Output known-1 are known to be set if set in either the LHS | RHS.
1376 RHSKnownOne |= LHSKnownOne;
1377 break;
1378 case Instruction::Xor: {
1379 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380 RHSKnownZero, RHSKnownOne, Depth+1))
1381 return true;
1382 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1383 "Bits known to be one AND zero?");
1384 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1385 LHSKnownZero, LHSKnownOne, Depth+1))
1386 return true;
1387 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1388 "Bits known to be one AND zero?");
1389
1390 // If all of the demanded bits are known zero on one side, return the other.
1391 // These bits cannot contribute to the result of the 'xor'.
1392 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393 return UpdateValueUsesWith(I, I->getOperand(0));
1394 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(1));
1396
1397 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1399 (RHSKnownOne & LHSKnownOne);
1400 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1402 (RHSKnownOne & LHSKnownZero);
1403
1404 // If all of the demanded bits are known to be zero on one side or the
1405 // other, turn this into an *inclusive* or.
1406 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1408 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001409 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001410 I->getName());
1411 InsertNewInstBefore(Or, *I);
1412 return UpdateValueUsesWith(I, Or);
1413 }
1414
1415 // If all of the demanded bits on one side are known, and all of the set
1416 // bits on that side are also known to be set on the other side, turn this
1417 // into an AND, as we know the bits will be cleared.
1418 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1420 // all known
1421 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1423 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001424 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 InsertNewInstBefore(And, *I);
1426 return UpdateValueUsesWith(I, And);
1427 }
1428 }
1429
1430 // If the RHS is a constant, see if we can simplify it.
1431 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433 return UpdateValueUsesWith(I, I);
1434
1435 RHSKnownZero = KnownZeroOut;
1436 RHSKnownOne = KnownOneOut;
1437 break;
1438 }
1439 case Instruction::Select:
1440 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441 RHSKnownZero, RHSKnownOne, Depth+1))
1442 return true;
1443 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1444 LHSKnownZero, LHSKnownOne, Depth+1))
1445 return true;
1446 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1447 "Bits known to be one AND zero?");
1448 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1450
1451 // If the operands are constants, see if we can simplify them.
1452 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453 return UpdateValueUsesWith(I, I);
1454 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1456
1457 // Only known if known in both the LHS and RHS.
1458 RHSKnownOne &= LHSKnownOne;
1459 RHSKnownZero &= LHSKnownZero;
1460 break;
1461 case Instruction::Trunc: {
1462 uint32_t truncBf =
1463 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1464 DemandedMask.zext(truncBf);
1465 RHSKnownZero.zext(truncBf);
1466 RHSKnownOne.zext(truncBf);
1467 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468 RHSKnownZero, RHSKnownOne, Depth+1))
1469 return true;
1470 DemandedMask.trunc(BitWidth);
1471 RHSKnownZero.trunc(BitWidth);
1472 RHSKnownOne.trunc(BitWidth);
1473 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1474 "Bits known to be one AND zero?");
1475 break;
1476 }
1477 case Instruction::BitCast:
1478 if (!I->getOperand(0)->getType()->isInteger())
1479 return false;
1480
1481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482 RHSKnownZero, RHSKnownOne, Depth+1))
1483 return true;
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 break;
1487 case Instruction::ZExt: {
1488 // Compute the bits in the result that are not present in the input.
1489 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1490 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1491
1492 DemandedMask.trunc(SrcBitWidth);
1493 RHSKnownZero.trunc(SrcBitWidth);
1494 RHSKnownOne.trunc(SrcBitWidth);
1495 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496 RHSKnownZero, RHSKnownOne, Depth+1))
1497 return true;
1498 DemandedMask.zext(BitWidth);
1499 RHSKnownZero.zext(BitWidth);
1500 RHSKnownOne.zext(BitWidth);
1501 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1502 "Bits known to be one AND zero?");
1503 // The top bits are known to be zero.
1504 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1505 break;
1506 }
1507 case Instruction::SExt: {
1508 // Compute the bits in the result that are not present in the input.
1509 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1510 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1511
1512 APInt InputDemandedBits = DemandedMask &
1513 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1514
1515 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1516 // If any of the sign extended bits are demanded, we know that the sign
1517 // bit is demanded.
1518 if ((NewBits & DemandedMask) != 0)
1519 InputDemandedBits.set(SrcBitWidth-1);
1520
1521 InputDemandedBits.trunc(SrcBitWidth);
1522 RHSKnownZero.trunc(SrcBitWidth);
1523 RHSKnownOne.trunc(SrcBitWidth);
1524 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525 RHSKnownZero, RHSKnownOne, Depth+1))
1526 return true;
1527 InputDemandedBits.zext(BitWidth);
1528 RHSKnownZero.zext(BitWidth);
1529 RHSKnownOne.zext(BitWidth);
1530 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1531 "Bits known to be one AND zero?");
1532
1533 // If the sign bit of the input is known set or clear, then we know the
1534 // top bits of the result.
1535
1536 // If the input sign bit is known zero, or if the NewBits are not demanded
1537 // convert this into a zero extension.
1538 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1539 {
1540 // Convert to ZExt cast
1541 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542 return UpdateValueUsesWith(I, NewCast);
1543 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1544 RHSKnownOne |= NewBits;
1545 }
1546 break;
1547 }
1548 case Instruction::Add: {
1549 // Figure out what the input bits are. If the top bits of the and result
1550 // are not demanded, then the add doesn't demand them from its input
1551 // either.
1552 uint32_t NLZ = DemandedMask.countLeadingZeros();
1553
1554 // If there is a constant on the RHS, there are a variety of xformations
1555 // we can do.
1556 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557 // If null, this should be simplified elsewhere. Some of the xforms here
1558 // won't work if the RHS is zero.
1559 if (RHS->isZero())
1560 break;
1561
1562 // If the top bit of the output is demanded, demand everything from the
1563 // input. Otherwise, we demand all the input bits except NLZ top bits.
1564 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1565
1566 // Find information about known zero/one bits in the input.
1567 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1568 LHSKnownZero, LHSKnownOne, Depth+1))
1569 return true;
1570
1571 // If the RHS of the add has bits set that can't affect the input, reduce
1572 // the constant.
1573 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574 return UpdateValueUsesWith(I, I);
1575
1576 // Avoid excess work.
1577 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1578 break;
1579
1580 // Turn it into OR if input bits are zero.
1581 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1582 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001583 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001584 I->getName());
1585 InsertNewInstBefore(Or, *I);
1586 return UpdateValueUsesWith(I, Or);
1587 }
1588
1589 // We can say something about the output known-zero and known-one bits,
1590 // depending on potential carries from the input constant and the
1591 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1592 // bits set and the RHS constant is 0x01001, then we know we have a known
1593 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1594
1595 // To compute this, we first compute the potential carry bits. These are
1596 // the bits which may be modified. I'm not aware of a better way to do
1597 // this scan.
1598 const APInt& RHSVal = RHS->getValue();
1599 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1600
1601 // Now that we know which bits have carries, compute the known-1/0 sets.
1602
1603 // Bits are known one if they are known zero in one operand and one in the
1604 // other, and there is no input carry.
1605 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1606 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1607
1608 // Bits are known zero if they are known zero in both operands and there
1609 // is no input carry.
1610 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1611 } else {
1612 // If the high-bits of this ADD are not demanded, then it does not demand
1613 // the high bits of its LHS or RHS.
1614 if (DemandedMask[BitWidth-1] == 0) {
1615 // Right fill the mask of bits for this ADD to demand the most
1616 // significant bit and all those below it.
1617 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1618 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619 LHSKnownZero, LHSKnownOne, Depth+1))
1620 return true;
1621 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622 LHSKnownZero, LHSKnownOne, Depth+1))
1623 return true;
1624 }
1625 }
1626 break;
1627 }
1628 case Instruction::Sub:
1629 // If the high-bits of this SUB are not demanded, then it does not demand
1630 // the high bits of its LHS or RHS.
1631 if (DemandedMask[BitWidth-1] == 0) {
1632 // Right fill the mask of bits for this SUB to demand the most
1633 // significant bit and all those below it.
1634 uint32_t NLZ = DemandedMask.countLeadingZeros();
1635 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1636 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637 LHSKnownZero, LHSKnownOne, Depth+1))
1638 return true;
1639 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1641 return true;
1642 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001643 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644 // the known zeros and ones.
1645 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646 break;
1647 case Instruction::Shl:
1648 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1650 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1652 RHSKnownZero, RHSKnownOne, Depth+1))
1653 return true;
1654 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1655 "Bits known to be one AND zero?");
1656 RHSKnownZero <<= ShiftAmt;
1657 RHSKnownOne <<= ShiftAmt;
1658 // low bits known zero.
1659 if (ShiftAmt)
1660 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1661 }
1662 break;
1663 case Instruction::LShr:
1664 // For a logical shift right
1665 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1666 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1667
1668 // Unsigned shift right.
1669 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1671 RHSKnownZero, RHSKnownOne, Depth+1))
1672 return true;
1673 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1674 "Bits known to be one AND zero?");
1675 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1677 if (ShiftAmt) {
1678 // Compute the new bits that are at the top now.
1679 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1680 RHSKnownZero |= HighBits; // high bits known zero.
1681 }
1682 }
1683 break;
1684 case Instruction::AShr:
1685 // If this is an arithmetic shift right and only the low-bit is set, we can
1686 // always convert this into a logical shr, even if the shift amount is
1687 // variable. The low bit of the shift cannot be an input sign bit unless
1688 // the shift amount is >= the size of the datatype, which is undefined.
1689 if (DemandedMask == 1) {
1690 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001691 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001692 I->getOperand(0), I->getOperand(1), I->getName());
1693 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694 return UpdateValueUsesWith(I, NewVal);
1695 }
1696
1697 // If the sign bit is the only bit demanded by this ashr, then there is no
1698 // need to do it, the shift doesn't change the high bit.
1699 if (DemandedMask.isSignBit())
1700 return UpdateValueUsesWith(I, I->getOperand(0));
1701
1702 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1703 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1704
1705 // Signed shift right.
1706 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1707 // If any of the "high bits" are demanded, we should set the sign bit as
1708 // demanded.
1709 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710 DemandedMaskIn.set(BitWidth-1);
1711 if (SimplifyDemandedBits(I->getOperand(0),
1712 DemandedMaskIn,
1713 RHSKnownZero, RHSKnownOne, Depth+1))
1714 return true;
1715 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1716 "Bits known to be one AND zero?");
1717 // Compute the new bits that are at the top now.
1718 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1719 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1721
1722 // Handle the sign bits.
1723 APInt SignBit(APInt::getSignBit(BitWidth));
1724 // Adjust to where it is now in the mask.
1725 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1726
1727 // If the input sign bit is known to be zero, or if none of the top bits
1728 // are demanded, turn this into an unsigned shift right.
1729 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1730 (HighBits & ~DemandedMask) == HighBits) {
1731 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001732 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 I->getOperand(0), SA, I->getName());
1734 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735 return UpdateValueUsesWith(I, NewVal);
1736 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737 RHSKnownOne |= HighBits;
1738 }
1739 }
1740 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001741 case Instruction::SRem:
1742 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743 APInt RA = Rem->getValue();
1744 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001745 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001746 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748 LHSKnownZero, LHSKnownOne, Depth+1))
1749 return true;
1750
1751 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752 LHSKnownZero |= ~LowBits;
1753 else if (LHSKnownOne[BitWidth-1])
1754 LHSKnownOne |= ~LowBits;
1755
1756 KnownZero |= LHSKnownZero & DemandedMask;
1757 KnownOne |= LHSKnownOne & DemandedMask;
1758
1759 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1760 }
1761 }
1762 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001763 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001764 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001766 if (RA.isPowerOf2()) {
1767 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001768 APInt Mask2 = LowBits & DemandedMask;
1769 KnownZero |= ~LowBits & DemandedMask;
1770 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771 KnownZero, KnownOne, Depth+1))
1772 return true;
1773
1774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001775 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001776 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001777 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001778
1779 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001781 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782 KnownZero2, KnownOne2, Depth+1))
1783 return true;
1784
Dan Gohmanbec16052008-04-28 17:02:21 +00001785 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001786 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001787 KnownZero2, KnownOne2, Depth+1))
1788 return true;
1789
1790 Leaders = std::max(Leaders,
1791 KnownZero2.countLeadingOnes());
1792 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001793 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001795 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796
1797 // If the client is only demanding bits that we know, return the known
1798 // constant.
1799 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1801 return false;
1802}
1803
1804
1805/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806/// 64 or fewer elements. DemandedElts contains the set of elements that are
1807/// actually used by the caller. This method analyzes which elements of the
1808/// operand are undef and returns that information in UndefElts.
1809///
1810/// If the information about demanded elements can be used to simplify the
1811/// operation, the operation is simplified, then the resultant value is
1812/// returned. This returns null if no change was made.
1813Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814 uint64_t &UndefElts,
1815 unsigned Depth) {
1816 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1817 assert(VWidth <= 64 && "Vector too wide to analyze!");
1818 uint64_t EltMask = ~0ULL >> (64-VWidth);
1819 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820 "Invalid DemandedElts!");
1821
1822 if (isa<UndefValue>(V)) {
1823 // If the entire vector is undefined, just return this info.
1824 UndefElts = EltMask;
1825 return 0;
1826 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827 UndefElts = EltMask;
1828 return UndefValue::get(V->getType());
1829 }
1830
1831 UndefElts = 0;
1832 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1834 Constant *Undef = UndefValue::get(EltTy);
1835
1836 std::vector<Constant*> Elts;
1837 for (unsigned i = 0; i != VWidth; ++i)
1838 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1839 Elts.push_back(Undef);
1840 UndefElts |= (1ULL << i);
1841 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1842 Elts.push_back(Undef);
1843 UndefElts |= (1ULL << i);
1844 } else { // Otherwise, defined.
1845 Elts.push_back(CP->getOperand(i));
1846 }
1847
1848 // If we changed the constant, return it.
1849 Constant *NewCP = ConstantVector::get(Elts);
1850 return NewCP != CP ? NewCP : 0;
1851 } else if (isa<ConstantAggregateZero>(V)) {
1852 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1853 // set to undef.
1854 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1855 Constant *Zero = Constant::getNullValue(EltTy);
1856 Constant *Undef = UndefValue::get(EltTy);
1857 std::vector<Constant*> Elts;
1858 for (unsigned i = 0; i != VWidth; ++i)
1859 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860 UndefElts = DemandedElts ^ EltMask;
1861 return ConstantVector::get(Elts);
1862 }
1863
1864 if (!V->hasOneUse()) { // Other users may use these bits.
1865 if (Depth != 0) { // Not at the root.
1866 // TODO: Just compute the UndefElts information recursively.
1867 return false;
1868 }
1869 return false;
1870 } else if (Depth == 10) { // Limit search depth.
1871 return false;
1872 }
1873
1874 Instruction *I = dyn_cast<Instruction>(V);
1875 if (!I) return false; // Only analyze instructions.
1876
1877 bool MadeChange = false;
1878 uint64_t UndefElts2;
1879 Value *TmpV;
1880 switch (I->getOpcode()) {
1881 default: break;
1882
1883 case Instruction::InsertElement: {
1884 // If this is a variable index, we don't know which element it overwrites.
1885 // demand exactly the same input as we produce.
1886 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1887 if (Idx == 0) {
1888 // Note that we can't propagate undef elt info, because we don't know
1889 // which elt is getting updated.
1890 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891 UndefElts2, Depth+1);
1892 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1893 break;
1894 }
1895
1896 // If this is inserting an element that isn't demanded, remove this
1897 // insertelement.
1898 unsigned IdxNo = Idx->getZExtValue();
1899 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900 return AddSoonDeadInstToWorklist(*I, 0);
1901
1902 // Otherwise, the element inserted overwrites whatever was there, so the
1903 // input demanded set is simpler than the output set.
1904 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905 DemandedElts & ~(1ULL << IdxNo),
1906 UndefElts, Depth+1);
1907 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1908
1909 // The inserted element is defined.
1910 UndefElts |= 1ULL << IdxNo;
1911 break;
1912 }
1913 case Instruction::BitCast: {
1914 // Vector->vector casts only.
1915 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1916 if (!VTy) break;
1917 unsigned InVWidth = VTy->getNumElements();
1918 uint64_t InputDemandedElts = 0;
1919 unsigned Ratio;
1920
1921 if (VWidth == InVWidth) {
1922 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1923 // elements as are demanded of us.
1924 Ratio = 1;
1925 InputDemandedElts = DemandedElts;
1926 } else if (VWidth > InVWidth) {
1927 // Untested so far.
1928 break;
1929
1930 // If there are more elements in the result than there are in the source,
1931 // then an input element is live if any of the corresponding output
1932 // elements are live.
1933 Ratio = VWidth/InVWidth;
1934 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935 if (DemandedElts & (1ULL << OutIdx))
1936 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1937 }
1938 } else {
1939 // Untested so far.
1940 break;
1941
1942 // If there are more elements in the source than there are in the result,
1943 // then an input element is live if the corresponding output element is
1944 // live.
1945 Ratio = InVWidth/VWidth;
1946 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947 if (DemandedElts & (1ULL << InIdx/Ratio))
1948 InputDemandedElts |= 1ULL << InIdx;
1949 }
1950
1951 // div/rem demand all inputs, because they don't want divide by zero.
1952 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953 UndefElts2, Depth+1);
1954 if (TmpV) {
1955 I->setOperand(0, TmpV);
1956 MadeChange = true;
1957 }
1958
1959 UndefElts = UndefElts2;
1960 if (VWidth > InVWidth) {
1961 assert(0 && "Unimp");
1962 // If there are more elements in the result than there are in the source,
1963 // then an output element is undef if the corresponding input element is
1964 // undef.
1965 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967 UndefElts |= 1ULL << OutIdx;
1968 } else if (VWidth < InVWidth) {
1969 assert(0 && "Unimp");
1970 // If there are more elements in the source than there are in the result,
1971 // then a result element is undef if all of the corresponding input
1972 // elements are undef.
1973 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1974 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1976 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1977 }
1978 break;
1979 }
1980 case Instruction::And:
1981 case Instruction::Or:
1982 case Instruction::Xor:
1983 case Instruction::Add:
1984 case Instruction::Sub:
1985 case Instruction::Mul:
1986 // div/rem demand all inputs, because they don't want divide by zero.
1987 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988 UndefElts, Depth+1);
1989 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991 UndefElts2, Depth+1);
1992 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1993
1994 // Output elements are undefined if both are undefined. Consider things
1995 // like undef&0. The result is known zero, not undef.
1996 UndefElts &= UndefElts2;
1997 break;
1998
1999 case Instruction::Call: {
2000 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2001 if (!II) break;
2002 switch (II->getIntrinsicID()) {
2003 default: break;
2004
2005 // Binary vector operations that work column-wise. A dest element is a
2006 // function of the corresponding input elements from the two inputs.
2007 case Intrinsic::x86_sse_sub_ss:
2008 case Intrinsic::x86_sse_mul_ss:
2009 case Intrinsic::x86_sse_min_ss:
2010 case Intrinsic::x86_sse_max_ss:
2011 case Intrinsic::x86_sse2_sub_sd:
2012 case Intrinsic::x86_sse2_mul_sd:
2013 case Intrinsic::x86_sse2_min_sd:
2014 case Intrinsic::x86_sse2_max_sd:
2015 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016 UndefElts, Depth+1);
2017 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019 UndefElts2, Depth+1);
2020 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2021
2022 // If only the low elt is demanded and this is a scalarizable intrinsic,
2023 // scalarize it now.
2024 if (DemandedElts == 1) {
2025 switch (II->getIntrinsicID()) {
2026 default: break;
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse_mul_ss:
2029 case Intrinsic::x86_sse2_sub_sd:
2030 case Intrinsic::x86_sse2_mul_sd:
2031 // TODO: Lower MIN/MAX/ABS/etc
2032 Value *LHS = II->getOperand(1);
2033 Value *RHS = II->getOperand(2);
2034 // Extract the element as scalars.
2035 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2037
2038 switch (II->getIntrinsicID()) {
2039 default: assert(0 && "Case stmts out of sync!");
2040 case Intrinsic::x86_sse_sub_ss:
2041 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002042 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043 II->getName()), *II);
2044 break;
2045 case Intrinsic::x86_sse_mul_ss:
2046 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002047 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 II->getName()), *II);
2049 break;
2050 }
2051
2052 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00002053 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2054 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002055 InsertNewInstBefore(New, *II);
2056 AddSoonDeadInstToWorklist(*II, 0);
2057 return New;
2058 }
2059 }
2060
2061 // Output elements are undefined if both are undefined. Consider things
2062 // like undef&0. The result is known zero, not undef.
2063 UndefElts &= UndefElts2;
2064 break;
2065 }
2066 break;
2067 }
2068 }
2069 return MadeChange ? I : 0;
2070}
2071
Dan Gohman5d56fd42008-05-19 22:14:15 +00002072/// ComputeNumSignBits - Return the number of times the sign bit of the
2073/// register is replicated into the other bits. We know that at least 1 bit
2074/// is always equal to the sign bit (itself), but other cases can give us
2075/// information. For example, immediately after an "ashr X, 2", we know that
2076/// the top 3 bits are all equal to each other, so we return 3.
2077///
2078unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079 const IntegerType *Ty = cast<IntegerType>(V->getType());
2080 unsigned TyBits = Ty->getBitWidth();
2081 unsigned Tmp, Tmp2;
Dan Gohman4afc4252008-05-23 02:28:01 +00002082 unsigned FirstAnswer = 1;
Dan Gohman5d56fd42008-05-19 22:14:15 +00002083
2084 if (Depth == 6)
2085 return 1; // Limit search depth.
2086
2087 User *U = dyn_cast<User>(V);
2088 switch (getOpcode(V)) {
2089 default: break;
2090 case Instruction::SExt:
2091 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2093
2094 case Instruction::AShr:
2095 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf0f12022008-05-20 21:01:12 +00002096 // ashr X, C -> adds C sign bits.
Dan Gohman5d56fd42008-05-19 22:14:15 +00002097 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098 Tmp += C->getZExtValue();
2099 if (Tmp > TyBits) Tmp = TyBits;
2100 }
2101 return Tmp;
2102 case Instruction::Shl:
2103 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104 // shl destroys sign bits.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106 if (C->getZExtValue() >= TyBits || // Bad shift.
2107 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2108 return Tmp - C->getZExtValue();
2109 }
2110 break;
2111 case Instruction::And:
2112 case Instruction::Or:
Dan Gohman4afc4252008-05-23 02:28:01 +00002113 case Instruction::Xor: // NOT is handled here.
Chris Lattner3554f972008-05-20 05:46:13 +00002114 // Logical binary ops preserve the number of sign bits at the worst.
2115 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2116 if (Tmp != 1) {
2117 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman4afc4252008-05-23 02:28:01 +00002118 FirstAnswer = std::min(Tmp, Tmp2);
2119 // We computed what we know about the sign bits as our first
2120 // answer. Now proceed to the generic code that uses
2121 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3554f972008-05-20 05:46:13 +00002122 }
Dan Gohman4afc4252008-05-23 02:28:01 +00002123 break;
Dan Gohman5d56fd42008-05-19 22:14:15 +00002124
2125 case Instruction::Select:
Chris Lattner3554f972008-05-20 05:46:13 +00002126 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman5d56fd42008-05-19 22:14:15 +00002127 if (Tmp == 1) return 1; // Early out.
Chris Lattner3554f972008-05-20 05:46:13 +00002128 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman5d56fd42008-05-19 22:14:15 +00002129 return std::min(Tmp, Tmp2);
2130
2131 case Instruction::Add:
2132 // Add can have at most one carry bit. Thus we know that the output
2133 // is, at worst, one more bit than the inputs.
2134 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135 if (Tmp == 1) return 1; // Early out.
2136
2137 // Special case decrementing a value (ADD X, -1):
2138 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139 if (CRHS->isAllOnesValue()) {
2140 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141 APInt Mask = APInt::getAllOnesValue(TyBits);
2142 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2143
2144 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2145 // sign bits set.
2146 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2147 return TyBits;
2148
2149 // If we are subtracting one from a positive number, there is no carry
2150 // out of the result.
2151 if (KnownZero.isNegative())
2152 return Tmp;
2153 }
2154
2155 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156 if (Tmp2 == 1) return 1;
2157 return std::min(Tmp, Tmp2)-1;
2158 break;
2159
2160 case Instruction::Sub:
2161 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162 if (Tmp2 == 1) return 1;
2163
2164 // Handle NEG.
2165 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166 if (CLHS->isNullValue()) {
2167 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168 APInt Mask = APInt::getAllOnesValue(TyBits);
2169 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2171 // sign bits set.
2172 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2173 return TyBits;
2174
2175 // If the input is known to be positive (the sign bit is known clear),
2176 // the output of the NEG has the same number of sign bits as the input.
2177 if (KnownZero.isNegative())
2178 return Tmp2;
2179
2180 // Otherwise, we treat this like a SUB.
2181 }
2182
2183 // Sub can have at most one carry bit. Thus we know that the output
2184 // is, at worst, one more bit than the inputs.
2185 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186 if (Tmp == 1) return 1; // Early out.
2187 return std::min(Tmp, Tmp2)-1;
2188 break;
2189 case Instruction::Trunc:
2190 // FIXME: it's tricky to do anything useful for this, but it is an important
2191 // case for targets like X86.
2192 break;
2193 }
2194
2195 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196 // use this information.
2197 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198 APInt Mask = APInt::getAllOnesValue(TyBits);
2199 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2200
2201 if (KnownZero.isNegative()) { // sign bit is 0
2202 Mask = KnownZero;
2203 } else if (KnownOne.isNegative()) { // sign bit is 1;
2204 Mask = KnownOne;
2205 } else {
2206 // Nothing known.
Dan Gohman4afc4252008-05-23 02:28:01 +00002207 return FirstAnswer;
Dan Gohman5d56fd42008-05-19 22:14:15 +00002208 }
2209
2210 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2211 // the number of identical bits in the top of the input value.
2212 Mask = ~Mask;
2213 Mask <<= Mask.getBitWidth()-TyBits;
2214 // Return # leading zeros. We use 'min' here in case Val was zero before
2215 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohman4afc4252008-05-23 02:28:01 +00002216 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman5d56fd42008-05-19 22:14:15 +00002217}
2218
2219
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002220/// AssociativeOpt - Perform an optimization on an associative operator. This
2221/// function is designed to check a chain of associative operators for a
2222/// potential to apply a certain optimization. Since the optimization may be
2223/// applicable if the expression was reassociated, this checks the chain, then
2224/// reassociates the expression as necessary to expose the optimization
2225/// opportunity. This makes use of a special Functor, which must define
2226/// 'shouldApply' and 'apply' methods.
2227///
2228template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00002229static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002230 unsigned Opcode = Root.getOpcode();
2231 Value *LHS = Root.getOperand(0);
2232
2233 // Quick check, see if the immediate LHS matches...
2234 if (F.shouldApply(LHS))
2235 return F.apply(Root);
2236
2237 // Otherwise, if the LHS is not of the same opcode as the root, return.
2238 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2239 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2240 // Should we apply this transform to the RHS?
2241 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2242
2243 // If not to the RHS, check to see if we should apply to the LHS...
2244 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2246 ShouldApply = true;
2247 }
2248
2249 // If the functor wants to apply the optimization to the RHS of LHSI,
2250 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2251 if (ShouldApply) {
2252 BasicBlock *BB = Root.getParent();
2253
2254 // Now all of the instructions are in the current basic block, go ahead
2255 // and perform the reassociation.
2256 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2257
2258 // First move the selected RHS to the LHS of the root...
2259 Root.setOperand(0, LHSI->getOperand(1));
2260
2261 // Make what used to be the LHS of the root be the user of the root...
2262 Value *ExtraOperand = TmpLHSI->getOperand(1);
2263 if (&Root == TmpLHSI) {
2264 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2265 return 0;
2266 }
2267 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2268 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2269 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270 BasicBlock::iterator ARI = &Root; ++ARI;
2271 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2272 ARI = Root;
2273
2274 // Now propagate the ExtraOperand down the chain of instructions until we
2275 // get to LHSI.
2276 while (TmpLHSI != LHSI) {
2277 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2278 // Move the instruction to immediately before the chain we are
2279 // constructing to avoid breaking dominance properties.
2280 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281 BB->getInstList().insert(ARI, NextLHSI);
2282 ARI = NextLHSI;
2283
2284 Value *NextOp = NextLHSI->getOperand(1);
2285 NextLHSI->setOperand(1, ExtraOperand);
2286 TmpLHSI = NextLHSI;
2287 ExtraOperand = NextOp;
2288 }
2289
2290 // Now that the instructions are reassociated, have the functor perform
2291 // the transformation...
2292 return F.apply(Root);
2293 }
2294
2295 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2296 }
2297 return 0;
2298}
2299
Dan Gohman089efff2008-05-13 00:00:25 +00002300namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002301
Nick Lewycky27f6c132008-05-23 04:34:58 +00002302// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303struct AddRHS {
2304 Value *RHS;
2305 AddRHS(Value *rhs) : RHS(rhs) {}
2306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00002308 return BinaryOperator::CreateShl(Add.getOperand(0),
2309 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002310 }
2311};
2312
2313// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2314// iff C1&C2 == 0
2315struct AddMaskingAnd {
2316 Constant *C2;
2317 AddMaskingAnd(Constant *c) : C2(c) {}
2318 bool shouldApply(Value *LHS) const {
2319 ConstantInt *C1;
2320 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2321 ConstantExpr::getAnd(C1, C2)->isNullValue();
2322 }
2323 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002324 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002325 }
2326};
2327
Dan Gohman089efff2008-05-13 00:00:25 +00002328}
2329
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2331 InstCombiner *IC) {
2332 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2333 if (Constant *SOC = dyn_cast<Constant>(SO))
2334 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2335
Gabor Greifa645dd32008-05-16 19:29:10 +00002336 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002337 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2338 }
2339
2340 // Figure out if the constant is the left or the right argument.
2341 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2343
2344 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2345 if (ConstIsRHS)
2346 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2348 }
2349
2350 Value *Op0 = SO, *Op1 = ConstOperand;
2351 if (!ConstIsRHS)
2352 std::swap(Op0, Op1);
2353 Instruction *New;
2354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002355 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002356 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002357 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358 SO->getName()+".cmp");
2359 else {
2360 assert(0 && "Unknown binary instruction type!");
2361 abort();
2362 }
2363 return IC->InsertNewInstBefore(New, I);
2364}
2365
2366// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367// constant as the other operand, try to fold the binary operator into the
2368// select arguments. This also works for Cast instructions, which obviously do
2369// not have a second operand.
2370static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2371 InstCombiner *IC) {
2372 // Don't modify shared select instructions
2373 if (!SI->hasOneUse()) return 0;
2374 Value *TV = SI->getOperand(1);
2375 Value *FV = SI->getOperand(2);
2376
2377 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2378 // Bool selects with constant operands can be folded to logical ops.
2379 if (SI->getType() == Type::Int1Ty) return 0;
2380
2381 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2383
Gabor Greifd6da1d02008-04-06 20:25:17 +00002384 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2385 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386 }
2387 return 0;
2388}
2389
2390
2391/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392/// node as operand #0, see if we can fold the instruction into the PHI (which
2393/// is only possible if all operands to the PHI are constants).
2394Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395 PHINode *PN = cast<PHINode>(I.getOperand(0));
2396 unsigned NumPHIValues = PN->getNumIncomingValues();
2397 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2398
2399 // Check to see if all of the operands of the PHI are constants. If there is
2400 // one non-constant value, remember the BB it is. If there is more than one
2401 // or if *it* is a PHI, bail out.
2402 BasicBlock *NonConstBB = 0;
2403 for (unsigned i = 0; i != NumPHIValues; ++i)
2404 if (!isa<Constant>(PN->getIncomingValue(i))) {
2405 if (NonConstBB) return 0; // More than one non-const value.
2406 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2407 NonConstBB = PN->getIncomingBlock(i);
2408
2409 // If the incoming non-constant value is in I's block, we have an infinite
2410 // loop.
2411 if (NonConstBB == I.getParent())
2412 return 0;
2413 }
2414
2415 // If there is exactly one non-constant value, we can insert a copy of the
2416 // operation in that block. However, if this is a critical edge, we would be
2417 // inserting the computation one some other paths (e.g. inside a loop). Only
2418 // do this if the pred block is unconditionally branching into the phi block.
2419 if (NonConstBB) {
2420 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421 if (!BI || !BI->isUnconditional()) return 0;
2422 }
2423
2424 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002425 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2427 InsertNewInstBefore(NewPN, *PN);
2428 NewPN->takeName(PN);
2429
2430 // Next, add all of the operands to the PHI.
2431 if (I.getNumOperands() == 2) {
2432 Constant *C = cast<Constant>(I.getOperand(1));
2433 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002434 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002435 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2436 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2438 else
2439 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2440 } else {
2441 assert(PN->getIncomingBlock(i) == NonConstBB);
2442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002443 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444 PN->getIncomingValue(i), C, "phitmp",
2445 NonConstBB->getTerminator());
2446 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002447 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448 CI->getPredicate(),
2449 PN->getIncomingValue(i), C, "phitmp",
2450 NonConstBB->getTerminator());
2451 else
2452 assert(0 && "Unknown binop!");
2453
2454 AddToWorkList(cast<Instruction>(InV));
2455 }
2456 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2457 }
2458 } else {
2459 CastInst *CI = cast<CastInst>(&I);
2460 const Type *RetTy = CI->getType();
2461 for (unsigned i = 0; i != NumPHIValues; ++i) {
2462 Value *InV;
2463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2464 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2465 } else {
2466 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002467 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002468 I.getType(), "phitmp",
2469 NonConstBB->getTerminator());
2470 AddToWorkList(cast<Instruction>(InV));
2471 }
2472 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2473 }
2474 }
2475 return ReplaceInstUsesWith(I, NewPN);
2476}
2477
Chris Lattner55476162008-01-29 06:52:45 +00002478
2479/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2480/// value is never equal to -0.0.
2481///
2482/// Note that this function will need to be revisited when we support nondefault
2483/// rounding modes!
2484///
2485static bool CannotBeNegativeZero(const Value *V) {
2486 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487 return !CFP->getValueAPF().isNegZero();
2488
Chris Lattner55476162008-01-29 06:52:45 +00002489 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnere3061db2008-05-19 20:27:56 +00002490 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner55476162008-01-29 06:52:45 +00002491 if (I->getOpcode() == Instruction::Add &&
2492 isa<ConstantFP>(I->getOperand(1)) &&
2493 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2494 return true;
2495
Chris Lattnere3061db2008-05-19 20:27:56 +00002496 // sitofp and uitofp turn into +0.0 for zero.
2497 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2498 return true;
2499
Chris Lattner55476162008-01-29 06:52:45 +00002500 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501 if (II->getIntrinsicID() == Intrinsic::sqrt)
2502 return CannotBeNegativeZero(II->getOperand(1));
2503
2504 if (const CallInst *CI = dyn_cast<CallInst>(I))
2505 if (const Function *F = CI->getCalledFunction()) {
2506 if (F->isDeclaration()) {
2507 switch (F->getNameLen()) {
2508 case 3: // abs(x) != -0.0
2509 if (!strcmp(F->getNameStart(), "abs")) return true;
2510 break;
2511 case 4: // abs[lf](x) != -0.0
2512 if (!strcmp(F->getNameStart(), "absf")) return true;
2513 if (!strcmp(F->getNameStart(), "absl")) return true;
2514 break;
2515 }
2516 }
2517 }
2518 }
2519
2520 return false;
2521}
2522
Chris Lattner3554f972008-05-20 05:46:13 +00002523/// WillNotOverflowSignedAdd - Return true if we can prove that:
2524/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2525/// This basically requires proving that the add in the original type would not
2526/// overflow to change the sign bit or have a carry out.
2527bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528 // There are different heuristics we can use for this. Here are some simple
2529 // ones.
2530
2531 // Add has the property that adding any two 2's complement numbers can only
2532 // have one carry bit which can change a sign. As such, if LHS and RHS each
2533 // have at least two sign bits, we know that the addition of the two values will
2534 // sign extend fine.
2535 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2536 return true;
2537
2538
2539 // If one of the operands only has one non-zero bit, and if the other operand
2540 // has a known-zero bit in a more significant place than it (not including the
2541 // sign bit) the ripple may go up to and fill the zero, but won't change the
2542 // sign. For example, (X & ~4) + 1.
2543
2544 // TODO: Implement.
2545
2546 return false;
2547}
2548
Chris Lattner55476162008-01-29 06:52:45 +00002549
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2551 bool Changed = SimplifyCommutative(I);
2552 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2553
2554 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2555 // X + undef -> undef
2556 if (isa<UndefValue>(RHS))
2557 return ReplaceInstUsesWith(I, RHS);
2558
2559 // X + 0 --> X
2560 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2561 if (RHSC->isNullValue())
2562 return ReplaceInstUsesWith(I, LHS);
2563 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002564 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2565 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566 return ReplaceInstUsesWith(I, LHS);
2567 }
2568
2569 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2570 // X + (signbit) --> X ^ signbit
2571 const APInt& Val = CI->getValue();
2572 uint32_t BitWidth = Val.getBitWidth();
2573 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002575
2576 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2577 // (X & 254)+1 -> (X&254)|1
2578 if (!isa<VectorType>(I.getType())) {
2579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2580 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2581 KnownZero, KnownOne))
2582 return &I;
2583 }
2584 }
2585
2586 if (isa<PHINode>(LHS))
2587 if (Instruction *NV = FoldOpIntoPhi(I))
2588 return NV;
2589
2590 ConstantInt *XorRHS = 0;
2591 Value *XorLHS = 0;
2592 if (isa<ConstantInt>(RHSC) &&
2593 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2594 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2595 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2596
2597 uint32_t Size = TySizeBits / 2;
2598 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2599 APInt CFF80Val(-C0080Val);
2600 do {
2601 if (TySizeBits > Size) {
2602 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2604 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2605 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2606 // This is a sign extend if the top bits are known zero.
2607 if (!MaskedValueIsZero(XorLHS,
2608 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2609 Size = 0; // Not a sign ext, but can't be any others either.
2610 break;
2611 }
2612 }
2613 Size >>= 1;
2614 C0080Val = APIntOps::lshr(C0080Val, Size);
2615 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2616 } while (Size >= 1);
2617
2618 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002619 // with funny bit widths then this switch statement should be removed. It
2620 // is just here to get the size of the "middle" type back up to something
2621 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002622 const Type *MiddleType = 0;
2623 switch (Size) {
2624 default: break;
2625 case 32: MiddleType = Type::Int32Ty; break;
2626 case 16: MiddleType = Type::Int16Ty; break;
2627 case 8: MiddleType = Type::Int8Ty; break;
2628 }
2629 if (MiddleType) {
2630 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2631 InsertNewInstBefore(NewTrunc, I);
2632 return new SExtInst(NewTrunc, I.getType(), I.getName());
2633 }
2634 }
2635 }
2636
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002637 if (I.getType() == Type::Int1Ty)
2638 return BinaryOperator::CreateXor(LHS, RHS);
2639
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002640 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002641 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002642 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2643
2644 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2645 if (RHSI->getOpcode() == Instruction::Sub)
2646 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2647 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2648 }
2649 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2650 if (LHSI->getOpcode() == Instruction::Sub)
2651 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2652 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2653 }
2654 }
2655
2656 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002657 // -A + -B --> -(A + B)
2658 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002659 if (LHS->getType()->isIntOrIntVector()) {
2660 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002661 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002662 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002663 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002664 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002665 }
2666
Gabor Greifa645dd32008-05-16 19:29:10 +00002667 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002668 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
2670 // A + -B --> A - B
2671 if (!isa<Constant>(RHS))
2672 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002673 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674
2675
2676 ConstantInt *C2;
2677 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2678 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002679 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680
2681 // X*C1 + X*C2 --> X * (C1+C2)
2682 ConstantInt *C1;
2683 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002685 }
2686
2687 // X + X*C --> X * (C+1)
2688 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002689 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002690
2691 // X + ~X --> -1 since ~X = -X-1
2692 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2693 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2694
2695
2696 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2697 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2698 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2699 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002700
2701 // A+B --> A|B iff A and B have no bits set in common.
2702 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2703 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2704 APInt LHSKnownOne(IT->getBitWidth(), 0);
2705 APInt LHSKnownZero(IT->getBitWidth(), 0);
2706 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2707 if (LHSKnownZero != 0) {
2708 APInt RHSKnownOne(IT->getBitWidth(), 0);
2709 APInt RHSKnownZero(IT->getBitWidth(), 0);
2710 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2711
2712 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002713 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002714 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002715 }
2716 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717
Nick Lewycky83598a72008-02-03 07:42:09 +00002718 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002719 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002720 Value *W, *X, *Y, *Z;
2721 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2722 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2723 if (W != Y) {
2724 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002725 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002726 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002727 std::swap(W, X);
2728 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002729 std::swap(Y, Z);
2730 std::swap(W, X);
2731 }
2732 }
2733
2734 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002735 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002736 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002737 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002738 }
2739 }
2740 }
2741
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002742 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2743 Value *X = 0;
2744 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002745 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002746
2747 // (X & FF00) + xx00 -> (X+xx00) & FF00
2748 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2749 Constant *Anded = And(CRHS, C2);
2750 if (Anded == CRHS) {
2751 // See if all bits from the first bit set in the Add RHS up are included
2752 // in the mask. First, get the rightmost bit.
2753 const APInt& AddRHSV = CRHS->getValue();
2754
2755 // Form a mask of all bits from the lowest bit added through the top.
2756 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2757
2758 // See if the and mask includes all of these bits.
2759 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2760
2761 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2762 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002763 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002764 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002765 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002766 }
2767 }
2768 }
2769
2770 // Try to fold constant add into select arguments.
2771 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2772 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2773 return R;
2774 }
2775
2776 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002777 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778 {
2779 CastInst *CI = dyn_cast<CastInst>(LHS);
2780 Value *Other = RHS;
2781 if (!CI) {
2782 CI = dyn_cast<CastInst>(RHS);
2783 Other = LHS;
2784 }
2785 if (CI && CI->getType()->isSized() &&
2786 (CI->getType()->getPrimitiveSizeInBits() ==
2787 TD->getIntPtrType()->getPrimitiveSizeInBits())
2788 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002789 unsigned AS =
2790 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002791 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2792 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002793 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002794 return new PtrToIntInst(I2, CI->getType());
2795 }
2796 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002797
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002798 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002799 {
2800 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2801 Value *Other = RHS;
2802 if (!SI) {
2803 SI = dyn_cast<SelectInst>(RHS);
2804 Other = LHS;
2805 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002806 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002807 Value *TV = SI->getTrueValue();
2808 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002809 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002810
2811 // Can we fold the add into the argument of the select?
2812 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002813 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2814 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002815 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002816 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2817 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002818 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002819 }
2820 }
Chris Lattner55476162008-01-29 06:52:45 +00002821
2822 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2823 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2824 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2825 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002826
Chris Lattner3554f972008-05-20 05:46:13 +00002827 // Check for (add (sext x), y), see if we can merge this into an
2828 // integer add followed by a sext.
2829 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2830 // (add (sext x), cst) --> (sext (add x, cst'))
2831 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2832 Constant *CI =
2833 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2834 if (LHSConv->hasOneUse() &&
2835 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2836 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2837 // Insert the new, smaller add.
2838 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2839 CI, "addconv");
2840 InsertNewInstBefore(NewAdd, I);
2841 return new SExtInst(NewAdd, I.getType());
2842 }
2843 }
2844
2845 // (add (sext x), (sext y)) --> (sext (add int x, y))
2846 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2847 // Only do this if x/y have the same type, if at last one of them has a
2848 // single use (so we don't increase the number of sexts), and if the
2849 // integer add will not overflow.
2850 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2851 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2852 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2853 RHSConv->getOperand(0))) {
2854 // Insert the new integer add.
2855 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2856 RHSConv->getOperand(0),
2857 "addconv");
2858 InsertNewInstBefore(NewAdd, I);
2859 return new SExtInst(NewAdd, I.getType());
2860 }
2861 }
2862 }
2863
2864 // Check for (add double (sitofp x), y), see if we can merge this into an
2865 // integer add followed by a promotion.
2866 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2867 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2868 // ... if the constant fits in the integer value. This is useful for things
2869 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2870 // requires a constant pool load, and generally allows the add to be better
2871 // instcombined.
2872 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2873 Constant *CI =
2874 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2875 if (LHSConv->hasOneUse() &&
2876 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2877 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2878 // Insert the new integer add.
2879 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2880 CI, "addconv");
2881 InsertNewInstBefore(NewAdd, I);
2882 return new SIToFPInst(NewAdd, I.getType());
2883 }
2884 }
2885
2886 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2887 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2888 // Only do this if x/y have the same type, if at last one of them has a
2889 // single use (so we don't increase the number of int->fp conversions),
2890 // and if the integer add will not overflow.
2891 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2892 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2893 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2894 RHSConv->getOperand(0))) {
2895 // Insert the new integer add.
2896 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2897 RHSConv->getOperand(0),
2898 "addconv");
2899 InsertNewInstBefore(NewAdd, I);
2900 return new SIToFPInst(NewAdd, I.getType());
2901 }
2902 }
2903 }
2904
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 return Changed ? &I : 0;
2906}
2907
2908// isSignBit - Return true if the value represented by the constant only has the
2909// highest order bit set.
2910static bool isSignBit(ConstantInt *CI) {
2911 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2912 return CI->getValue() == APInt::getSignBit(NumBits);
2913}
2914
2915Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2916 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2917
2918 if (Op0 == Op1) // sub X, X -> 0
2919 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2920
2921 // If this is a 'B = x-(-A)', change to B = x+A...
2922 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002923 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002924
2925 if (isa<UndefValue>(Op0))
2926 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2927 if (isa<UndefValue>(Op1))
2928 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2929
2930 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2931 // Replace (-1 - A) with (~A)...
2932 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002933 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002934
2935 // C - ~X == X + (1+C)
2936 Value *X = 0;
2937 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002938 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002939
2940 // -(X >>u 31) -> (X >>s 31)
2941 // -(X >>s 31) -> (X >>u 31)
2942 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002943 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944 if (SI->getOpcode() == Instruction::LShr) {
2945 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2946 // Check to see if we are shifting out everything but the sign bit.
2947 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2948 SI->getType()->getPrimitiveSizeInBits()-1) {
2949 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002950 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951 SI->getOperand(0), CU, SI->getName());
2952 }
2953 }
2954 }
2955 else if (SI->getOpcode() == Instruction::AShr) {
2956 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2957 // Check to see if we are shifting out everything but the sign bit.
2958 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2959 SI->getType()->getPrimitiveSizeInBits()-1) {
2960 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002961 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002962 SI->getOperand(0), CU, SI->getName());
2963 }
2964 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002965 }
2966 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967 }
2968
2969 // Try to fold constant sub into select arguments.
2970 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2972 return R;
2973
2974 if (isa<PHINode>(Op0))
2975 if (Instruction *NV = FoldOpIntoPhi(I))
2976 return NV;
2977 }
2978
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002979 if (I.getType() == Type::Int1Ty)
2980 return BinaryOperator::CreateXor(Op0, Op1);
2981
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002982 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2983 if (Op1I->getOpcode() == Instruction::Add &&
2984 !Op0->getType()->isFPOrFPVector()) {
2985 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002986 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002987 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002988 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2990 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2991 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002992 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002993 Op1I->getOperand(0));
2994 }
2995 }
2996
2997 if (Op1I->hasOneUse()) {
2998 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2999 // is not used by anyone else...
3000 //
3001 if (Op1I->getOpcode() == Instruction::Sub &&
3002 !Op1I->getType()->isFPOrFPVector()) {
3003 // Swap the two operands of the subexpr...
3004 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
3005 Op1I->setOperand(0, IIOp1);
3006 Op1I->setOperand(1, IIOp0);
3007
3008 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010 }
3011
3012 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3013 //
3014 if (Op1I->getOpcode() == Instruction::And &&
3015 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3016 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3017
3018 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00003019 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3020 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021 }
3022
3023 // 0 - (X sdiv C) -> (X sdiv -C)
3024 if (Op1I->getOpcode() == Instruction::SDiv)
3025 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3026 if (CSI->isZero())
3027 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00003028 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 ConstantExpr::getNeg(DivRHS));
3030
3031 // X - X*C --> X * (1-C)
3032 ConstantInt *C2 = 0;
3033 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
3034 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003035 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036 }
Dan Gohmanda338742007-09-17 17:31:57 +00003037
3038 // X - ((X / Y) * Y) --> X % Y
3039 if (Op1I->getOpcode() == Instruction::Mul)
3040 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3041 if (Op0 == I->getOperand(0) &&
3042 Op1I->getOperand(1) == I->getOperand(1)) {
3043 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00003044 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00003045 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00003046 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00003047 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003048 }
3049 }
3050
3051 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003052 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003053 if (Op0I->getOpcode() == Instruction::Add) {
3054 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3055 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3056 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3057 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3058 } else if (Op0I->getOpcode() == Instruction::Sub) {
3059 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00003060 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003061 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003062 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003063
3064 ConstantInt *C1;
3065 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
3066 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00003067 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068
3069 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3070 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00003071 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003072 }
3073 return 0;
3074}
3075
3076/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3077/// comparison only checks the sign bit. If it only checks the sign bit, set
3078/// TrueIfSigned if the result of the comparison is true when the input value is
3079/// signed.
3080static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3081 bool &TrueIfSigned) {
3082 switch (pred) {
3083 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3084 TrueIfSigned = true;
3085 return RHS->isZero();
3086 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3087 TrueIfSigned = true;
3088 return RHS->isAllOnesValue();
3089 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3090 TrueIfSigned = false;
3091 return RHS->isAllOnesValue();
3092 case ICmpInst::ICMP_UGT:
3093 // True if LHS u> RHS and RHS == high-bit-mask - 1
3094 TrueIfSigned = true;
3095 return RHS->getValue() ==
3096 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3097 case ICmpInst::ICMP_UGE:
3098 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3099 TrueIfSigned = true;
3100 return RHS->getValue() ==
3101 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
3102 default:
3103 return false;
3104 }
3105}
3106
3107Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3108 bool Changed = SimplifyCommutative(I);
3109 Value *Op0 = I.getOperand(0);
3110
3111 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3112 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3113
3114 // Simplify mul instructions with a constant RHS...
3115 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3116 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3117
3118 // ((X << C1)*C2) == (X * (C2 << C1))
3119 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3120 if (SI->getOpcode() == Instruction::Shl)
3121 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00003122 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003123 ConstantExpr::getShl(CI, ShOp));
3124
3125 if (CI->isZero())
3126 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3127 if (CI->equalsInt(1)) // X * 1 == X
3128 return ReplaceInstUsesWith(I, Op0);
3129 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00003130 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131
3132 const APInt& Val = cast<ConstantInt>(CI)->getValue();
3133 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00003134 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003135 ConstantInt::get(Op0->getType(), Val.logBase2()));
3136 }
3137 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
3138 if (Op1F->isNullValue())
3139 return ReplaceInstUsesWith(I, Op1);
3140
3141 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3142 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00003143 // We need a better interface for long double here.
3144 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3145 if (Op1F->isExactlyValue(1.0))
3146 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 }
3148
3149 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3150 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00003151 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003152 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00003153 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 Op1, "tmp");
3155 InsertNewInstBefore(Add, I);
3156 Value *C1C2 = ConstantExpr::getMul(Op1,
3157 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00003158 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159
3160 }
3161
3162 // Try to fold constant mul into select arguments.
3163 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3164 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3165 return R;
3166
3167 if (isa<PHINode>(Op0))
3168 if (Instruction *NV = FoldOpIntoPhi(I))
3169 return NV;
3170 }
3171
3172 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3173 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00003174 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003176 if (I.getType() == Type::Int1Ty)
3177 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
3178
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179 // If one of the operands of the multiply is a cast from a boolean value, then
3180 // we know the bool is either zero or one, so this is a 'masking' multiply.
3181 // See if we can simplify things based on how the boolean was originally
3182 // formed.
3183 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003184 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003185 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3186 BoolCast = CI;
3187 if (!BoolCast)
3188 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3189 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3190 BoolCast = CI;
3191 if (BoolCast) {
3192 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3193 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3194 const Type *SCOpTy = SCIOp0->getType();
3195 bool TIS = false;
3196
3197 // If the icmp is true iff the sign bit of X is set, then convert this
3198 // multiply into a shift/and combination.
3199 if (isa<ConstantInt>(SCIOp1) &&
3200 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3201 TIS) {
3202 // Shift the X value right to turn it into "all signbits".
3203 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3204 SCOpTy->getPrimitiveSizeInBits()-1);
3205 Value *V =
3206 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003207 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003208 BoolCast->getOperand(0)->getName()+
3209 ".mask"), I);
3210
3211 // If the multiply type is not the same as the source type, sign extend
3212 // or truncate to the multiply type.
3213 if (I.getType() != V->getType()) {
3214 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3215 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
3216 Instruction::CastOps opcode =
3217 (SrcBits == DstBits ? Instruction::BitCast :
3218 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3219 V = InsertCastBefore(opcode, V, I.getType(), I);
3220 }
3221
3222 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00003223 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 }
3225 }
3226 }
3227
3228 return Changed ? &I : 0;
3229}
3230
3231/// This function implements the transforms on div instructions that work
3232/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3233/// used by the visitors to those instructions.
3234/// @brief Transforms common to all three div instructions
3235Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3236 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3237
Chris Lattner653ef3c2008-02-19 06:12:18 +00003238 // undef / X -> 0 for integer.
3239 // undef / X -> undef for FP (the undef could be a snan).
3240 if (isa<UndefValue>(Op0)) {
3241 if (Op0->getType()->isFPOrFPVector())
3242 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003243 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003244 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003245
3246 // X / undef -> undef
3247 if (isa<UndefValue>(Op1))
3248 return ReplaceInstUsesWith(I, Op1);
3249
Chris Lattner5be238b2008-01-28 00:58:18 +00003250 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3251 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003252 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00003253 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3254 // the same basic block, then we replace the select with Y, and the
3255 // condition of the select with false (if the cond value is in the same BB).
3256 // If the select has uses other than the div, this allows them to be
3257 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3258 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 if (ST->isNullValue()) {
3260 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3261 if (CondI && CondI->getParent() == I.getParent())
3262 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3263 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3264 I.setOperand(1, SI->getOperand(2));
3265 else
3266 UpdateValueUsesWith(SI, SI->getOperand(2));
3267 return &I;
3268 }
3269
Chris Lattner5be238b2008-01-28 00:58:18 +00003270 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3271 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003272 if (ST->isNullValue()) {
3273 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3274 if (CondI && CondI->getParent() == I.getParent())
3275 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3276 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3277 I.setOperand(1, SI->getOperand(1));
3278 else
3279 UpdateValueUsesWith(SI, SI->getOperand(1));
3280 return &I;
3281 }
3282 }
3283
3284 return 0;
3285}
3286
3287/// This function implements the transforms common to both integer division
3288/// instructions (udiv and sdiv). It is called by the visitors to those integer
3289/// division instructions.
3290/// @brief Common integer divide transforms
3291Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3292 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3293
Chris Lattnercefb36c2008-05-16 02:59:42 +00003294 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00003295 if (Op0 == Op1) {
3296 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3297 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3298 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3299 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3300 }
3301
3302 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3303 return ReplaceInstUsesWith(I, CI);
3304 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00003305
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 if (Instruction *Common = commonDivTransforms(I))
3307 return Common;
3308
3309 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3310 // div X, 1 == X
3311 if (RHS->equalsInt(1))
3312 return ReplaceInstUsesWith(I, Op0);
3313
3314 // (X / C1) / C2 -> X / (C1*C2)
3315 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3316 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3317 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00003318 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3319 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3320 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003321 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00003322 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003323 }
3324
3325 if (!RHS->isZero()) { // avoid X udiv 0
3326 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3327 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3328 return R;
3329 if (isa<PHINode>(Op0))
3330 if (Instruction *NV = FoldOpIntoPhi(I))
3331 return NV;
3332 }
3333 }
3334
3335 // 0 / X == 0, we don't need to preserve faults!
3336 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3337 if (LHS->equalsInt(0))
3338 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3339
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003340 // It can't be division by zero, hence it must be division by one.
3341 if (I.getType() == Type::Int1Ty)
3342 return ReplaceInstUsesWith(I, Op0);
3343
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344 return 0;
3345}
3346
3347Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3349
3350 // Handle the integer div common cases
3351 if (Instruction *Common = commonIDivTransforms(I))
3352 return Common;
3353
3354 // X udiv C^2 -> X >> C
3355 // Check to see if this is an unsigned division with an exact power of 2,
3356 // if so, convert to a right shift.
3357 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3358 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003359 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003360 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3361 }
3362
3363 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3364 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3365 if (RHSI->getOpcode() == Instruction::Shl &&
3366 isa<ConstantInt>(RHSI->getOperand(0))) {
3367 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3368 if (C1.isPowerOf2()) {
3369 Value *N = RHSI->getOperand(1);
3370 const Type *NTy = N->getType();
3371 if (uint32_t C2 = C1.logBase2()) {
3372 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003373 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003375 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003376 }
3377 }
3378 }
3379
3380 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3381 // where C1&C2 are powers of two.
3382 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3383 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3384 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3385 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3386 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3387 // Compute the shift amounts
3388 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3389 // Construct the "on true" case of the select
3390 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003391 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003392 Op0, TC, SI->getName()+".t");
3393 TSI = InsertNewInstBefore(TSI, I);
3394
3395 // Construct the "on false" case of the select
3396 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003397 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003398 Op0, FC, SI->getName()+".f");
3399 FSI = InsertNewInstBefore(FSI, I);
3400
3401 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003402 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003403 }
3404 }
3405 return 0;
3406}
3407
3408Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3410
3411 // Handle the integer div common cases
3412 if (Instruction *Common = commonIDivTransforms(I))
3413 return Common;
3414
3415 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3416 // sdiv X, -1 == -X
3417 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003418 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419
3420 // -X/C -> X/-C
3421 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00003422 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 }
3424
3425 // If the sign bits of both operands are zero (i.e. we can prove they are
3426 // unsigned inputs), turn this into a udiv.
3427 if (I.getType()->isInteger()) {
3428 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3429 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003430 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003431 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003432 }
3433 }
3434
3435 return 0;
3436}
3437
3438Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3439 return commonDivTransforms(I);
3440}
3441
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442/// This function implements the transforms on rem instructions that work
3443/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3444/// is used by the visitors to those instructions.
3445/// @brief Transforms common to all three rem instructions
3446Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3447 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3448
Chris Lattner653ef3c2008-02-19 06:12:18 +00003449 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003450 if (Constant *LHS = dyn_cast<Constant>(Op0))
3451 if (LHS->isNullValue())
3452 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3453
Chris Lattner653ef3c2008-02-19 06:12:18 +00003454 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3455 if (I.getType()->isFPOrFPVector())
3456 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003457 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003458 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459 if (isa<UndefValue>(Op1))
3460 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3461
3462 // Handle cases involving: rem X, (select Cond, Y, Z)
3463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3464 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3465 // the same basic block, then we replace the select with Y, and the
3466 // condition of the select with false (if the cond value is in the same
3467 // BB). If the select has uses other than the div, this allows them to be
3468 // simplified also.
3469 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3470 if (ST->isNullValue()) {
3471 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3472 if (CondI && CondI->getParent() == I.getParent())
3473 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3474 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3475 I.setOperand(1, SI->getOperand(2));
3476 else
3477 UpdateValueUsesWith(SI, SI->getOperand(2));
3478 return &I;
3479 }
3480 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3481 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3482 if (ST->isNullValue()) {
3483 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3484 if (CondI && CondI->getParent() == I.getParent())
3485 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3486 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3487 I.setOperand(1, SI->getOperand(1));
3488 else
3489 UpdateValueUsesWith(SI, SI->getOperand(1));
3490 return &I;
3491 }
3492 }
3493
3494 return 0;
3495}
3496
3497/// This function implements the transforms common to both integer remainder
3498/// instructions (urem and srem). It is called by the visitors to those integer
3499/// remainder instructions.
3500/// @brief Common integer remainder transforms
3501Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3503
3504 if (Instruction *common = commonRemTransforms(I))
3505 return common;
3506
3507 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3508 // X % 0 == undef, we don't need to preserve faults!
3509 if (RHS->equalsInt(0))
3510 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3511
3512 if (RHS->equalsInt(1)) // X % 1 == 0
3513 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3514
3515 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3516 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3517 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3518 return R;
3519 } else if (isa<PHINode>(Op0I)) {
3520 if (Instruction *NV = FoldOpIntoPhi(I))
3521 return NV;
3522 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003523
3524 // See if we can fold away this rem instruction.
3525 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3526 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3527 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3528 KnownZero, KnownOne))
3529 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530 }
3531 }
3532
3533 return 0;
3534}
3535
3536Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3538
3539 if (Instruction *common = commonIRemTransforms(I))
3540 return common;
3541
3542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3543 // X urem C^2 -> X and C
3544 // Check to see if this is an unsigned remainder with an exact power of 2,
3545 // if so, convert to a bitwise and.
3546 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3547 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003548 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003549 }
3550
3551 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3552 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3553 if (RHSI->getOpcode() == Instruction::Shl &&
3554 isa<ConstantInt>(RHSI->getOperand(0))) {
3555 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3556 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003557 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003559 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003560 }
3561 }
3562 }
3563
3564 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3565 // where C1&C2 are powers of two.
3566 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3567 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3568 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3569 // STO == 0 and SFO == 0 handled above.
3570 if ((STO->getValue().isPowerOf2()) &&
3571 (SFO->getValue().isPowerOf2())) {
3572 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003573 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003574 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003575 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003576 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577 }
3578 }
3579 }
3580
3581 return 0;
3582}
3583
3584Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3585 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3586
Dan Gohmandb3dd962007-11-05 23:16:33 +00003587 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003588 if (Instruction *common = commonIRemTransforms(I))
3589 return common;
3590
3591 if (Value *RHSNeg = dyn_castNegVal(Op1))
3592 if (!isa<ConstantInt>(RHSNeg) ||
3593 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3594 // X % -Y -> X % Y
3595 AddUsesToWorkList(I);
3596 I.setOperand(1, RHSNeg);
3597 return &I;
3598 }
3599
Dan Gohmandb3dd962007-11-05 23:16:33 +00003600 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003601 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003602 if (I.getType()->isInteger()) {
3603 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3604 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3605 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003606 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003607 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003608 }
3609
3610 return 0;
3611}
3612
3613Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3614 return commonRemTransforms(I);
3615}
3616
3617// isMaxValueMinusOne - return true if this is Max-1
3618static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3619 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3620 if (!isSigned)
3621 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3622 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3623}
3624
3625// isMinValuePlusOne - return true if this is Min+1
3626static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3627 if (!isSigned)
3628 return C->getValue() == 1; // unsigned
3629
3630 // Calculate 1111111111000000000000
3631 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3632 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3633}
3634
3635// isOneBitSet - Return true if there is exactly one bit set in the specified
3636// constant.
3637static bool isOneBitSet(const ConstantInt *CI) {
3638 return CI->getValue().isPowerOf2();
3639}
3640
3641// isHighOnes - Return true if the constant is of the form 1+0+.
3642// This is the same as lowones(~X).
3643static bool isHighOnes(const ConstantInt *CI) {
3644 return (~CI->getValue() + 1).isPowerOf2();
3645}
3646
3647/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3648/// are carefully arranged to allow folding of expressions such as:
3649///
3650/// (A < B) | (A > B) --> (A != B)
3651///
3652/// Note that this is only valid if the first and second predicates have the
3653/// same sign. Is illegal to do: (A u< B) | (A s> B)
3654///
3655/// Three bits are used to represent the condition, as follows:
3656/// 0 A > B
3657/// 1 A == B
3658/// 2 A < B
3659///
3660/// <=> Value Definition
3661/// 000 0 Always false
3662/// 001 1 A > B
3663/// 010 2 A == B
3664/// 011 3 A >= B
3665/// 100 4 A < B
3666/// 101 5 A != B
3667/// 110 6 A <= B
3668/// 111 7 Always true
3669///
3670static unsigned getICmpCode(const ICmpInst *ICI) {
3671 switch (ICI->getPredicate()) {
3672 // False -> 0
3673 case ICmpInst::ICMP_UGT: return 1; // 001
3674 case ICmpInst::ICMP_SGT: return 1; // 001
3675 case ICmpInst::ICMP_EQ: return 2; // 010
3676 case ICmpInst::ICMP_UGE: return 3; // 011
3677 case ICmpInst::ICMP_SGE: return 3; // 011
3678 case ICmpInst::ICMP_ULT: return 4; // 100
3679 case ICmpInst::ICMP_SLT: return 4; // 100
3680 case ICmpInst::ICMP_NE: return 5; // 101
3681 case ICmpInst::ICMP_ULE: return 6; // 110
3682 case ICmpInst::ICMP_SLE: return 6; // 110
3683 // True -> 7
3684 default:
3685 assert(0 && "Invalid ICmp predicate!");
3686 return 0;
3687 }
3688}
3689
3690/// getICmpValue - This is the complement of getICmpCode, which turns an
3691/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003692/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693/// of predicate to use in new icmp instructions.
3694static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3695 switch (code) {
3696 default: assert(0 && "Illegal ICmp code!");
3697 case 0: return ConstantInt::getFalse();
3698 case 1:
3699 if (sign)
3700 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3701 else
3702 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3703 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3704 case 3:
3705 if (sign)
3706 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3707 else
3708 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3709 case 4:
3710 if (sign)
3711 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3712 else
3713 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3714 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3715 case 6:
3716 if (sign)
3717 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3718 else
3719 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3720 case 7: return ConstantInt::getTrue();
3721 }
3722}
3723
3724static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3725 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3726 (ICmpInst::isSignedPredicate(p1) &&
3727 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3728 (ICmpInst::isSignedPredicate(p2) &&
3729 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3730}
3731
3732namespace {
3733// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3734struct FoldICmpLogical {
3735 InstCombiner &IC;
3736 Value *LHS, *RHS;
3737 ICmpInst::Predicate pred;
3738 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3739 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3740 pred(ICI->getPredicate()) {}
3741 bool shouldApply(Value *V) const {
3742 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3743 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003744 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3745 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003746 return false;
3747 }
3748 Instruction *apply(Instruction &Log) const {
3749 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3750 if (ICI->getOperand(0) != LHS) {
3751 assert(ICI->getOperand(1) == LHS);
3752 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3753 }
3754
3755 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3756 unsigned LHSCode = getICmpCode(ICI);
3757 unsigned RHSCode = getICmpCode(RHSICI);
3758 unsigned Code;
3759 switch (Log.getOpcode()) {
3760 case Instruction::And: Code = LHSCode & RHSCode; break;
3761 case Instruction::Or: Code = LHSCode | RHSCode; break;
3762 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3763 default: assert(0 && "Illegal logical opcode!"); return 0;
3764 }
3765
3766 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3767 ICmpInst::isSignedPredicate(ICI->getPredicate());
3768
3769 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3770 if (Instruction *I = dyn_cast<Instruction>(RV))
3771 return I;
3772 // Otherwise, it's a constant boolean value...
3773 return IC.ReplaceInstUsesWith(Log, RV);
3774 }
3775};
3776} // end anonymous namespace
3777
3778// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3779// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3780// guaranteed to be a binary operator.
3781Instruction *InstCombiner::OptAndOp(Instruction *Op,
3782 ConstantInt *OpRHS,
3783 ConstantInt *AndRHS,
3784 BinaryOperator &TheAnd) {
3785 Value *X = Op->getOperand(0);
3786 Constant *Together = 0;
3787 if (!Op->isShift())
3788 Together = And(AndRHS, OpRHS);
3789
3790 switch (Op->getOpcode()) {
3791 case Instruction::Xor:
3792 if (Op->hasOneUse()) {
3793 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003794 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003795 InsertNewInstBefore(And, TheAnd);
3796 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003797 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003798 }
3799 break;
3800 case Instruction::Or:
3801 if (Together == AndRHS) // (X | C) & C --> C
3802 return ReplaceInstUsesWith(TheAnd, AndRHS);
3803
3804 if (Op->hasOneUse() && Together != OpRHS) {
3805 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003806 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 InsertNewInstBefore(Or, TheAnd);
3808 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003809 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810 }
3811 break;
3812 case Instruction::Add:
3813 if (Op->hasOneUse()) {
3814 // Adding a one to a single bit bit-field should be turned into an XOR
3815 // of the bit. First thing to check is to see if this AND is with a
3816 // single bit constant.
3817 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3818
3819 // If there is only one bit set...
3820 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3821 // Ok, at this point, we know that we are masking the result of the
3822 // ADD down to exactly one bit. If the constant we are adding has
3823 // no bits set below this bit, then we can eliminate the ADD.
3824 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3825
3826 // Check to see if any bits below the one bit set in AndRHSV are set.
3827 if ((AddRHS & (AndRHSV-1)) == 0) {
3828 // If not, the only thing that can effect the output of the AND is
3829 // the bit specified by AndRHSV. If that bit is set, the effect of
3830 // the XOR is to toggle the bit. If it is clear, then the ADD has
3831 // no effect.
3832 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3833 TheAnd.setOperand(0, X);
3834 return &TheAnd;
3835 } else {
3836 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003837 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003838 InsertNewInstBefore(NewAnd, TheAnd);
3839 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003840 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003841 }
3842 }
3843 }
3844 }
3845 break;
3846
3847 case Instruction::Shl: {
3848 // We know that the AND will not produce any of the bits shifted in, so if
3849 // the anded constant includes them, clear them now!
3850 //
3851 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3852 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3853 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3854 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3855
3856 if (CI->getValue() == ShlMask) {
3857 // Masking out bits that the shift already masks
3858 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3859 } else if (CI != AndRHS) { // Reducing bits set in and.
3860 TheAnd.setOperand(1, CI);
3861 return &TheAnd;
3862 }
3863 break;
3864 }
3865 case Instruction::LShr:
3866 {
3867 // We know that the AND will not produce any of the bits shifted in, so if
3868 // the anded constant includes them, clear them now! This only applies to
3869 // unsigned shifts, because a signed shr may bring in set bits!
3870 //
3871 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3872 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3873 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3874 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3875
3876 if (CI->getValue() == ShrMask) {
3877 // Masking out bits that the shift already masks.
3878 return ReplaceInstUsesWith(TheAnd, Op);
3879 } else if (CI != AndRHS) {
3880 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3881 return &TheAnd;
3882 }
3883 break;
3884 }
3885 case Instruction::AShr:
3886 // Signed shr.
3887 // See if this is shifting in some sign extension, then masking it out
3888 // with an and.
3889 if (Op->hasOneUse()) {
3890 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3891 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3892 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3893 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3894 if (C == AndRHS) { // Masking out bits shifted in.
3895 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3896 // Make the argument unsigned.
3897 Value *ShVal = Op->getOperand(0);
3898 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003899 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003900 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003902 }
3903 }
3904 break;
3905 }
3906 return 0;
3907}
3908
3909
3910/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3911/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3912/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3913/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3914/// insert new instructions.
3915Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3916 bool isSigned, bool Inside,
3917 Instruction &IB) {
3918 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3919 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3920 "Lo is not <= Hi in range emission code!");
3921
3922 if (Inside) {
3923 if (Lo == Hi) // Trivially false.
3924 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3925
3926 // V >= Min && V < Hi --> V < Hi
3927 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3928 ICmpInst::Predicate pred = (isSigned ?
3929 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3930 return new ICmpInst(pred, V, Hi);
3931 }
3932
3933 // Emit V-Lo <u Hi-Lo
3934 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003935 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003936 InsertNewInstBefore(Add, IB);
3937 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3938 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3939 }
3940
3941 if (Lo == Hi) // Trivially true.
3942 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3943
3944 // V < Min || V >= Hi -> V > Hi-1
3945 Hi = SubOne(cast<ConstantInt>(Hi));
3946 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3947 ICmpInst::Predicate pred = (isSigned ?
3948 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3949 return new ICmpInst(pred, V, Hi);
3950 }
3951
3952 // Emit V-Lo >u Hi-1-Lo
3953 // Note that Hi has already had one subtracted from it, above.
3954 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003955 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003956 InsertNewInstBefore(Add, IB);
3957 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3958 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3959}
3960
3961// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3962// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3963// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3964// not, since all 1s are not contiguous.
3965static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3966 const APInt& V = Val->getValue();
3967 uint32_t BitWidth = Val->getType()->getBitWidth();
3968 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3969
3970 // look for the first zero bit after the run of ones
3971 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3972 // look for the first non-zero bit
3973 ME = V.getActiveBits();
3974 return true;
3975}
3976
3977/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3978/// where isSub determines whether the operator is a sub. If we can fold one of
3979/// the following xforms:
3980///
3981/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3982/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3983/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3984///
3985/// return (A +/- B).
3986///
3987Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3988 ConstantInt *Mask, bool isSub,
3989 Instruction &I) {
3990 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3991 if (!LHSI || LHSI->getNumOperands() != 2 ||
3992 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3993
3994 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3995
3996 switch (LHSI->getOpcode()) {
3997 default: return 0;
3998 case Instruction::And:
3999 if (And(N, Mask) == Mask) {
4000 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4001 if ((Mask->getValue().countLeadingZeros() +
4002 Mask->getValue().countPopulation()) ==
4003 Mask->getValue().getBitWidth())
4004 break;
4005
4006 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4007 // part, we don't need any explicit masks to take them out of A. If that
4008 // is all N is, ignore it.
4009 uint32_t MB = 0, ME = 0;
4010 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4011 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4012 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4013 if (MaskedValueIsZero(RHS, Mask))
4014 break;
4015 }
4016 }
4017 return 0;
4018 case Instruction::Or:
4019 case Instruction::Xor:
4020 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4021 if ((Mask->getValue().countLeadingZeros() +
4022 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4023 && And(N, Mask)->isZero())
4024 break;
4025 return 0;
4026 }
4027
4028 Instruction *New;
4029 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00004030 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004031 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004032 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004033 return InsertNewInstBefore(New, I);
4034}
4035
4036Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4037 bool Changed = SimplifyCommutative(I);
4038 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4039
4040 if (isa<UndefValue>(Op1)) // X & undef -> 0
4041 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4042
4043 // and X, X = X
4044 if (Op0 == Op1)
4045 return ReplaceInstUsesWith(I, Op1);
4046
4047 // See if we can simplify any instructions used by the instruction whose sole
4048 // purpose is to compute bits we don't care about.
4049 if (!isa<VectorType>(I.getType())) {
4050 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4051 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4052 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4053 KnownZero, KnownOne))
4054 return &I;
4055 } else {
4056 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4057 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4058 return ReplaceInstUsesWith(I, I.getOperand(0));
4059 } else if (isa<ConstantAggregateZero>(Op1)) {
4060 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4061 }
4062 }
4063
4064 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4065 const APInt& AndRHSMask = AndRHS->getValue();
4066 APInt NotAndRHS(~AndRHSMask);
4067
4068 // Optimize a variety of ((val OP C1) & C2) combinations...
4069 if (isa<BinaryOperator>(Op0)) {
4070 Instruction *Op0I = cast<Instruction>(Op0);
4071 Value *Op0LHS = Op0I->getOperand(0);
4072 Value *Op0RHS = Op0I->getOperand(1);
4073 switch (Op0I->getOpcode()) {
4074 case Instruction::Xor:
4075 case Instruction::Or:
4076 // If the mask is only needed on one incoming arm, push it up.
4077 if (Op0I->hasOneUse()) {
4078 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4079 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004080 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004081 Op0RHS->getName()+".masked");
4082 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004083 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004084 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4085 }
4086 if (!isa<Constant>(Op0RHS) &&
4087 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4088 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004089 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 Op0LHS->getName()+".masked");
4091 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004092 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004093 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4094 }
4095 }
4096
4097 break;
4098 case Instruction::Add:
4099 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4100 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4101 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4102 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004103 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004104 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004105 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004106 break;
4107
4108 case Instruction::Sub:
4109 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4110 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4111 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4112 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004113 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004114 break;
4115 }
4116
4117 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4118 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4119 return Res;
4120 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4121 // If this is an integer truncation or change from signed-to-unsigned, and
4122 // if the source is an and/or with immediate, transform it. This
4123 // frequently occurs for bitfield accesses.
4124 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4125 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4126 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004127 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 if (CastOp->getOpcode() == Instruction::And) {
4129 // Change: and (cast (and X, C1) to T), C2
4130 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4131 // This will fold the two constants together, which may allow
4132 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004133 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004134 CastOp->getOperand(0), I.getType(),
4135 CastOp->getName()+".shrunk");
4136 NewCast = InsertNewInstBefore(NewCast, I);
4137 // trunc_or_bitcast(C1)&C2
4138 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4139 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004140 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004141 } else if (CastOp->getOpcode() == Instruction::Or) {
4142 // Change: and (cast (or X, C1) to T), C2
4143 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4144 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4145 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4146 return ReplaceInstUsesWith(I, AndRHS);
4147 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004148 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149 }
4150 }
4151
4152 // Try to fold constant and into select arguments.
4153 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4154 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4155 return R;
4156 if (isa<PHINode>(Op0))
4157 if (Instruction *NV = FoldOpIntoPhi(I))
4158 return NV;
4159 }
4160
4161 Value *Op0NotVal = dyn_castNotVal(Op0);
4162 Value *Op1NotVal = dyn_castNotVal(Op1);
4163
4164 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4166
4167 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4168 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004169 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170 I.getName()+".demorgan");
4171 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004172 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004173 }
4174
4175 {
4176 Value *A = 0, *B = 0, *C = 0, *D = 0;
4177 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4178 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4179 return ReplaceInstUsesWith(I, Op1);
4180
4181 // (A|B) & ~(A&B) -> A^B
4182 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4183 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004184 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 }
4186 }
4187
4188 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4189 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4190 return ReplaceInstUsesWith(I, Op0);
4191
4192 // ~(A&B) & (A|B) -> A^B
4193 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4194 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004195 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004196 }
4197 }
4198
4199 if (Op0->hasOneUse() &&
4200 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4201 if (A == Op1) { // (A^B)&A -> A&(A^B)
4202 I.swapOperands(); // Simplify below
4203 std::swap(Op0, Op1);
4204 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4205 cast<BinaryOperator>(Op0)->swapOperands();
4206 I.swapOperands(); // Simplify below
4207 std::swap(Op0, Op1);
4208 }
4209 }
4210 if (Op1->hasOneUse() &&
4211 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4212 if (B == Op0) { // B&(A^B) -> B&(B^A)
4213 cast<BinaryOperator>(Op1)->swapOperands();
4214 std::swap(A, B);
4215 }
4216 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00004217 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004218 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004219 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004220 }
4221 }
4222 }
4223
4224 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4225 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4226 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4227 return R;
4228
4229 Value *LHSVal, *RHSVal;
4230 ConstantInt *LHSCst, *RHSCst;
4231 ICmpInst::Predicate LHSCC, RHSCC;
4232 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4233 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4234 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4235 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4236 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4237 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4238 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00004239 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4240
4241 // Don't try to fold ICMP_SLT + ICMP_ULT.
4242 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4243 ICmpInst::isSignedPredicate(LHSCC) ==
4244 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00004246 ICmpInst::Predicate GT;
4247 if (ICmpInst::isSignedPredicate(LHSCC) ||
4248 (ICmpInst::isEquality(LHSCC) &&
4249 ICmpInst::isSignedPredicate(RHSCC)))
4250 GT = ICmpInst::ICMP_SGT;
4251 else
4252 GT = ICmpInst::ICMP_UGT;
4253
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004254 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4255 ICmpInst *LHS = cast<ICmpInst>(Op0);
4256 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4257 std::swap(LHS, RHS);
4258 std::swap(LHSCst, RHSCst);
4259 std::swap(LHSCC, RHSCC);
4260 }
4261
4262 // At this point, we know we have have two icmp instructions
4263 // comparing a value against two constants and and'ing the result
4264 // together. Because of the above check, we know that we only have
4265 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4266 // (from the FoldICmpLogical check above), that the two constants
4267 // are not equal and that the larger constant is on the RHS
4268 assert(LHSCst != RHSCst && "Compares not folded above?");
4269
4270 switch (LHSCC) {
4271 default: assert(0 && "Unknown integer condition code!");
4272 case ICmpInst::ICMP_EQ:
4273 switch (RHSCC) {
4274 default: assert(0 && "Unknown integer condition code!");
4275 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4276 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4277 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
4278 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4279 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4280 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4281 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4282 return ReplaceInstUsesWith(I, LHS);
4283 }
4284 case ICmpInst::ICMP_NE:
4285 switch (RHSCC) {
4286 default: assert(0 && "Unknown integer condition code!");
4287 case ICmpInst::ICMP_ULT:
4288 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4289 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4290 break; // (X != 13 & X u< 15) -> no change
4291 case ICmpInst::ICMP_SLT:
4292 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4293 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4294 break; // (X != 13 & X s< 15) -> no change
4295 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4296 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4297 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4298 return ReplaceInstUsesWith(I, RHS);
4299 case ICmpInst::ICMP_NE:
4300 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4301 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004302 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004303 LHSVal->getName()+".off");
4304 InsertNewInstBefore(Add, I);
4305 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4306 ConstantInt::get(Add->getType(), 1));
4307 }
4308 break; // (X != 13 & X != 15) -> no change
4309 }
4310 break;
4311 case ICmpInst::ICMP_ULT:
4312 switch (RHSCC) {
4313 default: assert(0 && "Unknown integer condition code!");
4314 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4315 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4316 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4317 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4318 break;
4319 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4320 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4321 return ReplaceInstUsesWith(I, LHS);
4322 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4323 break;
4324 }
4325 break;
4326 case ICmpInst::ICMP_SLT:
4327 switch (RHSCC) {
4328 default: assert(0 && "Unknown integer condition code!");
4329 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4330 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4331 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4332 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4333 break;
4334 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4335 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4336 return ReplaceInstUsesWith(I, LHS);
4337 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4338 break;
4339 }
4340 break;
4341 case ICmpInst::ICMP_UGT:
4342 switch (RHSCC) {
4343 default: assert(0 && "Unknown integer condition code!");
4344 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4345 return ReplaceInstUsesWith(I, LHS);
4346 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4347 return ReplaceInstUsesWith(I, RHS);
4348 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4349 break;
4350 case ICmpInst::ICMP_NE:
4351 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4352 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4353 break; // (X u> 13 & X != 15) -> no change
4354 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4355 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4356 true, I);
4357 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4358 break;
4359 }
4360 break;
4361 case ICmpInst::ICMP_SGT:
4362 switch (RHSCC) {
4363 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00004364 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004365 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4366 return ReplaceInstUsesWith(I, RHS);
4367 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4368 break;
4369 case ICmpInst::ICMP_NE:
4370 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4371 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4372 break; // (X s> 13 & X != 15) -> no change
4373 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4374 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4375 true, I);
4376 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4377 break;
4378 }
4379 break;
4380 }
4381 }
4382 }
4383
4384 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4385 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4386 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4387 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4388 const Type *SrcTy = Op0C->getOperand(0)->getType();
4389 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4390 // Only do this if the casts both really cause code to be generated.
4391 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4392 I.getType(), TD) &&
4393 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4394 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004395 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004396 Op1C->getOperand(0),
4397 I.getName());
4398 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004399 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004400 }
4401 }
4402
4403 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4404 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4405 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4406 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4407 SI0->getOperand(1) == SI1->getOperand(1) &&
4408 (SI0->hasOneUse() || SI1->hasOneUse())) {
4409 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004410 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004411 SI1->getOperand(0),
4412 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004413 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004414 SI1->getOperand(1));
4415 }
4416 }
4417
Chris Lattner91882432007-10-24 05:38:08 +00004418 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4419 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4420 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4421 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4422 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4423 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4424 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4425 // If either of the constants are nans, then the whole thing returns
4426 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004427 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004428 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4429 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4430 RHS->getOperand(0));
4431 }
4432 }
4433 }
4434
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004435 return Changed ? &I : 0;
4436}
4437
4438/// CollectBSwapParts - Look to see if the specified value defines a single byte
4439/// in the result. If it does, and if the specified byte hasn't been filled in
4440/// yet, fill it in and return false.
4441static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4442 Instruction *I = dyn_cast<Instruction>(V);
4443 if (I == 0) return true;
4444
4445 // If this is an or instruction, it is an inner node of the bswap.
4446 if (I->getOpcode() == Instruction::Or)
4447 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4448 CollectBSwapParts(I->getOperand(1), ByteValues);
4449
4450 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4451 // If this is a shift by a constant int, and it is "24", then its operand
4452 // defines a byte. We only handle unsigned types here.
4453 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4454 // Not shifting the entire input by N-1 bytes?
4455 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4456 8*(ByteValues.size()-1))
4457 return true;
4458
4459 unsigned DestNo;
4460 if (I->getOpcode() == Instruction::Shl) {
4461 // X << 24 defines the top byte with the lowest of the input bytes.
4462 DestNo = ByteValues.size()-1;
4463 } else {
4464 // X >>u 24 defines the low byte with the highest of the input bytes.
4465 DestNo = 0;
4466 }
4467
4468 // If the destination byte value is already defined, the values are or'd
4469 // together, which isn't a bswap (unless it's an or of the same bits).
4470 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4471 return true;
4472 ByteValues[DestNo] = I->getOperand(0);
4473 return false;
4474 }
4475
4476 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4477 // don't have this.
4478 Value *Shift = 0, *ShiftLHS = 0;
4479 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4480 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4481 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4482 return true;
4483 Instruction *SI = cast<Instruction>(Shift);
4484
4485 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4486 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4487 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4488 return true;
4489
4490 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4491 unsigned DestByte;
4492 if (AndAmt->getValue().getActiveBits() > 64)
4493 return true;
4494 uint64_t AndAmtVal = AndAmt->getZExtValue();
4495 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4496 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4497 break;
4498 // Unknown mask for bswap.
4499 if (DestByte == ByteValues.size()) return true;
4500
4501 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4502 unsigned SrcByte;
4503 if (SI->getOpcode() == Instruction::Shl)
4504 SrcByte = DestByte - ShiftBytes;
4505 else
4506 SrcByte = DestByte + ShiftBytes;
4507
4508 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4509 if (SrcByte != ByteValues.size()-DestByte-1)
4510 return true;
4511
4512 // If the destination byte value is already defined, the values are or'd
4513 // together, which isn't a bswap (unless it's an or of the same bits).
4514 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4515 return true;
4516 ByteValues[DestByte] = SI->getOperand(0);
4517 return false;
4518}
4519
4520/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4521/// If so, insert the new bswap intrinsic and return it.
4522Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4523 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4524 if (!ITy || ITy->getBitWidth() % 16)
4525 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4526
4527 /// ByteValues - For each byte of the result, we keep track of which value
4528 /// defines each byte.
4529 SmallVector<Value*, 8> ByteValues;
4530 ByteValues.resize(ITy->getBitWidth()/8);
4531
4532 // Try to find all the pieces corresponding to the bswap.
4533 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4534 CollectBSwapParts(I.getOperand(1), ByteValues))
4535 return 0;
4536
4537 // Check to see if all of the bytes come from the same value.
4538 Value *V = ByteValues[0];
4539 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4540
4541 // Check to make sure that all of the bytes come from the same value.
4542 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4543 if (ByteValues[i] != V)
4544 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004545 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004546 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004547 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004548 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004549}
4550
4551
4552Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4553 bool Changed = SimplifyCommutative(I);
4554 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4555
4556 if (isa<UndefValue>(Op1)) // X | undef -> -1
4557 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4558
4559 // or X, X = X
4560 if (Op0 == Op1)
4561 return ReplaceInstUsesWith(I, Op0);
4562
4563 // See if we can simplify any instructions used by the instruction whose sole
4564 // purpose is to compute bits we don't care about.
4565 if (!isa<VectorType>(I.getType())) {
4566 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4567 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4568 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4569 KnownZero, KnownOne))
4570 return &I;
4571 } else if (isa<ConstantAggregateZero>(Op1)) {
4572 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4573 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4574 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4575 return ReplaceInstUsesWith(I, I.getOperand(1));
4576 }
4577
4578
4579
4580 // or X, -1 == -1
4581 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4582 ConstantInt *C1 = 0; Value *X = 0;
4583 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4584 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004585 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004586 InsertNewInstBefore(Or, I);
4587 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004588 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004589 ConstantInt::get(RHS->getValue() | C1->getValue()));
4590 }
4591
4592 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4593 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004594 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004595 InsertNewInstBefore(Or, I);
4596 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004597 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004598 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4599 }
4600
4601 // Try to fold constant and into select arguments.
4602 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4603 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4604 return R;
4605 if (isa<PHINode>(Op0))
4606 if (Instruction *NV = FoldOpIntoPhi(I))
4607 return NV;
4608 }
4609
4610 Value *A = 0, *B = 0;
4611 ConstantInt *C1 = 0, *C2 = 0;
4612
4613 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4614 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4615 return ReplaceInstUsesWith(I, Op1);
4616 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4617 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4618 return ReplaceInstUsesWith(I, Op0);
4619
4620 // (A | B) | C and A | (B | C) -> bswap if possible.
4621 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4622 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4623 match(Op1, m_Or(m_Value(), m_Value())) ||
4624 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4625 match(Op1, m_Shift(m_Value(), m_Value())))) {
4626 if (Instruction *BSwap = MatchBSwap(I))
4627 return BSwap;
4628 }
4629
4630 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4631 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4632 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004633 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004634 InsertNewInstBefore(NOr, I);
4635 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004636 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004637 }
4638
4639 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4640 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4641 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004642 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004643 InsertNewInstBefore(NOr, I);
4644 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004645 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004646 }
4647
4648 // (A & C)|(B & D)
4649 Value *C = 0, *D = 0;
4650 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4651 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4652 Value *V1 = 0, *V2 = 0, *V3 = 0;
4653 C1 = dyn_cast<ConstantInt>(C);
4654 C2 = dyn_cast<ConstantInt>(D);
4655 if (C1 && C2) { // (A & C1)|(B & C2)
4656 // If we have: ((V + N) & C1) | (V & C2)
4657 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4658 // replace with V+N.
4659 if (C1->getValue() == ~C2->getValue()) {
4660 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4661 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4662 // Add commutes, try both ways.
4663 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4664 return ReplaceInstUsesWith(I, A);
4665 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4666 return ReplaceInstUsesWith(I, A);
4667 }
4668 // Or commutes, try both ways.
4669 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4670 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4671 // Add commutes, try both ways.
4672 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4673 return ReplaceInstUsesWith(I, B);
4674 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4675 return ReplaceInstUsesWith(I, B);
4676 }
4677 }
4678 V1 = 0; V2 = 0; V3 = 0;
4679 }
4680
4681 // Check to see if we have any common things being and'ed. If so, find the
4682 // terms for V1 & (V2|V3).
4683 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4684 if (A == B) // (A & C)|(A & D) == A & (C|D)
4685 V1 = A, V2 = C, V3 = D;
4686 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4687 V1 = A, V2 = B, V3 = C;
4688 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4689 V1 = C, V2 = A, V3 = D;
4690 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4691 V1 = C, V2 = A, V3 = B;
4692
4693 if (V1) {
4694 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004695 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4696 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004697 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004698 }
4699 }
4700
4701 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4702 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4703 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4704 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4705 SI0->getOperand(1) == SI1->getOperand(1) &&
4706 (SI0->hasOneUse() || SI1->hasOneUse())) {
4707 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004708 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004709 SI1->getOperand(0),
4710 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004711 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004712 SI1->getOperand(1));
4713 }
4714 }
4715
4716 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4717 if (A == Op1) // ~A | A == -1
4718 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4719 } else {
4720 A = 0;
4721 }
4722 // Note, A is still live here!
4723 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4724 if (Op0 == B)
4725 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4726
4727 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4728 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004729 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004730 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004731 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004732 }
4733 }
4734
4735 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4736 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4737 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4738 return R;
4739
4740 Value *LHSVal, *RHSVal;
4741 ConstantInt *LHSCst, *RHSCst;
4742 ICmpInst::Predicate LHSCC, RHSCC;
4743 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4744 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4745 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4746 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4747 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4748 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4749 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4750 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4751 // We can't fold (ugt x, C) | (sgt x, C2).
4752 PredicatesFoldable(LHSCC, RHSCC)) {
4753 // Ensure that the larger constant is on the RHS.
4754 ICmpInst *LHS = cast<ICmpInst>(Op0);
4755 bool NeedsSwap;
4756 if (ICmpInst::isSignedPredicate(LHSCC))
4757 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4758 else
4759 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4760
4761 if (NeedsSwap) {
4762 std::swap(LHS, RHS);
4763 std::swap(LHSCst, RHSCst);
4764 std::swap(LHSCC, RHSCC);
4765 }
4766
4767 // At this point, we know we have have two icmp instructions
4768 // comparing a value against two constants and or'ing the result
4769 // together. Because of the above check, we know that we only have
4770 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4771 // FoldICmpLogical check above), that the two constants are not
4772 // equal.
4773 assert(LHSCst != RHSCst && "Compares not folded above?");
4774
4775 switch (LHSCC) {
4776 default: assert(0 && "Unknown integer condition code!");
4777 case ICmpInst::ICMP_EQ:
4778 switch (RHSCC) {
4779 default: assert(0 && "Unknown integer condition code!");
4780 case ICmpInst::ICMP_EQ:
4781 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4782 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004783 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004784 LHSVal->getName()+".off");
4785 InsertNewInstBefore(Add, I);
4786 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4787 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4788 }
4789 break; // (X == 13 | X == 15) -> no change
4790 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4791 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4792 break;
4793 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4794 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4795 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4796 return ReplaceInstUsesWith(I, RHS);
4797 }
4798 break;
4799 case ICmpInst::ICMP_NE:
4800 switch (RHSCC) {
4801 default: assert(0 && "Unknown integer condition code!");
4802 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4803 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4804 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4805 return ReplaceInstUsesWith(I, LHS);
4806 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4807 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4808 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4809 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4810 }
4811 break;
4812 case ICmpInst::ICMP_ULT:
4813 switch (RHSCC) {
4814 default: assert(0 && "Unknown integer condition code!");
4815 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4816 break;
4817 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004818 // If RHSCst is [us]MAXINT, it is always false. Not handling
4819 // this can cause overflow.
4820 if (RHSCst->isMaxValue(false))
4821 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004822 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4823 false, I);
4824 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4825 break;
4826 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4827 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4828 return ReplaceInstUsesWith(I, RHS);
4829 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4830 break;
4831 }
4832 break;
4833 case ICmpInst::ICMP_SLT:
4834 switch (RHSCC) {
4835 default: assert(0 && "Unknown integer condition code!");
4836 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4837 break;
4838 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004839 // If RHSCst is [us]MAXINT, it is always false. Not handling
4840 // this can cause overflow.
4841 if (RHSCst->isMaxValue(true))
4842 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004843 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4844 false, I);
4845 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4846 break;
4847 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4848 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4849 return ReplaceInstUsesWith(I, RHS);
4850 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4851 break;
4852 }
4853 break;
4854 case ICmpInst::ICMP_UGT:
4855 switch (RHSCC) {
4856 default: assert(0 && "Unknown integer condition code!");
4857 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4858 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4859 return ReplaceInstUsesWith(I, LHS);
4860 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4861 break;
4862 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4863 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4864 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4865 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4866 break;
4867 }
4868 break;
4869 case ICmpInst::ICMP_SGT:
4870 switch (RHSCC) {
4871 default: assert(0 && "Unknown integer condition code!");
4872 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4873 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4874 return ReplaceInstUsesWith(I, LHS);
4875 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4876 break;
4877 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4878 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4879 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4880 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4881 break;
4882 }
4883 break;
4884 }
4885 }
4886 }
4887
4888 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004889 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004890 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4891 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004892 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4893 !isa<ICmpInst>(Op1C->getOperand(0))) {
4894 const Type *SrcTy = Op0C->getOperand(0)->getType();
4895 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4896 // Only do this if the casts both really cause code to be
4897 // generated.
4898 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4899 I.getType(), TD) &&
4900 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4901 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004902 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004903 Op1C->getOperand(0),
4904 I.getName());
4905 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004906 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004907 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004908 }
4909 }
Chris Lattner91882432007-10-24 05:38:08 +00004910 }
4911
4912
4913 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4914 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4915 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4916 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004917 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4918 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004919 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4920 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4921 // If either of the constants are nans, then the whole thing returns
4922 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004923 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004924 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4925
4926 // Otherwise, no need to compare the two constants, compare the
4927 // rest.
4928 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4929 RHS->getOperand(0));
4930 }
4931 }
4932 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004933
4934 return Changed ? &I : 0;
4935}
4936
Dan Gohman089efff2008-05-13 00:00:25 +00004937namespace {
4938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004939// XorSelf - Implements: X ^ X --> 0
4940struct XorSelf {
4941 Value *RHS;
4942 XorSelf(Value *rhs) : RHS(rhs) {}
4943 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4944 Instruction *apply(BinaryOperator &Xor) const {
4945 return &Xor;
4946 }
4947};
4948
Dan Gohman089efff2008-05-13 00:00:25 +00004949}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004950
4951Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4952 bool Changed = SimplifyCommutative(I);
4953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4954
Evan Chenge5cd8032008-03-25 20:07:13 +00004955 if (isa<UndefValue>(Op1)) {
4956 if (isa<UndefValue>(Op0))
4957 // Handle undef ^ undef -> 0 special case. This is a common
4958 // idiom (misuse).
4959 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004960 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004961 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004962
4963 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4964 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004965 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4967 }
4968
4969 // See if we can simplify any instructions used by the instruction whose sole
4970 // purpose is to compute bits we don't care about.
4971 if (!isa<VectorType>(I.getType())) {
4972 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4973 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4974 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4975 KnownZero, KnownOne))
4976 return &I;
4977 } else if (isa<ConstantAggregateZero>(Op1)) {
4978 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4979 }
4980
4981 // Is this a ~ operation?
4982 if (Value *NotOp = dyn_castNotVal(&I)) {
4983 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4984 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4985 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4986 if (Op0I->getOpcode() == Instruction::And ||
4987 Op0I->getOpcode() == Instruction::Or) {
4988 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4989 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4990 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004991 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004992 Op0I->getOperand(1)->getName()+".not");
4993 InsertNewInstBefore(NotY, I);
4994 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004995 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004996 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004997 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004998 }
4999 }
5000 }
5001 }
5002
5003
5004 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00005005 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5006 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5007 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005008 return new ICmpInst(ICI->getInversePredicate(),
5009 ICI->getOperand(0), ICI->getOperand(1));
5010
Nick Lewycky1405e922007-08-06 20:04:16 +00005011 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5012 return new FCmpInst(FCI->getInversePredicate(),
5013 FCI->getOperand(0), FCI->getOperand(1));
5014 }
5015
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005016 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5017 // ~(c-X) == X-c-1 == X+(-c-1)
5018 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5019 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5020 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5021 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5022 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005023 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005024 }
5025
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005026 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005027 if (Op0I->getOpcode() == Instruction::Add) {
5028 // ~(X-c) --> (-c-1)-X
5029 if (RHS->isAllOnesValue()) {
5030 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005031 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005032 ConstantExpr::getSub(NegOp0CI,
5033 ConstantInt::get(I.getType(), 1)),
5034 Op0I->getOperand(0));
5035 } else if (RHS->getValue().isSignBit()) {
5036 // (X + C) ^ signbit -> (X + C + signbit)
5037 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005038 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005039
5040 }
5041 } else if (Op0I->getOpcode() == Instruction::Or) {
5042 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5043 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5044 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5045 // Anything in both C1 and C2 is known to be zero, remove it from
5046 // NewRHS.
5047 Constant *CommonBits = And(Op0CI, RHS);
5048 NewRHS = ConstantExpr::getAnd(NewRHS,
5049 ConstantExpr::getNot(CommonBits));
5050 AddToWorkList(Op0I);
5051 I.setOperand(0, Op0I->getOperand(0));
5052 I.setOperand(1, NewRHS);
5053 return &I;
5054 }
5055 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005056 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005057 }
5058
5059 // Try to fold constant and into select arguments.
5060 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5061 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5062 return R;
5063 if (isa<PHINode>(Op0))
5064 if (Instruction *NV = FoldOpIntoPhi(I))
5065 return NV;
5066 }
5067
5068 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5069 if (X == Op1)
5070 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5071
5072 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5073 if (X == Op0)
5074 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5075
5076
5077 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5078 if (Op1I) {
5079 Value *A, *B;
5080 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5081 if (A == Op0) { // B^(B|A) == (A|B)^B
5082 Op1I->swapOperands();
5083 I.swapOperands();
5084 std::swap(Op0, Op1);
5085 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5086 I.swapOperands(); // Simplified below.
5087 std::swap(Op0, Op1);
5088 }
5089 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5090 if (Op0 == A) // A^(A^B) == B
5091 return ReplaceInstUsesWith(I, B);
5092 else if (Op0 == B) // A^(B^A) == B
5093 return ReplaceInstUsesWith(I, A);
5094 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5095 if (A == Op0) { // A^(A&B) -> A^(B&A)
5096 Op1I->swapOperands();
5097 std::swap(A, B);
5098 }
5099 if (B == Op0) { // A^(B&A) -> (B&A)^A
5100 I.swapOperands(); // Simplified below.
5101 std::swap(Op0, Op1);
5102 }
5103 }
5104 }
5105
5106 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5107 if (Op0I) {
5108 Value *A, *B;
5109 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5110 if (A == Op1) // (B|A)^B == (A|B)^B
5111 std::swap(A, B);
5112 if (B == Op1) { // (A|B)^B == A & ~B
5113 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00005114 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5115 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005116 }
5117 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5118 if (Op1 == A) // (A^B)^A == B
5119 return ReplaceInstUsesWith(I, B);
5120 else if (Op1 == B) // (B^A)^A == B
5121 return ReplaceInstUsesWith(I, A);
5122 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5123 if (A == Op1) // (A&B)^A -> (B&A)^A
5124 std::swap(A, B);
5125 if (B == Op1 && // (B&A)^A == ~B & A
5126 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5127 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00005128 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5129 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005130 }
5131 }
5132 }
5133
5134 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5135 if (Op0I && Op1I && Op0I->isShift() &&
5136 Op0I->getOpcode() == Op1I->getOpcode() &&
5137 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5138 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5139 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005140 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005141 Op1I->getOperand(0),
5142 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005143 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005144 Op1I->getOperand(1));
5145 }
5146
5147 if (Op0I && Op1I) {
5148 Value *A, *B, *C, *D;
5149 // (A & B)^(A | B) -> A ^ B
5150 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5151 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5152 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005153 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005154 }
5155 // (A | B)^(A & B) -> A ^ B
5156 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5157 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5158 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005159 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005160 }
5161
5162 // (A & B)^(C & D)
5163 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5164 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5165 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5166 // (X & Y)^(X & Y) -> (Y^Z) & X
5167 Value *X = 0, *Y = 0, *Z = 0;
5168 if (A == C)
5169 X = A, Y = B, Z = D;
5170 else if (A == D)
5171 X = A, Y = B, Z = C;
5172 else if (B == C)
5173 X = B, Y = A, Z = D;
5174 else if (B == D)
5175 X = B, Y = A, Z = C;
5176
5177 if (X) {
5178 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005179 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5180 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005181 }
5182 }
5183 }
5184
5185 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5186 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5187 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5188 return R;
5189
5190 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005191 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005192 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5193 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5194 const Type *SrcTy = Op0C->getOperand(0)->getType();
5195 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5196 // Only do this if the casts both really cause code to be generated.
5197 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5198 I.getType(), TD) &&
5199 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5200 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005201 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005202 Op1C->getOperand(0),
5203 I.getName());
5204 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005205 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005206 }
5207 }
Chris Lattner91882432007-10-24 05:38:08 +00005208 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005209 return Changed ? &I : 0;
5210}
5211
5212/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5213/// overflowed for this type.
5214static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5215 ConstantInt *In2, bool IsSigned = false) {
5216 Result = cast<ConstantInt>(Add(In1, In2));
5217
5218 if (IsSigned)
5219 if (In2->getValue().isNegative())
5220 return Result->getValue().sgt(In1->getValue());
5221 else
5222 return Result->getValue().slt(In1->getValue());
5223 else
5224 return Result->getValue().ult(In1->getValue());
5225}
5226
5227/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5228/// code necessary to compute the offset from the base pointer (without adding
5229/// in the base pointer). Return the result as a signed integer of intptr size.
5230static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5231 TargetData &TD = IC.getTargetData();
5232 gep_type_iterator GTI = gep_type_begin(GEP);
5233 const Type *IntPtrTy = TD.getIntPtrType();
5234 Value *Result = Constant::getNullValue(IntPtrTy);
5235
5236 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005237 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005238 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5239
5240 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5241 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00005242 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005243 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5244 if (OpC->isZero()) continue;
5245
5246 // Handle a struct index, which adds its field offset to the pointer.
5247 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5248 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5249
5250 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5251 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5252 else
5253 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005254 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005255 ConstantInt::get(IntPtrTy, Size),
5256 GEP->getName()+".offs"), I);
5257 continue;
5258 }
5259
5260 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5261 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5262 Scale = ConstantExpr::getMul(OC, Scale);
5263 if (Constant *RC = dyn_cast<Constant>(Result))
5264 Result = ConstantExpr::getAdd(RC, Scale);
5265 else {
5266 // Emit an add instruction.
5267 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005268 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005269 GEP->getName()+".offs"), I);
5270 }
5271 continue;
5272 }
5273 // Convert to correct type.
5274 if (Op->getType() != IntPtrTy) {
5275 if (Constant *OpC = dyn_cast<Constant>(Op))
5276 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5277 else
5278 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5279 Op->getName()+".c"), I);
5280 }
5281 if (Size != 1) {
5282 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5283 if (Constant *OpC = dyn_cast<Constant>(Op))
5284 Op = ConstantExpr::getMul(OpC, Scale);
5285 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005286 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005287 GEP->getName()+".idx"), I);
5288 }
5289
5290 // Emit an add instruction.
5291 if (isa<Constant>(Op) && isa<Constant>(Result))
5292 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5293 cast<Constant>(Result));
5294 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005295 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005296 GEP->getName()+".offs"), I);
5297 }
5298 return Result;
5299}
5300
Chris Lattnereba75862008-04-22 02:53:33 +00005301
5302/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5303/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5304/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5305/// complex, and scales are involved. The above expression would also be legal
5306/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5307/// later form is less amenable to optimization though, and we are allowed to
5308/// generate the first by knowing that pointer arithmetic doesn't overflow.
5309///
5310/// If we can't emit an optimized form for this expression, this returns null.
5311///
5312static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5313 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005314 TargetData &TD = IC.getTargetData();
5315 gep_type_iterator GTI = gep_type_begin(GEP);
5316
5317 // Check to see if this gep only has a single variable index. If so, and if
5318 // any constant indices are a multiple of its scale, then we can compute this
5319 // in terms of the scale of the variable index. For example, if the GEP
5320 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5321 // because the expression will cross zero at the same point.
5322 unsigned i, e = GEP->getNumOperands();
5323 int64_t Offset = 0;
5324 for (i = 1; i != e; ++i, ++GTI) {
5325 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5326 // Compute the aggregate offset of constant indices.
5327 if (CI->isZero()) continue;
5328
5329 // Handle a struct index, which adds its field offset to the pointer.
5330 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5331 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5332 } else {
5333 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5334 Offset += Size*CI->getSExtValue();
5335 }
5336 } else {
5337 // Found our variable index.
5338 break;
5339 }
5340 }
5341
5342 // If there are no variable indices, we must have a constant offset, just
5343 // evaluate it the general way.
5344 if (i == e) return 0;
5345
5346 Value *VariableIdx = GEP->getOperand(i);
5347 // Determine the scale factor of the variable element. For example, this is
5348 // 4 if the variable index is into an array of i32.
5349 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5350
5351 // Verify that there are no other variable indices. If so, emit the hard way.
5352 for (++i, ++GTI; i != e; ++i, ++GTI) {
5353 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5354 if (!CI) return 0;
5355
5356 // Compute the aggregate offset of constant indices.
5357 if (CI->isZero()) continue;
5358
5359 // Handle a struct index, which adds its field offset to the pointer.
5360 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5361 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5362 } else {
5363 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5364 Offset += Size*CI->getSExtValue();
5365 }
5366 }
5367
5368 // Okay, we know we have a single variable index, which must be a
5369 // pointer/array/vector index. If there is no offset, life is simple, return
5370 // the index.
5371 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5372 if (Offset == 0) {
5373 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5374 // we don't need to bother extending: the extension won't affect where the
5375 // computation crosses zero.
5376 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5377 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5378 VariableIdx->getNameStart(), &I);
5379 return VariableIdx;
5380 }
5381
5382 // Otherwise, there is an index. The computation we will do will be modulo
5383 // the pointer size, so get it.
5384 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5385
5386 Offset &= PtrSizeMask;
5387 VariableScale &= PtrSizeMask;
5388
5389 // To do this transformation, any constant index must be a multiple of the
5390 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5391 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5392 // multiple of the variable scale.
5393 int64_t NewOffs = Offset / (int64_t)VariableScale;
5394 if (Offset != NewOffs*(int64_t)VariableScale)
5395 return 0;
5396
5397 // Okay, we can do this evaluation. Start by converting the index to intptr.
5398 const Type *IntPtrTy = TD.getIntPtrType();
5399 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005400 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005401 true /*SExt*/,
5402 VariableIdx->getNameStart(), &I);
5403 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005404 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005405}
5406
5407
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005408/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5409/// else. At this point we know that the GEP is on the LHS of the comparison.
5410Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5411 ICmpInst::Predicate Cond,
5412 Instruction &I) {
5413 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5414
Chris Lattnereba75862008-04-22 02:53:33 +00005415 // Look through bitcasts.
5416 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5417 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005418
5419 Value *PtrBase = GEPLHS->getOperand(0);
5420 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005421 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005422 // This transformation (ignoring the base and scales) is valid because we
5423 // know pointers can't overflow. See if we can output an optimized form.
5424 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5425
5426 // If not, synthesize the offset the hard way.
5427 if (Offset == 0)
5428 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005429 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5430 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5432 // If the base pointers are different, but the indices are the same, just
5433 // compare the base pointer.
5434 if (PtrBase != GEPRHS->getOperand(0)) {
5435 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5436 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5437 GEPRHS->getOperand(0)->getType();
5438 if (IndicesTheSame)
5439 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5440 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5441 IndicesTheSame = false;
5442 break;
5443 }
5444
5445 // If all indices are the same, just compare the base pointers.
5446 if (IndicesTheSame)
5447 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5448 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5449
5450 // Otherwise, the base pointers are different and the indices are
5451 // different, bail out.
5452 return 0;
5453 }
5454
5455 // If one of the GEPs has all zero indices, recurse.
5456 bool AllZeros = true;
5457 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5458 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5459 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5460 AllZeros = false;
5461 break;
5462 }
5463 if (AllZeros)
5464 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5465 ICmpInst::getSwappedPredicate(Cond), I);
5466
5467 // If the other GEP has all zero indices, recurse.
5468 AllZeros = true;
5469 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5470 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5471 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5472 AllZeros = false;
5473 break;
5474 }
5475 if (AllZeros)
5476 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5477
5478 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5479 // If the GEPs only differ by one index, compare it.
5480 unsigned NumDifferences = 0; // Keep track of # differences.
5481 unsigned DiffOperand = 0; // The operand that differs.
5482 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5483 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5484 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5485 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5486 // Irreconcilable differences.
5487 NumDifferences = 2;
5488 break;
5489 } else {
5490 if (NumDifferences++) break;
5491 DiffOperand = i;
5492 }
5493 }
5494
5495 if (NumDifferences == 0) // SAME GEP?
5496 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005497 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005498 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005499
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005500 else if (NumDifferences == 1) {
5501 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5502 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5503 // Make sure we do a signed comparison here.
5504 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5505 }
5506 }
5507
5508 // Only lower this if the icmp is the only user of the GEP or if we expect
5509 // the result to fold to a constant!
5510 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5511 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5512 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5513 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5514 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5515 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5516 }
5517 }
5518 return 0;
5519}
5520
Chris Lattnere6b62d92008-05-19 20:18:56 +00005521/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5522///
5523Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5524 Instruction *LHSI,
5525 Constant *RHSC) {
5526 if (!isa<ConstantFP>(RHSC)) return 0;
5527 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5528
5529 // Get the width of the mantissa. We don't want to hack on conversions that
5530 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005531 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005532 if (MantissaWidth == -1) return 0; // Unknown.
5533
5534 // Check to see that the input is converted from an integer type that is small
5535 // enough that preserves all bits. TODO: check here for "known" sign bits.
5536 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5537 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5538
5539 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5540 if (isa<UIToFPInst>(LHSI))
5541 ++InputSize;
5542
5543 // If the conversion would lose info, don't hack on this.
5544 if ((int)InputSize > MantissaWidth)
5545 return 0;
5546
5547 // Otherwise, we can potentially simplify the comparison. We know that it
5548 // will always come through as an integer value and we know the constant is
5549 // not a NAN (it would have been previously simplified).
5550 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5551
5552 ICmpInst::Predicate Pred;
5553 switch (I.getPredicate()) {
5554 default: assert(0 && "Unexpected predicate!");
5555 case FCmpInst::FCMP_UEQ:
5556 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5557 case FCmpInst::FCMP_UGT:
5558 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5559 case FCmpInst::FCMP_UGE:
5560 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5561 case FCmpInst::FCMP_ULT:
5562 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5563 case FCmpInst::FCMP_ULE:
5564 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5565 case FCmpInst::FCMP_UNE:
5566 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5567 case FCmpInst::FCMP_ORD:
5568 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5569 case FCmpInst::FCMP_UNO:
5570 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5571 }
5572
5573 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5574
5575 // Now we know that the APFloat is a normal number, zero or inf.
5576
Chris Lattnerf13ff492008-05-20 03:50:52 +00005577 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005578 // comparing an i8 to 300.0.
5579 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5580
5581 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5582 // and large values.
5583 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5584 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5585 APFloat::rmNearestTiesToEven);
5586 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner82a80002008-05-24 04:06:28 +00005587 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5588 Pred == ICmpInst::ICMP_SLE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005589 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5590 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5591 }
5592
5593 // See if the RHS value is < SignedMin.
5594 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5595 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5596 APFloat::rmNearestTiesToEven);
5597 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner82a80002008-05-24 04:06:28 +00005598 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5599 Pred == ICmpInst::ICMP_SGE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005600 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5601 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5602 }
5603
5604 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5605 // it may still be fractional. See if it is fractional by casting the FP
5606 // value to the integer value and back, checking for equality. Don't do this
5607 // for zero, because -0.0 is not fractional.
5608 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5609 if (!RHS.isZero() &&
5610 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5611 // If we had a comparison against a fractional value, we have to adjust
5612 // the compare predicate and sometimes the value. RHSC is rounded towards
5613 // zero at this point.
5614 switch (Pred) {
5615 default: assert(0 && "Unexpected integer comparison!");
5616 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5617 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5618 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5619 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5620 case ICmpInst::ICMP_SLE:
5621 // (float)int <= 4.4 --> int <= 4
5622 // (float)int <= -4.4 --> int < -4
5623 if (RHS.isNegative())
5624 Pred = ICmpInst::ICMP_SLT;
5625 break;
5626 case ICmpInst::ICMP_SLT:
5627 // (float)int < -4.4 --> int < -4
5628 // (float)int < 4.4 --> int <= 4
5629 if (!RHS.isNegative())
5630 Pred = ICmpInst::ICMP_SLE;
5631 break;
5632 case ICmpInst::ICMP_SGT:
5633 // (float)int > 4.4 --> int > 4
5634 // (float)int > -4.4 --> int >= -4
5635 if (RHS.isNegative())
5636 Pred = ICmpInst::ICMP_SGE;
5637 break;
5638 case ICmpInst::ICMP_SGE:
5639 // (float)int >= -4.4 --> int >= -4
5640 // (float)int >= 4.4 --> int > 4
5641 if (!RHS.isNegative())
5642 Pred = ICmpInst::ICMP_SGT;
5643 break;
5644 }
5645 }
5646
5647 // Lower this FP comparison into an appropriate integer version of the
5648 // comparison.
5649 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5650}
5651
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005652Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5653 bool Changed = SimplifyCompare(I);
5654 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5655
5656 // Fold trivial predicates.
5657 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5658 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5659 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5660 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5661
5662 // Simplify 'fcmp pred X, X'
5663 if (Op0 == Op1) {
5664 switch (I.getPredicate()) {
5665 default: assert(0 && "Unknown predicate!");
5666 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5667 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5668 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5669 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5670 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5671 case FCmpInst::FCMP_OLT: // True if ordered and less than
5672 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5673 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5674
5675 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5676 case FCmpInst::FCMP_ULT: // True if unordered or less than
5677 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5678 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5679 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5680 I.setPredicate(FCmpInst::FCMP_UNO);
5681 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5682 return &I;
5683
5684 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5685 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5686 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5687 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5688 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5689 I.setPredicate(FCmpInst::FCMP_ORD);
5690 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5691 return &I;
5692 }
5693 }
5694
5695 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5696 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5697
5698 // Handle fcmp with constant RHS
5699 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005700 // If the constant is a nan, see if we can fold the comparison based on it.
5701 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5702 if (CFP->getValueAPF().isNaN()) {
5703 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5704 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005705 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5706 "Comparison must be either ordered or unordered!");
5707 // True if unordered.
5708 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005709 }
5710 }
5711
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005712 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5713 switch (LHSI->getOpcode()) {
5714 case Instruction::PHI:
5715 if (Instruction *NV = FoldOpIntoPhi(I))
5716 return NV;
5717 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005718 case Instruction::SIToFP:
5719 case Instruction::UIToFP:
5720 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5721 return NV;
5722 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005723 case Instruction::Select:
5724 // If either operand of the select is a constant, we can fold the
5725 // comparison into the select arms, which will cause one to be
5726 // constant folded and the select turned into a bitwise or.
5727 Value *Op1 = 0, *Op2 = 0;
5728 if (LHSI->hasOneUse()) {
5729 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5730 // Fold the known value into the constant operand.
5731 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5732 // Insert a new FCmp of the other select operand.
5733 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5734 LHSI->getOperand(2), RHSC,
5735 I.getName()), I);
5736 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5737 // Fold the known value into the constant operand.
5738 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5739 // Insert a new FCmp of the other select operand.
5740 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5741 LHSI->getOperand(1), RHSC,
5742 I.getName()), I);
5743 }
5744 }
5745
5746 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005747 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005748 break;
5749 }
5750 }
5751
5752 return Changed ? &I : 0;
5753}
5754
5755Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5756 bool Changed = SimplifyCompare(I);
5757 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5758 const Type *Ty = Op0->getType();
5759
5760 // icmp X, X
5761 if (Op0 == Op1)
5762 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005763 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005764
5765 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5766 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005767
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005768 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5769 // addresses never equal each other! We already know that Op0 != Op1.
5770 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5771 isa<ConstantPointerNull>(Op0)) &&
5772 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5773 isa<ConstantPointerNull>(Op1)))
5774 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005775 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005776
5777 // icmp's with boolean values can always be turned into bitwise operations
5778 if (Ty == Type::Int1Ty) {
5779 switch (I.getPredicate()) {
5780 default: assert(0 && "Invalid icmp instruction!");
5781 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005782 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005783 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005784 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005785 }
5786 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005787 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005788
5789 case ICmpInst::ICMP_UGT:
5790 case ICmpInst::ICMP_SGT:
5791 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5792 // FALL THROUGH
5793 case ICmpInst::ICMP_ULT:
5794 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005795 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005796 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005797 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005798 }
5799 case ICmpInst::ICMP_UGE:
5800 case ICmpInst::ICMP_SGE:
5801 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5802 // FALL THROUGH
5803 case ICmpInst::ICMP_ULE:
5804 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005805 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005806 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005807 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005808 }
5809 }
5810 }
5811
5812 // See if we are doing a comparison between a constant and an instruction that
5813 // can be folded into the comparison.
5814 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005815 Value *A, *B;
5816
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005817 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5818 if (I.isEquality() && CI->isNullValue() &&
5819 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5820 // (icmp cond A B) if cond is equality
5821 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005822 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005823
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005824 switch (I.getPredicate()) {
5825 default: break;
5826 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5827 if (CI->isMinValue(false))
5828 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5829 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5830 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5831 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5832 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5833 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5834 if (CI->isMinValue(true))
5835 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5836 ConstantInt::getAllOnesValue(Op0->getType()));
5837
5838 break;
5839
5840 case ICmpInst::ICMP_SLT:
5841 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5842 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5843 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5844 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5845 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5846 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5847 break;
5848
5849 case ICmpInst::ICMP_UGT:
5850 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5851 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5852 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5853 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5854 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5855 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5856
5857 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5858 if (CI->isMaxValue(true))
5859 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5860 ConstantInt::getNullValue(Op0->getType()));
5861 break;
5862
5863 case ICmpInst::ICMP_SGT:
5864 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5865 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5866 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5867 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5868 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5869 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5870 break;
5871
5872 case ICmpInst::ICMP_ULE:
5873 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5874 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5875 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5876 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5877 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5878 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5879 break;
5880
5881 case ICmpInst::ICMP_SLE:
5882 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5883 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5884 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5885 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5886 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5887 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5888 break;
5889
5890 case ICmpInst::ICMP_UGE:
5891 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5892 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5893 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5894 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5895 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5896 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5897 break;
5898
5899 case ICmpInst::ICMP_SGE:
5900 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5901 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5902 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5903 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5904 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5905 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5906 break;
5907 }
5908
5909 // If we still have a icmp le or icmp ge instruction, turn it into the
5910 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5911 // already been handled above, this requires little checking.
5912 //
5913 switch (I.getPredicate()) {
5914 default: break;
5915 case ICmpInst::ICMP_ULE:
5916 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5917 case ICmpInst::ICMP_SLE:
5918 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5919 case ICmpInst::ICMP_UGE:
5920 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5921 case ICmpInst::ICMP_SGE:
5922 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5923 }
5924
5925 // See if we can fold the comparison based on bits known to be zero or one
5926 // in the input. If this comparison is a normal comparison, it demands all
5927 // bits, if it is a sign bit comparison, it only demands the sign bit.
5928
5929 bool UnusedBit;
5930 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5931
5932 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5933 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5934 if (SimplifyDemandedBits(Op0,
5935 isSignBit ? APInt::getSignBit(BitWidth)
5936 : APInt::getAllOnesValue(BitWidth),
5937 KnownZero, KnownOne, 0))
5938 return &I;
5939
5940 // Given the known and unknown bits, compute a range that the LHS could be
5941 // in.
5942 if ((KnownOne | KnownZero) != 0) {
5943 // Compute the Min, Max and RHS values based on the known bits. For the
5944 // EQ and NE we use unsigned values.
5945 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5946 const APInt& RHSVal = CI->getValue();
5947 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5948 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5949 Max);
5950 } else {
5951 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5952 Max);
5953 }
5954 switch (I.getPredicate()) { // LE/GE have been folded already.
5955 default: assert(0 && "Unknown icmp opcode!");
5956 case ICmpInst::ICMP_EQ:
5957 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5959 break;
5960 case ICmpInst::ICMP_NE:
5961 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5962 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5963 break;
5964 case ICmpInst::ICMP_ULT:
5965 if (Max.ult(RHSVal))
5966 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5967 if (Min.uge(RHSVal))
5968 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5969 break;
5970 case ICmpInst::ICMP_UGT:
5971 if (Min.ugt(RHSVal))
5972 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5973 if (Max.ule(RHSVal))
5974 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5975 break;
5976 case ICmpInst::ICMP_SLT:
5977 if (Max.slt(RHSVal))
5978 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5979 if (Min.sgt(RHSVal))
5980 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5981 break;
5982 case ICmpInst::ICMP_SGT:
5983 if (Min.sgt(RHSVal))
5984 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5985 if (Max.sle(RHSVal))
5986 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5987 break;
5988 }
5989 }
5990
5991 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5992 // instruction, see if that instruction also has constants so that the
5993 // instruction can be folded into the icmp
5994 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5995 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5996 return Res;
5997 }
5998
5999 // Handle icmp with constant (but not simple integer constant) RHS
6000 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6001 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6002 switch (LHSI->getOpcode()) {
6003 case Instruction::GetElementPtr:
6004 if (RHSC->isNullValue()) {
6005 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6006 bool isAllZeros = true;
6007 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6008 if (!isa<Constant>(LHSI->getOperand(i)) ||
6009 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6010 isAllZeros = false;
6011 break;
6012 }
6013 if (isAllZeros)
6014 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6015 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6016 }
6017 break;
6018
6019 case Instruction::PHI:
6020 if (Instruction *NV = FoldOpIntoPhi(I))
6021 return NV;
6022 break;
6023 case Instruction::Select: {
6024 // If either operand of the select is a constant, we can fold the
6025 // comparison into the select arms, which will cause one to be
6026 // constant folded and the select turned into a bitwise or.
6027 Value *Op1 = 0, *Op2 = 0;
6028 if (LHSI->hasOneUse()) {
6029 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6030 // Fold the known value into the constant operand.
6031 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6032 // Insert a new ICmp of the other select operand.
6033 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6034 LHSI->getOperand(2), RHSC,
6035 I.getName()), I);
6036 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6037 // Fold the known value into the constant operand.
6038 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6039 // Insert a new ICmp of the other select operand.
6040 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6041 LHSI->getOperand(1), RHSC,
6042 I.getName()), I);
6043 }
6044 }
6045
6046 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006047 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006048 break;
6049 }
6050 case Instruction::Malloc:
6051 // If we have (malloc != null), and if the malloc has a single use, we
6052 // can assume it is successful and remove the malloc.
6053 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6054 AddToWorkList(LHSI);
6055 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006056 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006057 }
6058 break;
6059 }
6060 }
6061
6062 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6063 if (User *GEP = dyn_castGetElementPtr(Op0))
6064 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6065 return NI;
6066 if (User *GEP = dyn_castGetElementPtr(Op1))
6067 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6068 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6069 return NI;
6070
6071 // Test to see if the operands of the icmp are casted versions of other
6072 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6073 // now.
6074 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6075 if (isa<PointerType>(Op0->getType()) &&
6076 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6077 // We keep moving the cast from the left operand over to the right
6078 // operand, where it can often be eliminated completely.
6079 Op0 = CI->getOperand(0);
6080
6081 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6082 // so eliminate it as well.
6083 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6084 Op1 = CI2->getOperand(0);
6085
6086 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006087 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006088 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6089 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6090 } else {
6091 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006092 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006093 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006094 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006095 return new ICmpInst(I.getPredicate(), Op0, Op1);
6096 }
6097 }
6098
6099 if (isa<CastInst>(Op0)) {
6100 // Handle the special case of: icmp (cast bool to X), <cst>
6101 // This comes up when you have code like
6102 // int X = A < B;
6103 // if (X) ...
6104 // For generality, we handle any zero-extension of any operand comparison
6105 // with a constant or another cast from the same type.
6106 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6107 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6108 return R;
6109 }
6110
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006111 // ~x < ~y --> y < x
6112 { Value *A, *B;
6113 if (match(Op0, m_Not(m_Value(A))) &&
6114 match(Op1, m_Not(m_Value(B))))
6115 return new ICmpInst(I.getPredicate(), B, A);
6116 }
6117
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006118 if (I.isEquality()) {
6119 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006120
6121 // -x == -y --> x == y
6122 if (match(Op0, m_Neg(m_Value(A))) &&
6123 match(Op1, m_Neg(m_Value(B))))
6124 return new ICmpInst(I.getPredicate(), A, B);
6125
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006126 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6127 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6128 Value *OtherVal = A == Op1 ? B : A;
6129 return new ICmpInst(I.getPredicate(), OtherVal,
6130 Constant::getNullValue(A->getType()));
6131 }
6132
6133 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6134 // A^c1 == C^c2 --> A == C^(c1^c2)
6135 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6136 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6137 if (Op1->hasOneUse()) {
6138 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00006139 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006140 return new ICmpInst(I.getPredicate(), A,
6141 InsertNewInstBefore(Xor, I));
6142 }
6143
6144 // A^B == A^D -> B == D
6145 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6146 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6147 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6148 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6149 }
6150 }
6151
6152 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6153 (A == Op0 || B == Op0)) {
6154 // A == (A^B) -> B == 0
6155 Value *OtherVal = A == Op0 ? B : A;
6156 return new ICmpInst(I.getPredicate(), OtherVal,
6157 Constant::getNullValue(A->getType()));
6158 }
6159 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6160 // (A-B) == A -> B == 0
6161 return new ICmpInst(I.getPredicate(), B,
6162 Constant::getNullValue(B->getType()));
6163 }
6164 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6165 // A == (A-B) -> B == 0
6166 return new ICmpInst(I.getPredicate(), B,
6167 Constant::getNullValue(B->getType()));
6168 }
6169
6170 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6171 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6172 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6173 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6174 Value *X = 0, *Y = 0, *Z = 0;
6175
6176 if (A == C) {
6177 X = B; Y = D; Z = A;
6178 } else if (A == D) {
6179 X = B; Y = C; Z = A;
6180 } else if (B == C) {
6181 X = A; Y = D; Z = B;
6182 } else if (B == D) {
6183 X = A; Y = C; Z = B;
6184 }
6185
6186 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006187 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6188 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006189 I.setOperand(0, Op1);
6190 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6191 return &I;
6192 }
6193 }
6194 }
6195 return Changed ? &I : 0;
6196}
6197
6198
6199/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6200/// and CmpRHS are both known to be integer constants.
6201Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6202 ConstantInt *DivRHS) {
6203 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6204 const APInt &CmpRHSV = CmpRHS->getValue();
6205
6206 // FIXME: If the operand types don't match the type of the divide
6207 // then don't attempt this transform. The code below doesn't have the
6208 // logic to deal with a signed divide and an unsigned compare (and
6209 // vice versa). This is because (x /s C1) <s C2 produces different
6210 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6211 // (x /u C1) <u C2. Simply casting the operands and result won't
6212 // work. :( The if statement below tests that condition and bails
6213 // if it finds it.
6214 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6215 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6216 return 0;
6217 if (DivRHS->isZero())
6218 return 0; // The ProdOV computation fails on divide by zero.
6219
6220 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6221 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6222 // C2 (CI). By solving for X we can turn this into a range check
6223 // instead of computing a divide.
6224 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6225
6226 // Determine if the product overflows by seeing if the product is
6227 // not equal to the divide. Make sure we do the same kind of divide
6228 // as in the LHS instruction that we're folding.
6229 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6230 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6231
6232 // Get the ICmp opcode
6233 ICmpInst::Predicate Pred = ICI.getPredicate();
6234
6235 // Figure out the interval that is being checked. For example, a comparison
6236 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6237 // Compute this interval based on the constants involved and the signedness of
6238 // the compare/divide. This computes a half-open interval, keeping track of
6239 // whether either value in the interval overflows. After analysis each
6240 // overflow variable is set to 0 if it's corresponding bound variable is valid
6241 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6242 int LoOverflow = 0, HiOverflow = 0;
6243 ConstantInt *LoBound = 0, *HiBound = 0;
6244
6245
6246 if (!DivIsSigned) { // udiv
6247 // e.g. X/5 op 3 --> [15, 20)
6248 LoBound = Prod;
6249 HiOverflow = LoOverflow = ProdOV;
6250 if (!HiOverflow)
6251 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006252 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006253 if (CmpRHSV == 0) { // (X / pos) op 0
6254 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6255 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6256 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006257 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006258 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6259 HiOverflow = LoOverflow = ProdOV;
6260 if (!HiOverflow)
6261 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6262 } else { // (X / pos) op neg
6263 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6264 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6265 LoOverflow = AddWithOverflow(LoBound, Prod,
6266 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
6267 HiBound = AddOne(Prod);
6268 HiOverflow = ProdOV ? -1 : 0;
6269 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006270 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006271 if (CmpRHSV == 0) { // (X / neg) op 0
6272 // e.g. X/-5 op 0 --> [-4, 5)
6273 LoBound = AddOne(DivRHS);
6274 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6275 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6276 HiOverflow = 1; // [INTMIN+1, overflow)
6277 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6278 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006279 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006280 // e.g. X/-5 op 3 --> [-19, -14)
6281 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6282 if (!LoOverflow)
6283 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6284 HiBound = AddOne(Prod);
6285 } else { // (X / neg) op neg
6286 // e.g. X/-5 op -3 --> [15, 20)
6287 LoBound = Prod;
6288 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6289 HiBound = Subtract(Prod, DivRHS);
6290 }
6291
6292 // Dividing by a negative swaps the condition. LT <-> GT
6293 Pred = ICmpInst::getSwappedPredicate(Pred);
6294 }
6295
6296 Value *X = DivI->getOperand(0);
6297 switch (Pred) {
6298 default: assert(0 && "Unhandled icmp opcode!");
6299 case ICmpInst::ICMP_EQ:
6300 if (LoOverflow && HiOverflow)
6301 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6302 else if (HiOverflow)
6303 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6304 ICmpInst::ICMP_UGE, X, LoBound);
6305 else if (LoOverflow)
6306 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6307 ICmpInst::ICMP_ULT, X, HiBound);
6308 else
6309 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6310 case ICmpInst::ICMP_NE:
6311 if (LoOverflow && HiOverflow)
6312 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6313 else if (HiOverflow)
6314 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6315 ICmpInst::ICMP_ULT, X, LoBound);
6316 else if (LoOverflow)
6317 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6318 ICmpInst::ICMP_UGE, X, HiBound);
6319 else
6320 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6321 case ICmpInst::ICMP_ULT:
6322 case ICmpInst::ICMP_SLT:
6323 if (LoOverflow == +1) // Low bound is greater than input range.
6324 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6325 if (LoOverflow == -1) // Low bound is less than input range.
6326 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6327 return new ICmpInst(Pred, X, LoBound);
6328 case ICmpInst::ICMP_UGT:
6329 case ICmpInst::ICMP_SGT:
6330 if (HiOverflow == +1) // High bound greater than input range.
6331 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6332 else if (HiOverflow == -1) // High bound less than input range.
6333 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6334 if (Pred == ICmpInst::ICMP_UGT)
6335 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6336 else
6337 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6338 }
6339}
6340
6341
6342/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6343///
6344Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6345 Instruction *LHSI,
6346 ConstantInt *RHS) {
6347 const APInt &RHSV = RHS->getValue();
6348
6349 switch (LHSI->getOpcode()) {
6350 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6351 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6352 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6353 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006354 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6355 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006356 Value *CompareVal = LHSI->getOperand(0);
6357
6358 // If the sign bit of the XorCST is not set, there is no change to
6359 // the operation, just stop using the Xor.
6360 if (!XorCST->getValue().isNegative()) {
6361 ICI.setOperand(0, CompareVal);
6362 AddToWorkList(LHSI);
6363 return &ICI;
6364 }
6365
6366 // Was the old condition true if the operand is positive?
6367 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6368
6369 // If so, the new one isn't.
6370 isTrueIfPositive ^= true;
6371
6372 if (isTrueIfPositive)
6373 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6374 else
6375 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6376 }
6377 }
6378 break;
6379 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6380 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6381 LHSI->getOperand(0)->hasOneUse()) {
6382 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6383
6384 // If the LHS is an AND of a truncating cast, we can widen the
6385 // and/compare to be the input width without changing the value
6386 // produced, eliminating a cast.
6387 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6388 // We can do this transformation if either the AND constant does not
6389 // have its sign bit set or if it is an equality comparison.
6390 // Extending a relational comparison when we're checking the sign
6391 // bit would not work.
6392 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006393 (ICI.isEquality() ||
6394 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006395 uint32_t BitWidth =
6396 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6397 APInt NewCST = AndCST->getValue();
6398 NewCST.zext(BitWidth);
6399 APInt NewCI = RHSV;
6400 NewCI.zext(BitWidth);
6401 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006402 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006403 ConstantInt::get(NewCST),LHSI->getName());
6404 InsertNewInstBefore(NewAnd, ICI);
6405 return new ICmpInst(ICI.getPredicate(), NewAnd,
6406 ConstantInt::get(NewCI));
6407 }
6408 }
6409
6410 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6411 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6412 // happens a LOT in code produced by the C front-end, for bitfield
6413 // access.
6414 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6415 if (Shift && !Shift->isShift())
6416 Shift = 0;
6417
6418 ConstantInt *ShAmt;
6419 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6420 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6421 const Type *AndTy = AndCST->getType(); // Type of the and.
6422
6423 // We can fold this as long as we can't shift unknown bits
6424 // into the mask. This can only happen with signed shift
6425 // rights, as they sign-extend.
6426 if (ShAmt) {
6427 bool CanFold = Shift->isLogicalShift();
6428 if (!CanFold) {
6429 // To test for the bad case of the signed shr, see if any
6430 // of the bits shifted in could be tested after the mask.
6431 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6432 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6433
6434 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6435 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6436 AndCST->getValue()) == 0)
6437 CanFold = true;
6438 }
6439
6440 if (CanFold) {
6441 Constant *NewCst;
6442 if (Shift->getOpcode() == Instruction::Shl)
6443 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6444 else
6445 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6446
6447 // Check to see if we are shifting out any of the bits being
6448 // compared.
6449 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6450 // If we shifted bits out, the fold is not going to work out.
6451 // As a special case, check to see if this means that the
6452 // result is always true or false now.
6453 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6454 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6455 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6456 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6457 } else {
6458 ICI.setOperand(1, NewCst);
6459 Constant *NewAndCST;
6460 if (Shift->getOpcode() == Instruction::Shl)
6461 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6462 else
6463 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6464 LHSI->setOperand(1, NewAndCST);
6465 LHSI->setOperand(0, Shift->getOperand(0));
6466 AddToWorkList(Shift); // Shift is dead.
6467 AddUsesToWorkList(ICI);
6468 return &ICI;
6469 }
6470 }
6471 }
6472
6473 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6474 // preferable because it allows the C<<Y expression to be hoisted out
6475 // of a loop if Y is invariant and X is not.
6476 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6477 ICI.isEquality() && !Shift->isArithmeticShift() &&
6478 isa<Instruction>(Shift->getOperand(0))) {
6479 // Compute C << Y.
6480 Value *NS;
6481 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006482 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006483 Shift->getOperand(1), "tmp");
6484 } else {
6485 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006486 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006487 Shift->getOperand(1), "tmp");
6488 }
6489 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6490
6491 // Compute X & (C << Y).
6492 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006493 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006494 InsertNewInstBefore(NewAnd, ICI);
6495
6496 ICI.setOperand(0, NewAnd);
6497 return &ICI;
6498 }
6499 }
6500 break;
6501
6502 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6503 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6504 if (!ShAmt) break;
6505
6506 uint32_t TypeBits = RHSV.getBitWidth();
6507
6508 // Check that the shift amount is in range. If not, don't perform
6509 // undefined shifts. When the shift is visited it will be
6510 // simplified.
6511 if (ShAmt->uge(TypeBits))
6512 break;
6513
6514 if (ICI.isEquality()) {
6515 // If we are comparing against bits always shifted out, the
6516 // comparison cannot succeed.
6517 Constant *Comp =
6518 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6519 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6520 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6521 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6522 return ReplaceInstUsesWith(ICI, Cst);
6523 }
6524
6525 if (LHSI->hasOneUse()) {
6526 // Otherwise strength reduce the shift into an and.
6527 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6528 Constant *Mask =
6529 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6530
6531 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006532 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006533 Mask, LHSI->getName()+".mask");
6534 Value *And = InsertNewInstBefore(AndI, ICI);
6535 return new ICmpInst(ICI.getPredicate(), And,
6536 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6537 }
6538 }
6539
6540 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6541 bool TrueIfSigned = false;
6542 if (LHSI->hasOneUse() &&
6543 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6544 // (X << 31) <s 0 --> (X&1) != 0
6545 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6546 (TypeBits-ShAmt->getZExtValue()-1));
6547 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006548 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006549 Mask, LHSI->getName()+".mask");
6550 Value *And = InsertNewInstBefore(AndI, ICI);
6551
6552 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6553 And, Constant::getNullValue(And->getType()));
6554 }
6555 break;
6556 }
6557
6558 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6559 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006560 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006561 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006562 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006563
Chris Lattner5ee84f82008-03-21 05:19:58 +00006564 // Check that the shift amount is in range. If not, don't perform
6565 // undefined shifts. When the shift is visited it will be
6566 // simplified.
6567 uint32_t TypeBits = RHSV.getBitWidth();
6568 if (ShAmt->uge(TypeBits))
6569 break;
6570
6571 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006572
Chris Lattner5ee84f82008-03-21 05:19:58 +00006573 // If we are comparing against bits always shifted out, the
6574 // comparison cannot succeed.
6575 APInt Comp = RHSV << ShAmtVal;
6576 if (LHSI->getOpcode() == Instruction::LShr)
6577 Comp = Comp.lshr(ShAmtVal);
6578 else
6579 Comp = Comp.ashr(ShAmtVal);
6580
6581 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6582 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6583 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6584 return ReplaceInstUsesWith(ICI, Cst);
6585 }
6586
6587 // Otherwise, check to see if the bits shifted out are known to be zero.
6588 // If so, we can compare against the unshifted value:
6589 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006590 if (LHSI->hasOneUse() &&
6591 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006592 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6593 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6594 ConstantExpr::getShl(RHS, ShAmt));
6595 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006596
Evan Chengfb9292a2008-04-23 00:38:06 +00006597 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006598 // Otherwise strength reduce the shift into an and.
6599 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6600 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006601
Chris Lattner5ee84f82008-03-21 05:19:58 +00006602 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006603 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006604 Mask, LHSI->getName()+".mask");
6605 Value *And = InsertNewInstBefore(AndI, ICI);
6606 return new ICmpInst(ICI.getPredicate(), And,
6607 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006608 }
6609 break;
6610 }
6611
6612 case Instruction::SDiv:
6613 case Instruction::UDiv:
6614 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6615 // Fold this div into the comparison, producing a range check.
6616 // Determine, based on the divide type, what the range is being
6617 // checked. If there is an overflow on the low or high side, remember
6618 // it, otherwise compute the range [low, hi) bounding the new value.
6619 // See: InsertRangeTest above for the kinds of replacements possible.
6620 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6621 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6622 DivRHS))
6623 return R;
6624 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006625
6626 case Instruction::Add:
6627 // Fold: icmp pred (add, X, C1), C2
6628
6629 if (!ICI.isEquality()) {
6630 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6631 if (!LHSC) break;
6632 const APInt &LHSV = LHSC->getValue();
6633
6634 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6635 .subtract(LHSV);
6636
6637 if (ICI.isSignedPredicate()) {
6638 if (CR.getLower().isSignBit()) {
6639 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6640 ConstantInt::get(CR.getUpper()));
6641 } else if (CR.getUpper().isSignBit()) {
6642 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6643 ConstantInt::get(CR.getLower()));
6644 }
6645 } else {
6646 if (CR.getLower().isMinValue()) {
6647 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6648 ConstantInt::get(CR.getUpper()));
6649 } else if (CR.getUpper().isMinValue()) {
6650 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6651 ConstantInt::get(CR.getLower()));
6652 }
6653 }
6654 }
6655 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006656 }
6657
6658 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6659 if (ICI.isEquality()) {
6660 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6661
6662 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6663 // the second operand is a constant, simplify a bit.
6664 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6665 switch (BO->getOpcode()) {
6666 case Instruction::SRem:
6667 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6668 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6669 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6670 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6671 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006672 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006673 BO->getName());
6674 InsertNewInstBefore(NewRem, ICI);
6675 return new ICmpInst(ICI.getPredicate(), NewRem,
6676 Constant::getNullValue(BO->getType()));
6677 }
6678 }
6679 break;
6680 case Instruction::Add:
6681 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6682 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6683 if (BO->hasOneUse())
6684 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6685 Subtract(RHS, BOp1C));
6686 } else if (RHSV == 0) {
6687 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6688 // efficiently invertible, or if the add has just this one use.
6689 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6690
6691 if (Value *NegVal = dyn_castNegVal(BOp1))
6692 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6693 else if (Value *NegVal = dyn_castNegVal(BOp0))
6694 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6695 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006696 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006697 InsertNewInstBefore(Neg, ICI);
6698 Neg->takeName(BO);
6699 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6700 }
6701 }
6702 break;
6703 case Instruction::Xor:
6704 // For the xor case, we can xor two constants together, eliminating
6705 // the explicit xor.
6706 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6707 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6708 ConstantExpr::getXor(RHS, BOC));
6709
6710 // FALLTHROUGH
6711 case Instruction::Sub:
6712 // Replace (([sub|xor] A, B) != 0) with (A != B)
6713 if (RHSV == 0)
6714 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6715 BO->getOperand(1));
6716 break;
6717
6718 case Instruction::Or:
6719 // If bits are being or'd in that are not present in the constant we
6720 // are comparing against, then the comparison could never succeed!
6721 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6722 Constant *NotCI = ConstantExpr::getNot(RHS);
6723 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6724 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6725 isICMP_NE));
6726 }
6727 break;
6728
6729 case Instruction::And:
6730 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6731 // If bits are being compared against that are and'd out, then the
6732 // comparison can never succeed!
6733 if ((RHSV & ~BOC->getValue()) != 0)
6734 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6735 isICMP_NE));
6736
6737 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6738 if (RHS == BOC && RHSV.isPowerOf2())
6739 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6740 ICmpInst::ICMP_NE, LHSI,
6741 Constant::getNullValue(RHS->getType()));
6742
6743 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6744 if (isSignBit(BOC)) {
6745 Value *X = BO->getOperand(0);
6746 Constant *Zero = Constant::getNullValue(X->getType());
6747 ICmpInst::Predicate pred = isICMP_NE ?
6748 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6749 return new ICmpInst(pred, X, Zero);
6750 }
6751
6752 // ((X & ~7) == 0) --> X < 8
6753 if (RHSV == 0 && isHighOnes(BOC)) {
6754 Value *X = BO->getOperand(0);
6755 Constant *NegX = ConstantExpr::getNeg(BOC);
6756 ICmpInst::Predicate pred = isICMP_NE ?
6757 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6758 return new ICmpInst(pred, X, NegX);
6759 }
6760 }
6761 default: break;
6762 }
6763 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6764 // Handle icmp {eq|ne} <intrinsic>, intcst.
6765 if (II->getIntrinsicID() == Intrinsic::bswap) {
6766 AddToWorkList(II);
6767 ICI.setOperand(0, II->getOperand(1));
6768 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6769 return &ICI;
6770 }
6771 }
6772 } else { // Not a ICMP_EQ/ICMP_NE
6773 // If the LHS is a cast from an integral value of the same size,
6774 // then since we know the RHS is a constant, try to simlify.
6775 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6776 Value *CastOp = Cast->getOperand(0);
6777 const Type *SrcTy = CastOp->getType();
6778 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6779 if (SrcTy->isInteger() &&
6780 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6781 // If this is an unsigned comparison, try to make the comparison use
6782 // smaller constant values.
6783 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6784 // X u< 128 => X s> -1
6785 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6786 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6787 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6788 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6789 // X u> 127 => X s< 0
6790 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6791 Constant::getNullValue(SrcTy));
6792 }
6793 }
6794 }
6795 }
6796 return 0;
6797}
6798
6799/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6800/// We only handle extending casts so far.
6801///
6802Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6803 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6804 Value *LHSCIOp = LHSCI->getOperand(0);
6805 const Type *SrcTy = LHSCIOp->getType();
6806 const Type *DestTy = LHSCI->getType();
6807 Value *RHSCIOp;
6808
6809 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6810 // integer type is the same size as the pointer type.
6811 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6812 getTargetData().getPointerSizeInBits() ==
6813 cast<IntegerType>(DestTy)->getBitWidth()) {
6814 Value *RHSOp = 0;
6815 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6816 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6817 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6818 RHSOp = RHSC->getOperand(0);
6819 // If the pointer types don't match, insert a bitcast.
6820 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006821 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006822 }
6823
6824 if (RHSOp)
6825 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6826 }
6827
6828 // The code below only handles extension cast instructions, so far.
6829 // Enforce this.
6830 if (LHSCI->getOpcode() != Instruction::ZExt &&
6831 LHSCI->getOpcode() != Instruction::SExt)
6832 return 0;
6833
6834 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6835 bool isSignedCmp = ICI.isSignedPredicate();
6836
6837 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6838 // Not an extension from the same type?
6839 RHSCIOp = CI->getOperand(0);
6840 if (RHSCIOp->getType() != LHSCIOp->getType())
6841 return 0;
6842
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006843 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006844 // and the other is a zext), then we can't handle this.
6845 if (CI->getOpcode() != LHSCI->getOpcode())
6846 return 0;
6847
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006848 // Deal with equality cases early.
6849 if (ICI.isEquality())
6850 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6851
6852 // A signed comparison of sign extended values simplifies into a
6853 // signed comparison.
6854 if (isSignedCmp && isSignedExt)
6855 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6856
6857 // The other three cases all fold into an unsigned comparison.
6858 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006859 }
6860
6861 // If we aren't dealing with a constant on the RHS, exit early
6862 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6863 if (!CI)
6864 return 0;
6865
6866 // Compute the constant that would happen if we truncated to SrcTy then
6867 // reextended to DestTy.
6868 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6869 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6870
6871 // If the re-extended constant didn't change...
6872 if (Res2 == CI) {
6873 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6874 // For example, we might have:
6875 // %A = sext short %X to uint
6876 // %B = icmp ugt uint %A, 1330
6877 // It is incorrect to transform this into
6878 // %B = icmp ugt short %X, 1330
6879 // because %A may have negative value.
6880 //
6881 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6882 // OR operation is EQ/NE.
6883 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6884 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6885 else
6886 return 0;
6887 }
6888
6889 // The re-extended constant changed so the constant cannot be represented
6890 // in the shorter type. Consequently, we cannot emit a simple comparison.
6891
6892 // First, handle some easy cases. We know the result cannot be equal at this
6893 // point so handle the ICI.isEquality() cases
6894 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6895 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6896 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6897 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6898
6899 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6900 // should have been folded away previously and not enter in here.
6901 Value *Result;
6902 if (isSignedCmp) {
6903 // We're performing a signed comparison.
6904 if (cast<ConstantInt>(CI)->getValue().isNegative())
6905 Result = ConstantInt::getFalse(); // X < (small) --> false
6906 else
6907 Result = ConstantInt::getTrue(); // X < (large) --> true
6908 } else {
6909 // We're performing an unsigned comparison.
6910 if (isSignedExt) {
6911 // We're performing an unsigned comp with a sign extended value.
6912 // This is true if the input is >= 0. [aka >s -1]
6913 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6914 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6915 NegOne, ICI.getName()), ICI);
6916 } else {
6917 // Unsigned extend & unsigned compare -> always true.
6918 Result = ConstantInt::getTrue();
6919 }
6920 }
6921
6922 // Finally, return the value computed.
6923 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6924 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6925 return ReplaceInstUsesWith(ICI, Result);
6926 } else {
6927 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6928 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6929 "ICmp should be folded!");
6930 if (Constant *CI = dyn_cast<Constant>(Result))
6931 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6932 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006933 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006934 }
6935}
6936
6937Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6938 return commonShiftTransforms(I);
6939}
6940
6941Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6942 return commonShiftTransforms(I);
6943}
6944
6945Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006946 if (Instruction *R = commonShiftTransforms(I))
6947 return R;
6948
6949 Value *Op0 = I.getOperand(0);
6950
6951 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6952 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6953 if (CSI->isAllOnesValue())
6954 return ReplaceInstUsesWith(I, CSI);
6955
6956 // See if we can turn a signed shr into an unsigned shr.
6957 if (MaskedValueIsZero(Op0,
6958 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006959 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006960
6961 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006962}
6963
6964Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6965 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6967
6968 // shl X, 0 == X and shr X, 0 == X
6969 // shl 0, X == 0 and shr 0, X == 0
6970 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6971 Op0 == Constant::getNullValue(Op0->getType()))
6972 return ReplaceInstUsesWith(I, Op0);
6973
6974 if (isa<UndefValue>(Op0)) {
6975 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6976 return ReplaceInstUsesWith(I, Op0);
6977 else // undef << X -> 0, undef >>u X -> 0
6978 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6979 }
6980 if (isa<UndefValue>(Op1)) {
6981 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6982 return ReplaceInstUsesWith(I, Op0);
6983 else // X << undef, X >>u undef -> 0
6984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6985 }
6986
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006987 // Try to fold constant and into select arguments.
6988 if (isa<Constant>(Op0))
6989 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6990 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6991 return R;
6992
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006993 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6994 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6995 return Res;
6996 return 0;
6997}
6998
6999Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7000 BinaryOperator &I) {
7001 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7002
7003 // See if we can simplify any instructions used by the instruction whose sole
7004 // purpose is to compute bits we don't care about.
7005 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7006 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
7007 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
7008 KnownZero, KnownOne))
7009 return &I;
7010
7011 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7012 // of a signed value.
7013 //
7014 if (Op1->uge(TypeBits)) {
7015 if (I.getOpcode() != Instruction::AShr)
7016 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7017 else {
7018 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7019 return &I;
7020 }
7021 }
7022
7023 // ((X*C1) << C2) == (X * (C1 << C2))
7024 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7025 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7026 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007027 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007028 ConstantExpr::getShl(BOOp, Op1));
7029
7030 // Try to fold constant and into select arguments.
7031 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7032 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7033 return R;
7034 if (isa<PHINode>(Op0))
7035 if (Instruction *NV = FoldOpIntoPhi(I))
7036 return NV;
7037
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007038 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7039 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7040 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7041 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7042 // place. Don't try to do this transformation in this case. Also, we
7043 // require that the input operand is a shift-by-constant so that we have
7044 // confidence that the shifts will get folded together. We could do this
7045 // xform in more cases, but it is unlikely to be profitable.
7046 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7047 isa<ConstantInt>(TrOp->getOperand(1))) {
7048 // Okay, we'll do this xform. Make the shift of shift.
7049 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007050 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007051 I.getName());
7052 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7053
7054 // For logical shifts, the truncation has the effect of making the high
7055 // part of the register be zeros. Emulate this by inserting an AND to
7056 // clear the top bits as needed. This 'and' will usually be zapped by
7057 // other xforms later if dead.
7058 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7059 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7060 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7061
7062 // The mask we constructed says what the trunc would do if occurring
7063 // between the shifts. We want to know the effect *after* the second
7064 // shift. We know that it is a logical shift by a constant, so adjust the
7065 // mask as appropriate.
7066 if (I.getOpcode() == Instruction::Shl)
7067 MaskV <<= Op1->getZExtValue();
7068 else {
7069 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7070 MaskV = MaskV.lshr(Op1->getZExtValue());
7071 }
7072
Gabor Greifa645dd32008-05-16 19:29:10 +00007073 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007074 TI->getName());
7075 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7076
7077 // Return the value truncated to the interesting size.
7078 return new TruncInst(And, I.getType());
7079 }
7080 }
7081
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007082 if (Op0->hasOneUse()) {
7083 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7084 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7085 Value *V1, *V2;
7086 ConstantInt *CC;
7087 switch (Op0BO->getOpcode()) {
7088 default: break;
7089 case Instruction::Add:
7090 case Instruction::And:
7091 case Instruction::Or:
7092 case Instruction::Xor: {
7093 // These operators commute.
7094 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7095 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7096 match(Op0BO->getOperand(1),
7097 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007098 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007099 Op0BO->getOperand(0), Op1,
7100 Op0BO->getName());
7101 InsertNewInstBefore(YS, I); // (Y << C)
7102 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007103 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007104 Op0BO->getOperand(1)->getName());
7105 InsertNewInstBefore(X, I); // (X + (Y << C))
7106 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007107 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007108 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7109 }
7110
7111 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7112 Value *Op0BOOp1 = Op0BO->getOperand(1);
7113 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7114 match(Op0BOOp1,
7115 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
7116 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7117 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007118 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007119 Op0BO->getOperand(0), Op1,
7120 Op0BO->getName());
7121 InsertNewInstBefore(YS, I); // (Y << C)
7122 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007123 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007124 V1->getName()+".mask");
7125 InsertNewInstBefore(XM, I); // X & (CC << C)
7126
Gabor Greifa645dd32008-05-16 19:29:10 +00007127 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007128 }
7129 }
7130
7131 // FALL THROUGH.
7132 case Instruction::Sub: {
7133 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7134 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7135 match(Op0BO->getOperand(0),
7136 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007137 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007138 Op0BO->getOperand(1), Op1,
7139 Op0BO->getName());
7140 InsertNewInstBefore(YS, I); // (Y << C)
7141 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007142 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143 Op0BO->getOperand(0)->getName());
7144 InsertNewInstBefore(X, I); // (X + (Y << C))
7145 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007146 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7148 }
7149
7150 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7151 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7152 match(Op0BO->getOperand(0),
7153 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7154 m_ConstantInt(CC))) && V2 == Op1 &&
7155 cast<BinaryOperator>(Op0BO->getOperand(0))
7156 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007157 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 Op0BO->getOperand(1), Op1,
7159 Op0BO->getName());
7160 InsertNewInstBefore(YS, I); // (Y << C)
7161 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007162 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007163 V1->getName()+".mask");
7164 InsertNewInstBefore(XM, I); // X & (CC << C)
7165
Gabor Greifa645dd32008-05-16 19:29:10 +00007166 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007167 }
7168
7169 break;
7170 }
7171 }
7172
7173
7174 // If the operand is an bitwise operator with a constant RHS, and the
7175 // shift is the only use, we can pull it out of the shift.
7176 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7177 bool isValid = true; // Valid only for And, Or, Xor
7178 bool highBitSet = false; // Transform if high bit of constant set?
7179
7180 switch (Op0BO->getOpcode()) {
7181 default: isValid = false; break; // Do not perform transform!
7182 case Instruction::Add:
7183 isValid = isLeftShift;
7184 break;
7185 case Instruction::Or:
7186 case Instruction::Xor:
7187 highBitSet = false;
7188 break;
7189 case Instruction::And:
7190 highBitSet = true;
7191 break;
7192 }
7193
7194 // If this is a signed shift right, and the high bit is modified
7195 // by the logical operation, do not perform the transformation.
7196 // The highBitSet boolean indicates the value of the high bit of
7197 // the constant which would cause it to be modified for this
7198 // operation.
7199 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007200 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007201 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007202
7203 if (isValid) {
7204 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7205
7206 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007207 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007208 InsertNewInstBefore(NewShift, I);
7209 NewShift->takeName(Op0BO);
7210
Gabor Greifa645dd32008-05-16 19:29:10 +00007211 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007212 NewRHS);
7213 }
7214 }
7215 }
7216 }
7217
7218 // Find out if this is a shift of a shift by a constant.
7219 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7220 if (ShiftOp && !ShiftOp->isShift())
7221 ShiftOp = 0;
7222
7223 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7224 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7225 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7226 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7227 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7228 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7229 Value *X = ShiftOp->getOperand(0);
7230
7231 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7232 if (AmtSum > TypeBits)
7233 AmtSum = TypeBits;
7234
7235 const IntegerType *Ty = cast<IntegerType>(I.getType());
7236
7237 // Check for (X << c1) << c2 and (X >> c1) >> c2
7238 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007239 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007240 ConstantInt::get(Ty, AmtSum));
7241 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7242 I.getOpcode() == Instruction::AShr) {
7243 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00007244 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007245 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7246 I.getOpcode() == Instruction::LShr) {
7247 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7248 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007249 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007250 InsertNewInstBefore(Shift, I);
7251
7252 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007253 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007254 }
7255
7256 // Okay, if we get here, one shift must be left, and the other shift must be
7257 // right. See if the amounts are equal.
7258 if (ShiftAmt1 == ShiftAmt2) {
7259 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7260 if (I.getOpcode() == Instruction::Shl) {
7261 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007262 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007263 }
7264 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7265 if (I.getOpcode() == Instruction::LShr) {
7266 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007267 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007268 }
7269 // We can simplify ((X << C) >>s C) into a trunc + sext.
7270 // NOTE: we could do this for any C, but that would make 'unusual' integer
7271 // types. For now, just stick to ones well-supported by the code
7272 // generators.
7273 const Type *SExtType = 0;
7274 switch (Ty->getBitWidth() - ShiftAmt1) {
7275 case 1 :
7276 case 8 :
7277 case 16 :
7278 case 32 :
7279 case 64 :
7280 case 128:
7281 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7282 break;
7283 default: break;
7284 }
7285 if (SExtType) {
7286 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7287 InsertNewInstBefore(NewTrunc, I);
7288 return new SExtInst(NewTrunc, Ty);
7289 }
7290 // Otherwise, we can't handle it yet.
7291 } else if (ShiftAmt1 < ShiftAmt2) {
7292 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7293
7294 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7295 if (I.getOpcode() == Instruction::Shl) {
7296 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7297 ShiftOp->getOpcode() == Instruction::AShr);
7298 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007299 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007300 InsertNewInstBefore(Shift, I);
7301
7302 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007303 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007304 }
7305
7306 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7307 if (I.getOpcode() == Instruction::LShr) {
7308 assert(ShiftOp->getOpcode() == Instruction::Shl);
7309 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007310 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007311 InsertNewInstBefore(Shift, I);
7312
7313 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007314 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007315 }
7316
7317 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7318 } else {
7319 assert(ShiftAmt2 < ShiftAmt1);
7320 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7321
7322 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7323 if (I.getOpcode() == Instruction::Shl) {
7324 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7325 ShiftOp->getOpcode() == Instruction::AShr);
7326 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007327 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007328 ConstantInt::get(Ty, ShiftDiff));
7329 InsertNewInstBefore(Shift, I);
7330
7331 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007332 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007333 }
7334
7335 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7336 if (I.getOpcode() == Instruction::LShr) {
7337 assert(ShiftOp->getOpcode() == Instruction::Shl);
7338 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007339 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007340 InsertNewInstBefore(Shift, I);
7341
7342 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007343 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007344 }
7345
7346 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7347 }
7348 }
7349 return 0;
7350}
7351
7352
7353/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7354/// expression. If so, decompose it, returning some value X, such that Val is
7355/// X*Scale+Offset.
7356///
7357static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7358 int &Offset) {
7359 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7360 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7361 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007362 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007363 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007364 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7365 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7366 if (I->getOpcode() == Instruction::Shl) {
7367 // This is a value scaled by '1 << the shift amt'.
7368 Scale = 1U << RHS->getZExtValue();
7369 Offset = 0;
7370 return I->getOperand(0);
7371 } else if (I->getOpcode() == Instruction::Mul) {
7372 // This value is scaled by 'RHS'.
7373 Scale = RHS->getZExtValue();
7374 Offset = 0;
7375 return I->getOperand(0);
7376 } else if (I->getOpcode() == Instruction::Add) {
7377 // We have X+C. Check to see if we really have (X*C2)+C1,
7378 // where C1 is divisible by C2.
7379 unsigned SubScale;
7380 Value *SubVal =
7381 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7382 Offset += RHS->getZExtValue();
7383 Scale = SubScale;
7384 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007385 }
7386 }
7387 }
7388
7389 // Otherwise, we can't look past this.
7390 Scale = 1;
7391 Offset = 0;
7392 return Val;
7393}
7394
7395
7396/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7397/// try to eliminate the cast by moving the type information into the alloc.
7398Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7399 AllocationInst &AI) {
7400 const PointerType *PTy = cast<PointerType>(CI.getType());
7401
7402 // Remove any uses of AI that are dead.
7403 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7404
7405 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7406 Instruction *User = cast<Instruction>(*UI++);
7407 if (isInstructionTriviallyDead(User)) {
7408 while (UI != E && *UI == User)
7409 ++UI; // If this instruction uses AI more than once, don't break UI.
7410
7411 ++NumDeadInst;
7412 DOUT << "IC: DCE: " << *User;
7413 EraseInstFromFunction(*User);
7414 }
7415 }
7416
7417 // Get the type really allocated and the type casted to.
7418 const Type *AllocElTy = AI.getAllocatedType();
7419 const Type *CastElTy = PTy->getElementType();
7420 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7421
7422 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7423 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7424 if (CastElTyAlign < AllocElTyAlign) return 0;
7425
7426 // If the allocation has multiple uses, only promote it if we are strictly
7427 // increasing the alignment of the resultant allocation. If we keep it the
7428 // same, we open the door to infinite loops of various kinds.
7429 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7430
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007431 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7432 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007433 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7434
7435 // See if we can satisfy the modulus by pulling a scale out of the array
7436 // size argument.
7437 unsigned ArraySizeScale;
7438 int ArrayOffset;
7439 Value *NumElements = // See if the array size is a decomposable linear expr.
7440 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7441
7442 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7443 // do the xform.
7444 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7445 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7446
7447 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7448 Value *Amt = 0;
7449 if (Scale == 1) {
7450 Amt = NumElements;
7451 } else {
7452 // If the allocation size is constant, form a constant mul expression
7453 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7454 if (isa<ConstantInt>(NumElements))
7455 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7456 // otherwise multiply the amount and the number of elements
7457 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007458 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007459 Amt = InsertNewInstBefore(Tmp, AI);
7460 }
7461 }
7462
7463 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7464 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007465 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007466 Amt = InsertNewInstBefore(Tmp, AI);
7467 }
7468
7469 AllocationInst *New;
7470 if (isa<MallocInst>(AI))
7471 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7472 else
7473 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7474 InsertNewInstBefore(New, AI);
7475 New->takeName(&AI);
7476
7477 // If the allocation has multiple uses, insert a cast and change all things
7478 // that used it to use the new cast. This will also hack on CI, but it will
7479 // die soon.
7480 if (!AI.hasOneUse()) {
7481 AddUsesToWorkList(AI);
7482 // New is the allocation instruction, pointer typed. AI is the original
7483 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7484 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7485 InsertNewInstBefore(NewCast, AI);
7486 AI.replaceAllUsesWith(NewCast);
7487 }
7488 return ReplaceInstUsesWith(CI, New);
7489}
7490
7491/// CanEvaluateInDifferentType - Return true if we can take the specified value
7492/// and return it as type Ty without inserting any new casts and without
7493/// changing the computed value. This is used by code that tries to decide
7494/// whether promoting or shrinking integer operations to wider or smaller types
7495/// will allow us to eliminate a truncate or extend.
7496///
7497/// This is a truncation operation if Ty is smaller than V->getType(), or an
7498/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00007499bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7500 unsigned CastOpc,
7501 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502 // We can always evaluate constants in another type.
7503 if (isa<ConstantInt>(V))
7504 return true;
7505
7506 Instruction *I = dyn_cast<Instruction>(V);
7507 if (!I) return false;
7508
7509 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7510
Chris Lattneref70bb82007-08-02 06:11:14 +00007511 // If this is an extension or truncate, we can often eliminate it.
7512 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7513 // If this is a cast from the destination type, we can trivially eliminate
7514 // it, and this will remove a cast overall.
7515 if (I->getOperand(0)->getType() == Ty) {
7516 // If the first operand is itself a cast, and is eliminable, do not count
7517 // this as an eliminable cast. We would prefer to eliminate those two
7518 // casts first.
7519 if (!isa<CastInst>(I->getOperand(0)))
7520 ++NumCastsRemoved;
7521 return true;
7522 }
7523 }
7524
7525 // We can't extend or shrink something that has multiple uses: doing so would
7526 // require duplicating the instruction in general, which isn't profitable.
7527 if (!I->hasOneUse()) return false;
7528
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007529 switch (I->getOpcode()) {
7530 case Instruction::Add:
7531 case Instruction::Sub:
7532 case Instruction::And:
7533 case Instruction::Or:
7534 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007535 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007536 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7537 NumCastsRemoved) &&
7538 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7539 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007540
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007541 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007542 // A multiply can be truncated by truncating its operands.
7543 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7544 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7545 NumCastsRemoved) &&
7546 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7547 NumCastsRemoved);
7548
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007549 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007550 // If we are truncating the result of this SHL, and if it's a shift of a
7551 // constant amount, we can always perform a SHL in a smaller type.
7552 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7553 uint32_t BitWidth = Ty->getBitWidth();
7554 if (BitWidth < OrigTy->getBitWidth() &&
7555 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007556 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7557 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007558 }
7559 break;
7560 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007561 // If this is a truncate of a logical shr, we can truncate it to a smaller
7562 // lshr iff we know that the bits we would otherwise be shifting in are
7563 // already zeros.
7564 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7565 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7566 uint32_t BitWidth = Ty->getBitWidth();
7567 if (BitWidth < OrigBitWidth &&
7568 MaskedValueIsZero(I->getOperand(0),
7569 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7570 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007571 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7572 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007573 }
7574 }
7575 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007576 case Instruction::ZExt:
7577 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007578 case Instruction::Trunc:
7579 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007580 // can safely replace it. Note that replacing it does not reduce the number
7581 // of casts in the input.
7582 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007583 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00007584
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007585 break;
7586 default:
7587 // TODO: Can handle more cases here.
7588 break;
7589 }
7590
7591 return false;
7592}
7593
7594/// EvaluateInDifferentType - Given an expression that
7595/// CanEvaluateInDifferentType returns true for, actually insert the code to
7596/// evaluate the expression.
7597Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7598 bool isSigned) {
7599 if (Constant *C = dyn_cast<Constant>(V))
7600 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7601
7602 // Otherwise, it must be an instruction.
7603 Instruction *I = cast<Instruction>(V);
7604 Instruction *Res = 0;
7605 switch (I->getOpcode()) {
7606 case Instruction::Add:
7607 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007608 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007609 case Instruction::And:
7610 case Instruction::Or:
7611 case Instruction::Xor:
7612 case Instruction::AShr:
7613 case Instruction::LShr:
7614 case Instruction::Shl: {
7615 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7616 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007617 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007618 LHS, RHS, I->getName());
7619 break;
7620 }
7621 case Instruction::Trunc:
7622 case Instruction::ZExt:
7623 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007624 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007625 // just return the source. There's no need to insert it because it is not
7626 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007627 if (I->getOperand(0)->getType() == Ty)
7628 return I->getOperand(0);
7629
Chris Lattneref70bb82007-08-02 06:11:14 +00007630 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007631 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattneref70bb82007-08-02 06:11:14 +00007632 Ty, I->getName());
7633 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007634 default:
7635 // TODO: Can handle more cases here.
7636 assert(0 && "Unreachable!");
7637 break;
7638 }
7639
7640 return InsertNewInstBefore(Res, *I);
7641}
7642
7643/// @brief Implement the transforms common to all CastInst visitors.
7644Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7645 Value *Src = CI.getOperand(0);
7646
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007647 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7648 // eliminate it now.
7649 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7650 if (Instruction::CastOps opc =
7651 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7652 // The first cast (CSrc) is eliminable so we need to fix up or replace
7653 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007654 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007655 }
7656 }
7657
7658 // If we are casting a select then fold the cast into the select
7659 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7660 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7661 return NV;
7662
7663 // If we are casting a PHI then fold the cast into the PHI
7664 if (isa<PHINode>(Src))
7665 if (Instruction *NV = FoldOpIntoPhi(CI))
7666 return NV;
7667
7668 return 0;
7669}
7670
7671/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7672Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7673 Value *Src = CI.getOperand(0);
7674
7675 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7676 // If casting the result of a getelementptr instruction with no offset, turn
7677 // this into a cast of the original pointer!
7678 if (GEP->hasAllZeroIndices()) {
7679 // Changing the cast operand is usually not a good idea but it is safe
7680 // here because the pointer operand is being replaced with another
7681 // pointer operand so the opcode doesn't need to change.
7682 AddToWorkList(GEP);
7683 CI.setOperand(0, GEP->getOperand(0));
7684 return &CI;
7685 }
7686
7687 // If the GEP has a single use, and the base pointer is a bitcast, and the
7688 // GEP computes a constant offset, see if we can convert these three
7689 // instructions into fewer. This typically happens with unions and other
7690 // non-type-safe code.
7691 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7692 if (GEP->hasAllConstantIndices()) {
7693 // We are guaranteed to get a constant from EmitGEPOffset.
7694 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7695 int64_t Offset = OffsetV->getSExtValue();
7696
7697 // Get the base pointer input of the bitcast, and the type it points to.
7698 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7699 const Type *GEPIdxTy =
7700 cast<PointerType>(OrigBase->getType())->getElementType();
7701 if (GEPIdxTy->isSized()) {
7702 SmallVector<Value*, 8> NewIndices;
7703
7704 // Start with the index over the outer type. Note that the type size
7705 // might be zero (even if the offset isn't zero) if the indexed type
7706 // is something like [0 x {int, int}]
7707 const Type *IntPtrTy = TD->getIntPtrType();
7708 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007709 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007710 FirstIdx = Offset/TySize;
7711 Offset %= TySize;
7712
7713 // Handle silly modulus not returning values values [0..TySize).
7714 if (Offset < 0) {
7715 --FirstIdx;
7716 Offset += TySize;
7717 assert(Offset >= 0);
7718 }
7719 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7720 }
7721
7722 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7723
7724 // Index into the types. If we fail, set OrigBase to null.
7725 while (Offset) {
7726 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7727 const StructLayout *SL = TD->getStructLayout(STy);
7728 if (Offset < (int64_t)SL->getSizeInBytes()) {
7729 unsigned Elt = SL->getElementContainingOffset(Offset);
7730 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7731
7732 Offset -= SL->getElementOffset(Elt);
7733 GEPIdxTy = STy->getElementType(Elt);
7734 } else {
7735 // Otherwise, we can't index into this, bail out.
7736 Offset = 0;
7737 OrigBase = 0;
7738 }
7739 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7740 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007741 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007742 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7743 Offset %= EltSize;
7744 } else {
7745 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7746 }
7747 GEPIdxTy = STy->getElementType();
7748 } else {
7749 // Otherwise, we can't index into this, bail out.
7750 Offset = 0;
7751 OrigBase = 0;
7752 }
7753 }
7754 if (OrigBase) {
7755 // If we were able to index down into an element, create the GEP
7756 // and bitcast the result. This eliminates one bitcast, potentially
7757 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007758 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7759 NewIndices.begin(),
7760 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007761 InsertNewInstBefore(NGEP, CI);
7762 NGEP->takeName(GEP);
7763
7764 if (isa<BitCastInst>(CI))
7765 return new BitCastInst(NGEP, CI.getType());
7766 assert(isa<PtrToIntInst>(CI));
7767 return new PtrToIntInst(NGEP, CI.getType());
7768 }
7769 }
7770 }
7771 }
7772 }
7773
7774 return commonCastTransforms(CI);
7775}
7776
7777
7778
7779/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7780/// integer types. This function implements the common transforms for all those
7781/// cases.
7782/// @brief Implement the transforms common to CastInst with integer operands
7783Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7784 if (Instruction *Result = commonCastTransforms(CI))
7785 return Result;
7786
7787 Value *Src = CI.getOperand(0);
7788 const Type *SrcTy = Src->getType();
7789 const Type *DestTy = CI.getType();
7790 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7791 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7792
7793 // See if we can simplify any instructions used by the LHS whose sole
7794 // purpose is to compute bits we don't care about.
7795 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7796 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7797 KnownZero, KnownOne))
7798 return &CI;
7799
7800 // If the source isn't an instruction or has more than one use then we
7801 // can't do anything more.
7802 Instruction *SrcI = dyn_cast<Instruction>(Src);
7803 if (!SrcI || !Src->hasOneUse())
7804 return 0;
7805
7806 // Attempt to propagate the cast into the instruction for int->int casts.
7807 int NumCastsRemoved = 0;
7808 if (!isa<BitCastInst>(CI) &&
7809 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007810 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007811 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007812 // eliminates the cast, so it is always a win. If this is a zero-extension,
7813 // we need to do an AND to maintain the clear top-part of the computation,
7814 // so we require that the input have eliminated at least one cast. If this
7815 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007816 // require that two casts have been eliminated.
7817 bool DoXForm;
7818 switch (CI.getOpcode()) {
7819 default:
7820 // All the others use floating point so we shouldn't actually
7821 // get here because of the check above.
7822 assert(0 && "Unknown cast type");
7823 case Instruction::Trunc:
7824 DoXForm = true;
7825 break;
7826 case Instruction::ZExt:
7827 DoXForm = NumCastsRemoved >= 1;
7828 break;
7829 case Instruction::SExt:
7830 DoXForm = NumCastsRemoved >= 2;
7831 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007832 }
7833
7834 if (DoXForm) {
7835 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7836 CI.getOpcode() == Instruction::SExt);
7837 assert(Res->getType() == DestTy);
7838 switch (CI.getOpcode()) {
7839 default: assert(0 && "Unknown cast type!");
7840 case Instruction::Trunc:
7841 case Instruction::BitCast:
7842 // Just replace this cast with the result.
7843 return ReplaceInstUsesWith(CI, Res);
7844 case Instruction::ZExt: {
7845 // We need to emit an AND to clear the high bits.
7846 assert(SrcBitSize < DestBitSize && "Not a zext?");
7847 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7848 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007849 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007850 }
7851 case Instruction::SExt:
7852 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007853 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007854 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7855 CI), DestTy);
7856 }
7857 }
7858 }
7859
7860 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7861 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7862
7863 switch (SrcI->getOpcode()) {
7864 case Instruction::Add:
7865 case Instruction::Mul:
7866 case Instruction::And:
7867 case Instruction::Or:
7868 case Instruction::Xor:
7869 // If we are discarding information, rewrite.
7870 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7871 // Don't insert two casts if they cannot be eliminated. We allow
7872 // two casts to be inserted if the sizes are the same. This could
7873 // only be converting signedness, which is a noop.
7874 if (DestBitSize == SrcBitSize ||
7875 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7876 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7877 Instruction::CastOps opcode = CI.getOpcode();
7878 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7879 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007880 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007881 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7882 }
7883 }
7884
7885 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7886 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7887 SrcI->getOpcode() == Instruction::Xor &&
7888 Op1 == ConstantInt::getTrue() &&
7889 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7890 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007891 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007892 }
7893 break;
7894 case Instruction::SDiv:
7895 case Instruction::UDiv:
7896 case Instruction::SRem:
7897 case Instruction::URem:
7898 // If we are just changing the sign, rewrite.
7899 if (DestBitSize == SrcBitSize) {
7900 // Don't insert two casts if they cannot be eliminated. We allow
7901 // two casts to be inserted if the sizes are the same. This could
7902 // only be converting signedness, which is a noop.
7903 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7904 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7905 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7906 Op0, DestTy, SrcI);
7907 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7908 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007909 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007910 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7911 }
7912 }
7913 break;
7914
7915 case Instruction::Shl:
7916 // Allow changing the sign of the source operand. Do not allow
7917 // changing the size of the shift, UNLESS the shift amount is a
7918 // constant. We must not change variable sized shifts to a smaller
7919 // size, because it is undefined to shift more bits out than exist
7920 // in the value.
7921 if (DestBitSize == SrcBitSize ||
7922 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7923 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7924 Instruction::BitCast : Instruction::Trunc);
7925 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7926 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007927 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928 }
7929 break;
7930 case Instruction::AShr:
7931 // If this is a signed shr, and if all bits shifted in are about to be
7932 // truncated off, turn it into an unsigned shr to allow greater
7933 // simplifications.
7934 if (DestBitSize < SrcBitSize &&
7935 isa<ConstantInt>(Op1)) {
7936 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7937 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7938 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007939 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007940 }
7941 }
7942 break;
7943 }
7944 return 0;
7945}
7946
7947Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7948 if (Instruction *Result = commonIntCastTransforms(CI))
7949 return Result;
7950
7951 Value *Src = CI.getOperand(0);
7952 const Type *Ty = CI.getType();
7953 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7954 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7955
7956 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7957 switch (SrcI->getOpcode()) {
7958 default: break;
7959 case Instruction::LShr:
7960 // We can shrink lshr to something smaller if we know the bits shifted in
7961 // are already zeros.
7962 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7963 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7964
7965 // Get a mask for the bits shifting in.
7966 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7967 Value* SrcIOp0 = SrcI->getOperand(0);
7968 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7969 if (ShAmt >= DestBitWidth) // All zeros.
7970 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7971
7972 // Okay, we can shrink this. Truncate the input, then return a new
7973 // shift.
7974 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7975 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7976 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007977 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007978 }
7979 } else { // This is a variable shr.
7980
7981 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7982 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7983 // loop-invariant and CSE'd.
7984 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7985 Value *One = ConstantInt::get(SrcI->getType(), 1);
7986
7987 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007988 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007989 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007990 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007991 SrcI->getOperand(0),
7992 "tmp"), CI);
7993 Value *Zero = Constant::getNullValue(V->getType());
7994 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7995 }
7996 }
7997 break;
7998 }
7999 }
8000
8001 return 0;
8002}
8003
Evan Chenge3779cf2008-03-24 00:21:34 +00008004/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8005/// in order to eliminate the icmp.
8006Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8007 bool DoXform) {
8008 // If we are just checking for a icmp eq of a single bit and zext'ing it
8009 // to an integer, then shift the bit to the appropriate place and then
8010 // cast to integer to avoid the comparison.
8011 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8012 const APInt &Op1CV = Op1C->getValue();
8013
8014 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8015 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8016 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8017 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8018 if (!DoXform) return ICI;
8019
8020 Value *In = ICI->getOperand(0);
8021 Value *Sh = ConstantInt::get(In->getType(),
8022 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008023 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008024 In->getName()+".lobit"),
8025 CI);
8026 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008027 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008028 false/*ZExt*/, "tmp", &CI);
8029
8030 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8031 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008032 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008033 In->getName()+".not"),
8034 CI);
8035 }
8036
8037 return ReplaceInstUsesWith(CI, In);
8038 }
8039
8040
8041
8042 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8043 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8044 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8045 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8046 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8047 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8048 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8049 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8050 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8051 // This only works for EQ and NE
8052 ICI->isEquality()) {
8053 // If Op1C some other power of two, convert:
8054 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8055 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8056 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8057 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8058
8059 APInt KnownZeroMask(~KnownZero);
8060 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8061 if (!DoXform) return ICI;
8062
8063 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8064 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8065 // (X&4) == 2 --> false
8066 // (X&4) != 2 --> true
8067 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8068 Res = ConstantExpr::getZExt(Res, CI.getType());
8069 return ReplaceInstUsesWith(CI, Res);
8070 }
8071
8072 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8073 Value *In = ICI->getOperand(0);
8074 if (ShiftAmt) {
8075 // Perform a logical shr by shiftamt.
8076 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008077 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00008078 ConstantInt::get(In->getType(), ShiftAmt),
8079 In->getName()+".lobit"), CI);
8080 }
8081
8082 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8083 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008084 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008085 InsertNewInstBefore(cast<Instruction>(In), CI);
8086 }
8087
8088 if (CI.getType() == In->getType())
8089 return ReplaceInstUsesWith(CI, In);
8090 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008091 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008092 }
8093 }
8094 }
8095
8096 return 0;
8097}
8098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008099Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8100 // If one of the common conversion will work ..
8101 if (Instruction *Result = commonIntCastTransforms(CI))
8102 return Result;
8103
8104 Value *Src = CI.getOperand(0);
8105
8106 // If this is a cast of a cast
8107 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8108 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8109 // types and if the sizes are just right we can convert this into a logical
8110 // 'and' which will be much cheaper than the pair of casts.
8111 if (isa<TruncInst>(CSrc)) {
8112 // Get the sizes of the types involved
8113 Value *A = CSrc->getOperand(0);
8114 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8115 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8116 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8117 // If we're actually extending zero bits and the trunc is a no-op
8118 if (MidSize < DstSize && SrcSize == DstSize) {
8119 // Replace both of the casts with an And of the type mask.
8120 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8121 Constant *AndConst = ConstantInt::get(AndValue);
8122 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00008123 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008124 // Unfortunately, if the type changed, we need to cast it back.
8125 if (And->getType() != CI.getType()) {
8126 And->setName(CSrc->getName()+".mask");
8127 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008128 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008129 }
8130 return And;
8131 }
8132 }
8133 }
8134
Evan Chenge3779cf2008-03-24 00:21:34 +00008135 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8136 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008137
Evan Chenge3779cf2008-03-24 00:21:34 +00008138 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8139 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8140 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8141 // of the (zext icmp) will be transformed.
8142 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8143 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8144 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8145 (transformZExtICmp(LHS, CI, false) ||
8146 transformZExtICmp(RHS, CI, false))) {
8147 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8148 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008149 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008150 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008151 }
8152
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008153 return 0;
8154}
8155
8156Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8157 if (Instruction *I = commonIntCastTransforms(CI))
8158 return I;
8159
8160 Value *Src = CI.getOperand(0);
8161
8162 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8163 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8164 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8165 // If we are just checking for a icmp eq of a single bit and zext'ing it
8166 // to an integer, then shift the bit to the appropriate place and then
8167 // cast to integer to avoid the comparison.
8168 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8169 const APInt &Op1CV = Op1C->getValue();
8170
8171 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8172 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8173 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8174 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8175 Value *In = ICI->getOperand(0);
8176 Value *Sh = ConstantInt::get(In->getType(),
8177 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008178 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008179 In->getName()+".lobit"),
8180 CI);
8181 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008182 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008183 true/*SExt*/, "tmp", &CI);
8184
8185 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00008186 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008187 In->getName()+".not"), CI);
8188
8189 return ReplaceInstUsesWith(CI, In);
8190 }
8191 }
8192 }
Dan Gohmanf0f12022008-05-20 21:01:12 +00008193
8194 // See if the value being truncated is already sign extended. If so, just
8195 // eliminate the trunc/sext pair.
8196 if (getOpcode(Src) == Instruction::Trunc) {
8197 Value *Op = cast<User>(Src)->getOperand(0);
8198 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8199 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8200 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8201 unsigned NumSignBits = ComputeNumSignBits(Op);
8202
8203 if (OpBits == DestBits) {
8204 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8205 // bits, it is already ready.
8206 if (NumSignBits > DestBits-MidBits)
8207 return ReplaceInstUsesWith(CI, Op);
8208 } else if (OpBits < DestBits) {
8209 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8210 // bits, just sext from i32.
8211 if (NumSignBits > OpBits-MidBits)
8212 return new SExtInst(Op, CI.getType(), "tmp");
8213 } else {
8214 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8215 // bits, just truncate to i32.
8216 if (NumSignBits > OpBits-MidBits)
8217 return new TruncInst(Op, CI.getType(), "tmp");
8218 }
8219 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008220
8221 return 0;
8222}
8223
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008224/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8225/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008226static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008227 APFloat F = CFP->getValueAPF();
8228 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00008229 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008230 return 0;
8231}
8232
8233/// LookThroughFPExtensions - If this is an fp extension instruction, look
8234/// through it until we get the source value.
8235static Value *LookThroughFPExtensions(Value *V) {
8236 if (Instruction *I = dyn_cast<Instruction>(V))
8237 if (I->getOpcode() == Instruction::FPExt)
8238 return LookThroughFPExtensions(I->getOperand(0));
8239
8240 // If this value is a constant, return the constant in the smallest FP type
8241 // that can accurately represent it. This allows us to turn
8242 // (float)((double)X+2.0) into x+2.0f.
8243 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8244 if (CFP->getType() == Type::PPC_FP128Ty)
8245 return V; // No constant folding of this.
8246 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008247 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008248 return V;
8249 if (CFP->getType() == Type::DoubleTy)
8250 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008251 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008252 return V;
8253 // Don't try to shrink to various long double types.
8254 }
8255
8256 return V;
8257}
8258
8259Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8260 if (Instruction *I = commonCastTransforms(CI))
8261 return I;
8262
8263 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8264 // smaller than the destination type, we can eliminate the truncate by doing
8265 // the add as the smaller type. This applies to add/sub/mul/div as well as
8266 // many builtins (sqrt, etc).
8267 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8268 if (OpI && OpI->hasOneUse()) {
8269 switch (OpI->getOpcode()) {
8270 default: break;
8271 case Instruction::Add:
8272 case Instruction::Sub:
8273 case Instruction::Mul:
8274 case Instruction::FDiv:
8275 case Instruction::FRem:
8276 const Type *SrcTy = OpI->getType();
8277 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8278 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8279 if (LHSTrunc->getType() != SrcTy &&
8280 RHSTrunc->getType() != SrcTy) {
8281 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8282 // If the source types were both smaller than the destination type of
8283 // the cast, do this xform.
8284 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8285 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8286 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8287 CI.getType(), CI);
8288 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8289 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008290 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008291 }
8292 }
8293 break;
8294 }
8295 }
8296 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008297}
8298
8299Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8300 return commonCastTransforms(CI);
8301}
8302
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008303Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8304 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8305 // mantissa to accurately represent all values of X. For example, do not
8306 // do this with i64->float->i64.
8307 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8308 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8309 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner9ce836b2008-05-19 21:17:23 +00008310 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008311 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8312
8313 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008314}
8315
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008316Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8317 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8318 // mantissa to accurately represent all values of X. For example, do not
8319 // do this with i64->float->i64.
8320 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8321 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8322 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner9ce836b2008-05-19 21:17:23 +00008323 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008324 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8325
8326 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008327}
8328
8329Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8330 return commonCastTransforms(CI);
8331}
8332
8333Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8334 return commonCastTransforms(CI);
8335}
8336
8337Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8338 return commonPointerCastTransforms(CI);
8339}
8340
Chris Lattner7c1626482008-01-08 07:23:51 +00008341Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8342 if (Instruction *I = commonCastTransforms(CI))
8343 return I;
8344
8345 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8346 if (!DestPointee->isSized()) return 0;
8347
8348 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8349 ConstantInt *Cst;
8350 Value *X;
8351 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8352 m_ConstantInt(Cst)))) {
8353 // If the source and destination operands have the same type, see if this
8354 // is a single-index GEP.
8355 if (X->getType() == CI.getType()) {
8356 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00008357 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008358
8359 // Convert the constant to intptr type.
8360 APInt Offset = Cst->getValue();
8361 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8362
8363 // If Offset is evenly divisible by Size, we can do this xform.
8364 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8365 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008366 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008367 }
8368 }
8369 // TODO: Could handle other cases, e.g. where add is indexing into field of
8370 // struct etc.
8371 } else if (CI.getOperand(0)->hasOneUse() &&
8372 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8373 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8374 // "inttoptr+GEP" instead of "add+intptr".
8375
8376 // Get the size of the pointee type.
8377 uint64_t Size = TD->getABITypeSize(DestPointee);
8378
8379 // Convert the constant to intptr type.
8380 APInt Offset = Cst->getValue();
8381 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8382
8383 // If Offset is evenly divisible by Size, we can do this xform.
8384 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8385 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8386
8387 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8388 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008389 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008390 }
8391 }
8392 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008393}
8394
8395Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8396 // If the operands are integer typed then apply the integer transforms,
8397 // otherwise just apply the common ones.
8398 Value *Src = CI.getOperand(0);
8399 const Type *SrcTy = Src->getType();
8400 const Type *DestTy = CI.getType();
8401
8402 if (SrcTy->isInteger() && DestTy->isInteger()) {
8403 if (Instruction *Result = commonIntCastTransforms(CI))
8404 return Result;
8405 } else if (isa<PointerType>(SrcTy)) {
8406 if (Instruction *I = commonPointerCastTransforms(CI))
8407 return I;
8408 } else {
8409 if (Instruction *Result = commonCastTransforms(CI))
8410 return Result;
8411 }
8412
8413
8414 // Get rid of casts from one type to the same type. These are useless and can
8415 // be replaced by the operand.
8416 if (DestTy == Src->getType())
8417 return ReplaceInstUsesWith(CI, Src);
8418
8419 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8420 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8421 const Type *DstElTy = DstPTy->getElementType();
8422 const Type *SrcElTy = SrcPTy->getElementType();
8423
Nate Begemandf5b3612008-03-31 00:22:16 +00008424 // If the address spaces don't match, don't eliminate the bitcast, which is
8425 // required for changing types.
8426 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8427 return 0;
8428
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008429 // If we are casting a malloc or alloca to a pointer to a type of the same
8430 // size, rewrite the allocation instruction to allocate the "right" type.
8431 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8432 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8433 return V;
8434
8435 // If the source and destination are pointers, and this cast is equivalent
8436 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8437 // This can enhance SROA and other transforms that want type-safe pointers.
8438 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8439 unsigned NumZeros = 0;
8440 while (SrcElTy != DstElTy &&
8441 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8442 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8443 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8444 ++NumZeros;
8445 }
8446
8447 // If we found a path from the src to dest, create the getelementptr now.
8448 if (SrcElTy == DstElTy) {
8449 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008450 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8451 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008452 }
8453 }
8454
8455 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8456 if (SVI->hasOneUse()) {
8457 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8458 // a bitconvert to a vector with the same # elts.
8459 if (isa<VectorType>(DestTy) &&
8460 cast<VectorType>(DestTy)->getNumElements() ==
8461 SVI->getType()->getNumElements()) {
8462 CastInst *Tmp;
8463 // If either of the operands is a cast from CI.getType(), then
8464 // evaluating the shuffle in the casted destination's type will allow
8465 // us to eliminate at least one cast.
8466 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8467 Tmp->getOperand(0)->getType() == DestTy) ||
8468 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8469 Tmp->getOperand(0)->getType() == DestTy)) {
8470 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8471 SVI->getOperand(0), DestTy, &CI);
8472 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8473 SVI->getOperand(1), DestTy, &CI);
8474 // Return a new shuffle vector. Use the same element ID's, as we
8475 // know the vector types match #elts.
8476 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8477 }
8478 }
8479 }
8480 }
8481 return 0;
8482}
8483
8484/// GetSelectFoldableOperands - We want to turn code that looks like this:
8485/// %C = or %A, %B
8486/// %D = select %cond, %C, %A
8487/// into:
8488/// %C = select %cond, %B, 0
8489/// %D = or %A, %C
8490///
8491/// Assuming that the specified instruction is an operand to the select, return
8492/// a bitmask indicating which operands of this instruction are foldable if they
8493/// equal the other incoming value of the select.
8494///
8495static unsigned GetSelectFoldableOperands(Instruction *I) {
8496 switch (I->getOpcode()) {
8497 case Instruction::Add:
8498 case Instruction::Mul:
8499 case Instruction::And:
8500 case Instruction::Or:
8501 case Instruction::Xor:
8502 return 3; // Can fold through either operand.
8503 case Instruction::Sub: // Can only fold on the amount subtracted.
8504 case Instruction::Shl: // Can only fold on the shift amount.
8505 case Instruction::LShr:
8506 case Instruction::AShr:
8507 return 1;
8508 default:
8509 return 0; // Cannot fold
8510 }
8511}
8512
8513/// GetSelectFoldableConstant - For the same transformation as the previous
8514/// function, return the identity constant that goes into the select.
8515static Constant *GetSelectFoldableConstant(Instruction *I) {
8516 switch (I->getOpcode()) {
8517 default: assert(0 && "This cannot happen!"); abort();
8518 case Instruction::Add:
8519 case Instruction::Sub:
8520 case Instruction::Or:
8521 case Instruction::Xor:
8522 case Instruction::Shl:
8523 case Instruction::LShr:
8524 case Instruction::AShr:
8525 return Constant::getNullValue(I->getType());
8526 case Instruction::And:
8527 return Constant::getAllOnesValue(I->getType());
8528 case Instruction::Mul:
8529 return ConstantInt::get(I->getType(), 1);
8530 }
8531}
8532
8533/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8534/// have the same opcode and only one use each. Try to simplify this.
8535Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8536 Instruction *FI) {
8537 if (TI->getNumOperands() == 1) {
8538 // If this is a non-volatile load or a cast from the same type,
8539 // merge.
8540 if (TI->isCast()) {
8541 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8542 return 0;
8543 } else {
8544 return 0; // unknown unary op.
8545 }
8546
8547 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008548 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8549 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008550 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008551 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008552 TI->getType());
8553 }
8554
8555 // Only handle binary operators here.
8556 if (!isa<BinaryOperator>(TI))
8557 return 0;
8558
8559 // Figure out if the operations have any operands in common.
8560 Value *MatchOp, *OtherOpT, *OtherOpF;
8561 bool MatchIsOpZero;
8562 if (TI->getOperand(0) == FI->getOperand(0)) {
8563 MatchOp = TI->getOperand(0);
8564 OtherOpT = TI->getOperand(1);
8565 OtherOpF = FI->getOperand(1);
8566 MatchIsOpZero = true;
8567 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8568 MatchOp = TI->getOperand(1);
8569 OtherOpT = TI->getOperand(0);
8570 OtherOpF = FI->getOperand(0);
8571 MatchIsOpZero = false;
8572 } else if (!TI->isCommutative()) {
8573 return 0;
8574 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8575 MatchOp = TI->getOperand(0);
8576 OtherOpT = TI->getOperand(1);
8577 OtherOpF = FI->getOperand(0);
8578 MatchIsOpZero = true;
8579 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8580 MatchOp = TI->getOperand(1);
8581 OtherOpT = TI->getOperand(0);
8582 OtherOpF = FI->getOperand(1);
8583 MatchIsOpZero = true;
8584 } else {
8585 return 0;
8586 }
8587
8588 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008589 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8590 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008591 InsertNewInstBefore(NewSI, SI);
8592
8593 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8594 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008595 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008596 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008597 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008598 }
8599 assert(0 && "Shouldn't get here");
8600 return 0;
8601}
8602
8603Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8604 Value *CondVal = SI.getCondition();
8605 Value *TrueVal = SI.getTrueValue();
8606 Value *FalseVal = SI.getFalseValue();
8607
8608 // select true, X, Y -> X
8609 // select false, X, Y -> Y
8610 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8611 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8612
8613 // select C, X, X -> X
8614 if (TrueVal == FalseVal)
8615 return ReplaceInstUsesWith(SI, TrueVal);
8616
8617 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8618 return ReplaceInstUsesWith(SI, FalseVal);
8619 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8620 return ReplaceInstUsesWith(SI, TrueVal);
8621 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8622 if (isa<Constant>(TrueVal))
8623 return ReplaceInstUsesWith(SI, TrueVal);
8624 else
8625 return ReplaceInstUsesWith(SI, FalseVal);
8626 }
8627
8628 if (SI.getType() == Type::Int1Ty) {
8629 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8630 if (C->getZExtValue()) {
8631 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008632 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008633 } else {
8634 // Change: A = select B, false, C --> A = and !B, C
8635 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008636 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008637 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008638 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008639 }
8640 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8641 if (C->getZExtValue() == false) {
8642 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008643 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008644 } else {
8645 // Change: A = select B, C, true --> A = or !B, C
8646 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008647 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008648 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008649 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008650 }
8651 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008652
8653 // select a, b, a -> a&b
8654 // select a, a, b -> a|b
8655 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008656 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008657 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008658 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008659 }
8660
8661 // Selecting between two integer constants?
8662 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8663 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8664 // select C, 1, 0 -> zext C to int
8665 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008666 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008667 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8668 // select C, 0, 1 -> zext !C to int
8669 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008670 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008671 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008672 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008673 }
8674
8675 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8676
8677 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8678
8679 // (x <s 0) ? -1 : 0 -> ashr x, 31
8680 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8681 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8682 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8683 // The comparison constant and the result are not neccessarily the
8684 // same width. Make an all-ones value by inserting a AShr.
8685 Value *X = IC->getOperand(0);
8686 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8687 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008688 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008689 ShAmt, "ones");
8690 InsertNewInstBefore(SRA, SI);
8691
8692 // Finally, convert to the type of the select RHS. We figure out
8693 // if this requires a SExt, Trunc or BitCast based on the sizes.
8694 Instruction::CastOps opc = Instruction::BitCast;
8695 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8696 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8697 if (SRASize < SISize)
8698 opc = Instruction::SExt;
8699 else if (SRASize > SISize)
8700 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008701 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008702 }
8703 }
8704
8705
8706 // If one of the constants is zero (we know they can't both be) and we
8707 // have an icmp instruction with zero, and we have an 'and' with the
8708 // non-constant value, eliminate this whole mess. This corresponds to
8709 // cases like this: ((X & 27) ? 27 : 0)
8710 if (TrueValC->isZero() || FalseValC->isZero())
8711 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8712 cast<Constant>(IC->getOperand(1))->isNullValue())
8713 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8714 if (ICA->getOpcode() == Instruction::And &&
8715 isa<ConstantInt>(ICA->getOperand(1)) &&
8716 (ICA->getOperand(1) == TrueValC ||
8717 ICA->getOperand(1) == FalseValC) &&
8718 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8719 // Okay, now we know that everything is set up, we just don't
8720 // know whether we have a icmp_ne or icmp_eq and whether the
8721 // true or false val is the zero.
8722 bool ShouldNotVal = !TrueValC->isZero();
8723 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8724 Value *V = ICA;
8725 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008726 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008727 Instruction::Xor, V, ICA->getOperand(1)), SI);
8728 return ReplaceInstUsesWith(SI, V);
8729 }
8730 }
8731 }
8732
8733 // See if we are selecting two values based on a comparison of the two values.
8734 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8735 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8736 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008737 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8738 // This is not safe in general for floating point:
8739 // consider X== -0, Y== +0.
8740 // It becomes safe if either operand is a nonzero constant.
8741 ConstantFP *CFPt, *CFPf;
8742 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8743 !CFPt->getValueAPF().isZero()) ||
8744 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8745 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008746 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008747 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008748 // Transform (X != Y) ? X : Y -> X
8749 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8750 return ReplaceInstUsesWith(SI, TrueVal);
8751 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8752
8753 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8754 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008755 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8756 // This is not safe in general for floating point:
8757 // consider X== -0, Y== +0.
8758 // It becomes safe if either operand is a nonzero constant.
8759 ConstantFP *CFPt, *CFPf;
8760 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8761 !CFPt->getValueAPF().isZero()) ||
8762 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8763 !CFPf->getValueAPF().isZero()))
8764 return ReplaceInstUsesWith(SI, FalseVal);
8765 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008766 // Transform (X != Y) ? Y : X -> Y
8767 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8768 return ReplaceInstUsesWith(SI, TrueVal);
8769 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8770 }
8771 }
8772
8773 // See if we are selecting two values based on a comparison of the two values.
8774 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8775 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8776 // Transform (X == Y) ? X : Y -> Y
8777 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8778 return ReplaceInstUsesWith(SI, FalseVal);
8779 // Transform (X != Y) ? X : Y -> X
8780 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8781 return ReplaceInstUsesWith(SI, TrueVal);
8782 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8783
8784 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8785 // Transform (X == Y) ? Y : X -> X
8786 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8787 return ReplaceInstUsesWith(SI, FalseVal);
8788 // Transform (X != Y) ? Y : X -> Y
8789 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8790 return ReplaceInstUsesWith(SI, TrueVal);
8791 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8792 }
8793 }
8794
8795 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8796 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8797 if (TI->hasOneUse() && FI->hasOneUse()) {
8798 Instruction *AddOp = 0, *SubOp = 0;
8799
8800 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8801 if (TI->getOpcode() == FI->getOpcode())
8802 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8803 return IV;
8804
8805 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8806 // even legal for FP.
8807 if (TI->getOpcode() == Instruction::Sub &&
8808 FI->getOpcode() == Instruction::Add) {
8809 AddOp = FI; SubOp = TI;
8810 } else if (FI->getOpcode() == Instruction::Sub &&
8811 TI->getOpcode() == Instruction::Add) {
8812 AddOp = TI; SubOp = FI;
8813 }
8814
8815 if (AddOp) {
8816 Value *OtherAddOp = 0;
8817 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8818 OtherAddOp = AddOp->getOperand(1);
8819 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8820 OtherAddOp = AddOp->getOperand(0);
8821 }
8822
8823 if (OtherAddOp) {
8824 // So at this point we know we have (Y -> OtherAddOp):
8825 // select C, (add X, Y), (sub X, Z)
8826 Value *NegVal; // Compute -Z
8827 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8828 NegVal = ConstantExpr::getNeg(C);
8829 } else {
8830 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008831 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008832 }
8833
8834 Value *NewTrueOp = OtherAddOp;
8835 Value *NewFalseOp = NegVal;
8836 if (AddOp != TI)
8837 std::swap(NewTrueOp, NewFalseOp);
8838 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008839 SelectInst::Create(CondVal, NewTrueOp,
8840 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008841
8842 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008843 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008844 }
8845 }
8846 }
8847
8848 // See if we can fold the select into one of our operands.
8849 if (SI.getType()->isInteger()) {
8850 // See the comment above GetSelectFoldableOperands for a description of the
8851 // transformation we are doing here.
8852 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8853 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8854 !isa<Constant>(FalseVal))
8855 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8856 unsigned OpToFold = 0;
8857 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8858 OpToFold = 1;
8859 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8860 OpToFold = 2;
8861 }
8862
8863 if (OpToFold) {
8864 Constant *C = GetSelectFoldableConstant(TVI);
8865 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008866 SelectInst::Create(SI.getCondition(),
8867 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008868 InsertNewInstBefore(NewSel, SI);
8869 NewSel->takeName(TVI);
8870 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008871 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008872 else {
8873 assert(0 && "Unknown instruction!!");
8874 }
8875 }
8876 }
8877
8878 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8879 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8880 !isa<Constant>(TrueVal))
8881 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8882 unsigned OpToFold = 0;
8883 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8884 OpToFold = 1;
8885 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8886 OpToFold = 2;
8887 }
8888
8889 if (OpToFold) {
8890 Constant *C = GetSelectFoldableConstant(FVI);
8891 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008892 SelectInst::Create(SI.getCondition(), C,
8893 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008894 InsertNewInstBefore(NewSel, SI);
8895 NewSel->takeName(FVI);
8896 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008897 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008898 else
8899 assert(0 && "Unknown instruction!!");
8900 }
8901 }
8902 }
8903
8904 if (BinaryOperator::isNot(CondVal)) {
8905 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8906 SI.setOperand(1, FalseVal);
8907 SI.setOperand(2, TrueVal);
8908 return &SI;
8909 }
8910
8911 return 0;
8912}
8913
Dan Gohman2d648bb2008-04-10 18:43:06 +00008914/// EnforceKnownAlignment - If the specified pointer points to an object that
8915/// we control, modify the object's alignment to PrefAlign. This isn't
8916/// often possible though. If alignment is important, a more reliable approach
8917/// is to simply align all global variables and allocation instructions to
8918/// their preferred alignment from the beginning.
8919///
8920static unsigned EnforceKnownAlignment(Value *V,
8921 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008922
Dan Gohman2d648bb2008-04-10 18:43:06 +00008923 User *U = dyn_cast<User>(V);
8924 if (!U) return Align;
8925
8926 switch (getOpcode(U)) {
8927 default: break;
8928 case Instruction::BitCast:
8929 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8930 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008931 // If all indexes are zero, it is just the alignment of the base pointer.
8932 bool AllZeroOperands = true;
Dan Gohman2d648bb2008-04-10 18:43:06 +00008933 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8934 if (!isa<Constant>(U->getOperand(i)) ||
8935 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008936 AllZeroOperands = false;
8937 break;
8938 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008939
8940 if (AllZeroOperands) {
8941 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008942 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008943 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008944 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008945 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008946 }
8947
8948 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8949 // If there is a large requested alignment and we can, bump up the alignment
8950 // of the global.
8951 if (!GV->isDeclaration()) {
8952 GV->setAlignment(PrefAlign);
8953 Align = PrefAlign;
8954 }
8955 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8956 // If there is a requested alignment and if this is an alloca, round up. We
8957 // don't do this for malloc, because some systems can't respect the request.
8958 if (isa<AllocaInst>(AI)) {
8959 AI->setAlignment(PrefAlign);
8960 Align = PrefAlign;
8961 }
8962 }
8963
8964 return Align;
8965}
8966
8967/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8968/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8969/// and it is more than the alignment of the ultimate object, see if we can
8970/// increase the alignment of the ultimate object, making this check succeed.
8971unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8972 unsigned PrefAlign) {
8973 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8974 sizeof(PrefAlign) * CHAR_BIT;
8975 APInt Mask = APInt::getAllOnesValue(BitWidth);
8976 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8977 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8978 unsigned TrailZ = KnownZero.countTrailingOnes();
8979 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8980
8981 if (PrefAlign > Align)
8982 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8983
8984 // We don't need to make any adjustment.
8985 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008986}
8987
Chris Lattner00ae5132008-01-13 23:50:23 +00008988Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008989 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8990 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008991 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8992 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8993
8994 if (CopyAlign < MinAlign) {
8995 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8996 return MI;
8997 }
8998
8999 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9000 // load/store.
9001 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9002 if (MemOpLength == 0) return 0;
9003
Chris Lattnerc669fb62008-01-14 00:28:35 +00009004 // Source and destination pointer types are always "i8*" for intrinsic. See
9005 // if the size is something we can handle with a single primitive load/store.
9006 // A single load+store correctly handles overlapping memory in the memmove
9007 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009008 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009009 if (Size == 0) return MI; // Delete this mem transfer.
9010
9011 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009012 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009013
Chris Lattnerc669fb62008-01-14 00:28:35 +00009014 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00009015 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009016
9017 // Memcpy forces the use of i8* for the source and destination. That means
9018 // that if you're using memcpy to move one double around, you'll get a cast
9019 // from double* to i8*. We'd much rather use a double load+store rather than
9020 // an i64 load+store, here because this improves the odds that the source or
9021 // dest address will be promotable. See if we can find a better type than the
9022 // integer datatype.
9023 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9024 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9025 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9026 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9027 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009028 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009029 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9030 if (STy->getNumElements() == 1)
9031 SrcETy = STy->getElementType(0);
9032 else
9033 break;
9034 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9035 if (ATy->getNumElements() == 1)
9036 SrcETy = ATy->getElementType();
9037 else
9038 break;
9039 } else
9040 break;
9041 }
9042
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009043 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00009044 NewPtrTy = PointerType::getUnqual(SrcETy);
9045 }
9046 }
9047
9048
Chris Lattner00ae5132008-01-13 23:50:23 +00009049 // If the memcpy/memmove provides better alignment info than we can
9050 // infer, use it.
9051 SrcAlign = std::max(SrcAlign, CopyAlign);
9052 DstAlign = std::max(DstAlign, CopyAlign);
9053
9054 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9055 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009056 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9057 InsertNewInstBefore(L, *MI);
9058 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9059
9060 // Set the size of the copy to 0, it will be deleted on the next iteration.
9061 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9062 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009063}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009064
Chris Lattner5af8a912008-04-30 06:39:11 +00009065Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9066 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9067 if (MI->getAlignment()->getZExtValue() < Alignment) {
9068 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9069 return MI;
9070 }
9071
9072 // Extract the length and alignment and fill if they are constant.
9073 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9074 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9075 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9076 return 0;
9077 uint64_t Len = LenC->getZExtValue();
9078 Alignment = MI->getAlignment()->getZExtValue();
9079
9080 // If the length is zero, this is a no-op
9081 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9082
9083 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9084 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9085 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9086
9087 Value *Dest = MI->getDest();
9088 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9089
9090 // Alignment 0 is identity for alignment 1 for memset, but not store.
9091 if (Alignment == 0) Alignment = 1;
9092
9093 // Extract the fill value and store.
9094 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9095 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9096 Alignment), *MI);
9097
9098 // Set the size of the copy to 0, it will be deleted on the next iteration.
9099 MI->setLength(Constant::getNullValue(LenC->getType()));
9100 return MI;
9101 }
9102
9103 return 0;
9104}
9105
9106
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009107/// visitCallInst - CallInst simplification. This mostly only handles folding
9108/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9109/// the heavy lifting.
9110///
9111Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9112 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9113 if (!II) return visitCallSite(&CI);
9114
9115 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9116 // visitCallSite.
9117 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9118 bool Changed = false;
9119
9120 // memmove/cpy/set of zero bytes is a noop.
9121 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9122 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9123
9124 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9125 if (CI->getZExtValue() == 1) {
9126 // Replace the instruction with just byte operations. We would
9127 // transform other cases to loads/stores, but we don't know if
9128 // alignment is sufficient.
9129 }
9130 }
9131
9132 // If we have a memmove and the source operation is a constant global,
9133 // then the source and dest pointers can't alias, so we can change this
9134 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009135 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009136 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9137 if (GVSrc->isConstant()) {
9138 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00009139 Intrinsic::ID MemCpyID;
9140 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9141 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009142 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00009143 MemCpyID = Intrinsic::memcpy_i64;
9144 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009145 Changed = true;
9146 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009147
9148 // memmove(x,x,size) -> noop.
9149 if (MMI->getSource() == MMI->getDest())
9150 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009151 }
9152
9153 // If we can determine a pointer alignment that is bigger than currently
9154 // set, update the alignment.
9155 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009156 if (Instruction *I = SimplifyMemTransfer(MI))
9157 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009158 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9159 if (Instruction *I = SimplifyMemSet(MSI))
9160 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009161 }
9162
9163 if (Changed) return II;
9164 } else {
9165 switch (II->getIntrinsicID()) {
9166 default: break;
9167 case Intrinsic::ppc_altivec_lvx:
9168 case Intrinsic::ppc_altivec_lvxl:
9169 case Intrinsic::x86_sse_loadu_ps:
9170 case Intrinsic::x86_sse2_loadu_pd:
9171 case Intrinsic::x86_sse2_loadu_dq:
9172 // Turn PPC lvx -> load if the pointer is known aligned.
9173 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009174 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00009175 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9176 PointerType::getUnqual(II->getType()),
9177 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009178 return new LoadInst(Ptr);
9179 }
9180 break;
9181 case Intrinsic::ppc_altivec_stvx:
9182 case Intrinsic::ppc_altivec_stvxl:
9183 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009184 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00009185 const Type *OpPtrTy =
9186 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00009187 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009188 return new StoreInst(II->getOperand(1), Ptr);
9189 }
9190 break;
9191 case Intrinsic::x86_sse_storeu_ps:
9192 case Intrinsic::x86_sse2_storeu_pd:
9193 case Intrinsic::x86_sse2_storeu_dq:
9194 case Intrinsic::x86_sse2_storel_dq:
9195 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009196 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00009197 const Type *OpPtrTy =
9198 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00009199 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009200 return new StoreInst(II->getOperand(2), Ptr);
9201 }
9202 break;
9203
9204 case Intrinsic::x86_sse_cvttss2si: {
9205 // These intrinsics only demands the 0th element of its input vector. If
9206 // we can simplify the input based on that, do so now.
9207 uint64_t UndefElts;
9208 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9209 UndefElts)) {
9210 II->setOperand(1, V);
9211 return II;
9212 }
9213 break;
9214 }
9215
9216 case Intrinsic::ppc_altivec_vperm:
9217 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9218 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9219 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9220
9221 // Check that all of the elements are integer constants or undefs.
9222 bool AllEltsOk = true;
9223 for (unsigned i = 0; i != 16; ++i) {
9224 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9225 !isa<UndefValue>(Mask->getOperand(i))) {
9226 AllEltsOk = false;
9227 break;
9228 }
9229 }
9230
9231 if (AllEltsOk) {
9232 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00009233 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9234 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009235 Value *Result = UndefValue::get(Op0->getType());
9236
9237 // Only extract each element once.
9238 Value *ExtractedElts[32];
9239 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9240
9241 for (unsigned i = 0; i != 16; ++i) {
9242 if (isa<UndefValue>(Mask->getOperand(i)))
9243 continue;
9244 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9245 Idx &= 31; // Match the hardware behavior.
9246
9247 if (ExtractedElts[Idx] == 0) {
9248 Instruction *Elt =
9249 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9250 InsertNewInstBefore(Elt, CI);
9251 ExtractedElts[Idx] = Elt;
9252 }
9253
9254 // Insert this value into the result vector.
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009255 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9256 i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009257 InsertNewInstBefore(cast<Instruction>(Result), CI);
9258 }
Gabor Greifa645dd32008-05-16 19:29:10 +00009259 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009260 }
9261 }
9262 break;
9263
9264 case Intrinsic::stackrestore: {
9265 // If the save is right next to the restore, remove the restore. This can
9266 // happen when variable allocas are DCE'd.
9267 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9268 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9269 BasicBlock::iterator BI = SS;
9270 if (&*++BI == II)
9271 return EraseInstFromFunction(CI);
9272 }
9273 }
9274
Chris Lattner416d91c2008-02-18 06:12:38 +00009275 // Scan down this block to see if there is another stack restore in the
9276 // same block without an intervening call/alloca.
9277 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009278 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00009279 bool CannotRemove = false;
9280 for (++BI; &*BI != TI; ++BI) {
9281 if (isa<AllocaInst>(BI)) {
9282 CannotRemove = true;
9283 break;
9284 }
9285 if (isa<CallInst>(BI)) {
9286 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009287 CannotRemove = true;
9288 break;
9289 }
Chris Lattner416d91c2008-02-18 06:12:38 +00009290 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009291 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00009292 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009293 }
Chris Lattner416d91c2008-02-18 06:12:38 +00009294
9295 // If the stack restore is in a return/unwind block and if there are no
9296 // allocas or calls between the restore and the return, nuke the restore.
9297 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9298 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009299 break;
9300 }
9301 }
9302 }
9303
9304 return visitCallSite(II);
9305}
9306
9307// InvokeInst simplification
9308//
9309Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9310 return visitCallSite(&II);
9311}
9312
Dale Johannesen96021832008-04-25 21:16:07 +00009313/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9314/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009315static bool isSafeToEliminateVarargsCast(const CallSite CS,
9316 const CastInst * const CI,
9317 const TargetData * const TD,
9318 const int ix) {
9319 if (!CI->isLosslessCast())
9320 return false;
9321
9322 // The size of ByVal arguments is derived from the type, so we
9323 // can't change to a type with a different size. If the size were
9324 // passed explicitly we could avoid this check.
9325 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9326 return true;
9327
9328 const Type* SrcTy =
9329 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9330 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9331 if (!SrcTy->isSized() || !DstTy->isSized())
9332 return false;
9333 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9334 return false;
9335 return true;
9336}
9337
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009338// visitCallSite - Improvements for call and invoke instructions.
9339//
9340Instruction *InstCombiner::visitCallSite(CallSite CS) {
9341 bool Changed = false;
9342
9343 // If the callee is a constexpr cast of a function, attempt to move the cast
9344 // to the arguments of the call/invoke.
9345 if (transformConstExprCastCall(CS)) return 0;
9346
9347 Value *Callee = CS.getCalledValue();
9348
9349 if (Function *CalleeF = dyn_cast<Function>(Callee))
9350 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9351 Instruction *OldCall = CS.getInstruction();
9352 // If the call and callee calling conventions don't match, this call must
9353 // be unreachable, as the call is undefined.
9354 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009355 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9356 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009357 if (!OldCall->use_empty())
9358 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9359 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9360 return EraseInstFromFunction(*OldCall);
9361 return 0;
9362 }
9363
9364 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9365 // This instruction is not reachable, just remove it. We insert a store to
9366 // undef so that we know that this code is not reachable, despite the fact
9367 // that we can't modify the CFG here.
9368 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009369 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009370 CS.getInstruction());
9371
9372 if (!CS.getInstruction()->use_empty())
9373 CS.getInstruction()->
9374 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9375
9376 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9377 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009378 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9379 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009380 }
9381 return EraseInstFromFunction(*CS.getInstruction());
9382 }
9383
Duncan Sands74833f22007-09-17 10:26:40 +00009384 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9385 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9386 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9387 return transformCallThroughTrampoline(CS);
9388
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009389 const PointerType *PTy = cast<PointerType>(Callee->getType());
9390 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9391 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009392 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009393 // See if we can optimize any arguments passed through the varargs area of
9394 // the call.
9395 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009396 E = CS.arg_end(); I != E; ++I, ++ix) {
9397 CastInst *CI = dyn_cast<CastInst>(*I);
9398 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9399 *I = CI->getOperand(0);
9400 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009401 }
Dale Johannesen35615462008-04-23 18:34:37 +00009402 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009403 }
9404
Duncan Sands2937e352007-12-19 21:13:37 +00009405 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009406 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009407 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009408 Changed = true;
9409 }
9410
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009411 return Changed ? CS.getInstruction() : 0;
9412}
9413
9414// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9415// attempt to move the cast to the arguments of the call/invoke.
9416//
9417bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9418 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9419 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9420 if (CE->getOpcode() != Instruction::BitCast ||
9421 !isa<Function>(CE->getOperand(0)))
9422 return false;
9423 Function *Callee = cast<Function>(CE->getOperand(0));
9424 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009425 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009426
9427 // Okay, this is a cast from a function to a different type. Unless doing so
9428 // would cause a type conversion of one of our arguments, change this call to
9429 // be a direct call with arguments casted to the appropriate types.
9430 //
9431 const FunctionType *FT = Callee->getFunctionType();
9432 const Type *OldRetTy = Caller->getType();
9433
Devang Pateld091d322008-03-11 18:04:06 +00009434 if (isa<StructType>(FT->getReturnType()))
9435 return false; // TODO: Handle multiple return values.
9436
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009437 // Check to see if we are changing the return type...
9438 if (OldRetTy != FT->getReturnType()) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009439 if (Callee->isDeclaration() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009440 // Conversion is ok if changing from pointer to int of same size.
9441 !(isa<PointerType>(FT->getReturnType()) &&
9442 TD->getIntPtrType() == OldRetTy))
9443 return false; // Cannot transform this return value.
9444
Duncan Sands5c489582008-01-06 10:12:28 +00009445 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009446 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00009447 FT->getReturnType() != Type::VoidTy &&
9448 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009449 return false; // Cannot transform this return value.
9450
Chris Lattner1c8733e2008-03-12 17:45:29 +00009451 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9452 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009453 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9454 return false; // Attribute not compatible with transformed value.
9455 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009456
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009457 // If the callsite is an invoke instruction, and the return value is used by
9458 // a PHI node in a successor, we cannot change the return type of the call
9459 // because there is no place to put the cast instruction (without breaking
9460 // the critical edge). Bail out in this case.
9461 if (!Caller->use_empty())
9462 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9463 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9464 UI != E; ++UI)
9465 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9466 if (PN->getParent() == II->getNormalDest() ||
9467 PN->getParent() == II->getUnwindDest())
9468 return false;
9469 }
9470
9471 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9472 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9473
9474 CallSite::arg_iterator AI = CS.arg_begin();
9475 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9476 const Type *ParamTy = FT->getParamType(i);
9477 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009478
9479 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009480 return false; // Cannot transform this parameter value.
9481
Chris Lattner1c8733e2008-03-12 17:45:29 +00009482 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9483 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009484
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009485 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00009486 // Some conversions are safe even if we do not have a body.
9487 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009488 bool isConvertible = ActTy == ParamTy ||
9489 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9490 (ParamTy->isInteger() && ActTy->isInteger() &&
9491 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9492 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9493 && c->getValue().isStrictlyPositive());
9494 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009495 }
9496
9497 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9498 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009499 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009500
Chris Lattner1c8733e2008-03-12 17:45:29 +00009501 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9502 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009503 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009504 // won't be dropping them. Check that these extra arguments have attributes
9505 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009506 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9507 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009508 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009509 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00009510 if (PAttrs & ParamAttr::VarArgsIncompatible)
9511 return false;
9512 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009513
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009514 // Okay, we decided that this is a safe thing to do: go ahead and start
9515 // inserting cast instructions as necessary...
9516 std::vector<Value*> Args;
9517 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009518 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009519 attrVec.reserve(NumCommonArgs);
9520
9521 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009522 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00009523
9524 // If the return value is not being used, the type may not be compatible
9525 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009526 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00009527
9528 // Add the new return attributes.
9529 if (RAttrs)
9530 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009531
9532 AI = CS.arg_begin();
9533 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9534 const Type *ParamTy = FT->getParamType(i);
9535 if ((*AI)->getType() == ParamTy) {
9536 Args.push_back(*AI);
9537 } else {
9538 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9539 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009540 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009541 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9542 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009543
9544 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009545 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00009546 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009547 }
9548
9549 // If the function takes more arguments than the call was taking, add them
9550 // now...
9551 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9552 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9553
9554 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009555 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009556 if (!FT->isVarArg()) {
9557 cerr << "WARNING: While resolving call to function '"
9558 << Callee->getName() << "' arguments were dropped!\n";
9559 } else {
9560 // Add all of the arguments in their promoted form to the arg list...
9561 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9562 const Type *PTy = getPromotedType((*AI)->getType());
9563 if (PTy != (*AI)->getType()) {
9564 // Must promote to pass through va_arg area!
9565 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9566 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009567 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009568 InsertNewInstBefore(Cast, *Caller);
9569 Args.push_back(Cast);
9570 } else {
9571 Args.push_back(*AI);
9572 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009573
Duncan Sands4ced1f82008-01-13 08:02:44 +00009574 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009575 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00009576 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9577 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009578 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009579 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009580
9581 if (FT->getReturnType() == Type::VoidTy)
9582 Caller->setName(""); // Void type should not have a name.
9583
Chris Lattner1c8733e2008-03-12 17:45:29 +00009584 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009585
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009586 Instruction *NC;
9587 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009588 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009589 Args.begin(), Args.end(),
9590 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009591 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009592 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009593 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009594 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9595 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009596 CallInst *CI = cast<CallInst>(Caller);
9597 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009598 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009599 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009600 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009601 }
9602
9603 // Insert a cast of the return type as necessary.
9604 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009605 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009606 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009607 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009608 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009609 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009610
9611 // If this is an invoke instruction, we should insert it after the first
9612 // non-phi, instruction in the normal successor block.
9613 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00009614 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009615 InsertNewInstBefore(NC, *I);
9616 } else {
9617 // Otherwise, it's a call, just insert cast right after the call instr
9618 InsertNewInstBefore(NC, *Caller);
9619 }
9620 AddUsersToWorkList(*Caller);
9621 } else {
9622 NV = UndefValue::get(Caller->getType());
9623 }
9624 }
9625
9626 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9627 Caller->replaceAllUsesWith(NV);
9628 Caller->eraseFromParent();
9629 RemoveFromWorkList(Caller);
9630 return true;
9631}
9632
Duncan Sands74833f22007-09-17 10:26:40 +00009633// transformCallThroughTrampoline - Turn a call to a function created by the
9634// init_trampoline intrinsic into a direct call to the underlying function.
9635//
9636Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9637 Value *Callee = CS.getCalledValue();
9638 const PointerType *PTy = cast<PointerType>(Callee->getType());
9639 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009640 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009641
9642 // If the call already has the 'nest' attribute somewhere then give up -
9643 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009644 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009645 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009646
9647 IntrinsicInst *Tramp =
9648 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9649
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009650 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009651 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9652 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9653
Chris Lattner1c8733e2008-03-12 17:45:29 +00009654 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9655 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009656 unsigned NestIdx = 1;
9657 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009658 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009659
9660 // Look for a parameter marked with the 'nest' attribute.
9661 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9662 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009663 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009664 // Record the parameter type and any other attributes.
9665 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009666 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009667 break;
9668 }
9669
9670 if (NestTy) {
9671 Instruction *Caller = CS.getInstruction();
9672 std::vector<Value*> NewArgs;
9673 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9674
Chris Lattner1c8733e2008-03-12 17:45:29 +00009675 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9676 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009677
Duncan Sands74833f22007-09-17 10:26:40 +00009678 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009679 // mean appending it. Likewise for attributes.
9680
9681 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009682 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9683 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009684
Duncan Sands74833f22007-09-17 10:26:40 +00009685 {
9686 unsigned Idx = 1;
9687 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9688 do {
9689 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009690 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009691 Value *NestVal = Tramp->getOperand(3);
9692 if (NestVal->getType() != NestTy)
9693 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9694 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009695 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009696 }
9697
9698 if (I == E)
9699 break;
9700
Duncan Sands48b81112008-01-14 19:52:09 +00009701 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009702 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009703 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009704 NewAttrs.push_back
9705 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009706
9707 ++Idx, ++I;
9708 } while (1);
9709 }
9710
9711 // The trampoline may have been bitcast to a bogus type (FTy).
9712 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009713 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009714
Duncan Sands74833f22007-09-17 10:26:40 +00009715 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009716 NewTypes.reserve(FTy->getNumParams()+1);
9717
Duncan Sands74833f22007-09-17 10:26:40 +00009718 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009719 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009720 {
9721 unsigned Idx = 1;
9722 FunctionType::param_iterator I = FTy->param_begin(),
9723 E = FTy->param_end();
9724
9725 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009726 if (Idx == NestIdx)
9727 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009728 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009729
9730 if (I == E)
9731 break;
9732
Duncan Sands48b81112008-01-14 19:52:09 +00009733 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009734 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009735
9736 ++Idx, ++I;
9737 } while (1);
9738 }
9739
9740 // Replace the trampoline call with a direct call. Let the generic
9741 // code sort out any function type mismatches.
9742 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009743 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009744 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9745 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009746 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009747
9748 Instruction *NewCaller;
9749 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009750 NewCaller = InvokeInst::Create(NewCallee,
9751 II->getNormalDest(), II->getUnwindDest(),
9752 NewArgs.begin(), NewArgs.end(),
9753 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009754 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009755 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009756 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009757 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9758 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009759 if (cast<CallInst>(Caller)->isTailCall())
9760 cast<CallInst>(NewCaller)->setTailCall();
9761 cast<CallInst>(NewCaller)->
9762 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009763 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009764 }
9765 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9766 Caller->replaceAllUsesWith(NewCaller);
9767 Caller->eraseFromParent();
9768 RemoveFromWorkList(Caller);
9769 return 0;
9770 }
9771 }
9772
9773 // Replace the trampoline call with a direct call. Since there is no 'nest'
9774 // parameter, there is no need to adjust the argument list. Let the generic
9775 // code sort out any function type mismatches.
9776 Constant *NewCallee =
9777 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9778 CS.setCalledFunction(NewCallee);
9779 return CS.getInstruction();
9780}
9781
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009782/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9783/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9784/// and a single binop.
9785Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9786 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9787 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9788 isa<CmpInst>(FirstInst));
9789 unsigned Opc = FirstInst->getOpcode();
9790 Value *LHSVal = FirstInst->getOperand(0);
9791 Value *RHSVal = FirstInst->getOperand(1);
9792
9793 const Type *LHSType = LHSVal->getType();
9794 const Type *RHSType = RHSVal->getType();
9795
9796 // Scan to see if all operands are the same opcode, all have one use, and all
9797 // kill their operands (i.e. the operands have one use).
9798 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9799 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9800 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9801 // Verify type of the LHS matches so we don't fold cmp's of different
9802 // types or GEP's with different index types.
9803 I->getOperand(0)->getType() != LHSType ||
9804 I->getOperand(1)->getType() != RHSType)
9805 return 0;
9806
9807 // If they are CmpInst instructions, check their predicates
9808 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9809 if (cast<CmpInst>(I)->getPredicate() !=
9810 cast<CmpInst>(FirstInst)->getPredicate())
9811 return 0;
9812
9813 // Keep track of which operand needs a phi node.
9814 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9815 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9816 }
9817
9818 // Otherwise, this is safe to transform, determine if it is profitable.
9819
9820 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9821 // Indexes are often folded into load/store instructions, so we don't want to
9822 // hide them behind a phi.
9823 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9824 return 0;
9825
9826 Value *InLHS = FirstInst->getOperand(0);
9827 Value *InRHS = FirstInst->getOperand(1);
9828 PHINode *NewLHS = 0, *NewRHS = 0;
9829 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009830 NewLHS = PHINode::Create(LHSType,
9831 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009832 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9833 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9834 InsertNewInstBefore(NewLHS, PN);
9835 LHSVal = NewLHS;
9836 }
9837
9838 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009839 NewRHS = PHINode::Create(RHSType,
9840 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009841 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9842 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9843 InsertNewInstBefore(NewRHS, PN);
9844 RHSVal = NewRHS;
9845 }
9846
9847 // Add all operands to the new PHIs.
9848 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9849 if (NewLHS) {
9850 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9851 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9852 }
9853 if (NewRHS) {
9854 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9855 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9856 }
9857 }
9858
9859 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009860 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009861 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009862 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009863 RHSVal);
9864 else {
9865 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009866 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009867 }
9868}
9869
9870/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9871/// of the block that defines it. This means that it must be obvious the value
9872/// of the load is not changed from the point of the load to the end of the
9873/// block it is in.
9874///
9875/// Finally, it is safe, but not profitable, to sink a load targetting a
9876/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9877/// to a register.
9878static bool isSafeToSinkLoad(LoadInst *L) {
9879 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9880
9881 for (++BBI; BBI != E; ++BBI)
9882 if (BBI->mayWriteToMemory())
9883 return false;
9884
9885 // Check for non-address taken alloca. If not address-taken already, it isn't
9886 // profitable to do this xform.
9887 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9888 bool isAddressTaken = false;
9889 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9890 UI != E; ++UI) {
9891 if (isa<LoadInst>(UI)) continue;
9892 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9893 // If storing TO the alloca, then the address isn't taken.
9894 if (SI->getOperand(1) == AI) continue;
9895 }
9896 isAddressTaken = true;
9897 break;
9898 }
9899
9900 if (!isAddressTaken)
9901 return false;
9902 }
9903
9904 return true;
9905}
9906
9907
9908// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9909// operator and they all are only used by the PHI, PHI together their
9910// inputs, and do the operation once, to the result of the PHI.
9911Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9912 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9913
9914 // Scan the instruction, looking for input operations that can be folded away.
9915 // If all input operands to the phi are the same instruction (e.g. a cast from
9916 // the same type or "+42") we can pull the operation through the PHI, reducing
9917 // code size and simplifying code.
9918 Constant *ConstantOp = 0;
9919 const Type *CastSrcTy = 0;
9920 bool isVolatile = false;
9921 if (isa<CastInst>(FirstInst)) {
9922 CastSrcTy = FirstInst->getOperand(0)->getType();
9923 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9924 // Can fold binop, compare or shift here if the RHS is a constant,
9925 // otherwise call FoldPHIArgBinOpIntoPHI.
9926 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9927 if (ConstantOp == 0)
9928 return FoldPHIArgBinOpIntoPHI(PN);
9929 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9930 isVolatile = LI->isVolatile();
9931 // We can't sink the load if the loaded value could be modified between the
9932 // load and the PHI.
9933 if (LI->getParent() != PN.getIncomingBlock(0) ||
9934 !isSafeToSinkLoad(LI))
9935 return 0;
9936 } else if (isa<GetElementPtrInst>(FirstInst)) {
9937 if (FirstInst->getNumOperands() == 2)
9938 return FoldPHIArgBinOpIntoPHI(PN);
9939 // Can't handle general GEPs yet.
9940 return 0;
9941 } else {
9942 return 0; // Cannot fold this operation.
9943 }
9944
9945 // Check to see if all arguments are the same operation.
9946 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9947 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9948 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9949 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9950 return 0;
9951 if (CastSrcTy) {
9952 if (I->getOperand(0)->getType() != CastSrcTy)
9953 return 0; // Cast operation must match.
9954 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9955 // We can't sink the load if the loaded value could be modified between
9956 // the load and the PHI.
9957 if (LI->isVolatile() != isVolatile ||
9958 LI->getParent() != PN.getIncomingBlock(i) ||
9959 !isSafeToSinkLoad(LI))
9960 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009961
9962 // If the PHI is volatile and its block has multiple successors, sinking
9963 // it would remove a load of the volatile value from the path through the
9964 // other successor.
9965 if (isVolatile &&
9966 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9967 return 0;
9968
9969
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009970 } else if (I->getOperand(1) != ConstantOp) {
9971 return 0;
9972 }
9973 }
9974
9975 // Okay, they are all the same operation. Create a new PHI node of the
9976 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009977 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9978 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009979 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9980
9981 Value *InVal = FirstInst->getOperand(0);
9982 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9983
9984 // Add all operands to the new PHI.
9985 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9986 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9987 if (NewInVal != InVal)
9988 InVal = 0;
9989 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9990 }
9991
9992 Value *PhiVal;
9993 if (InVal) {
9994 // The new PHI unions all of the same values together. This is really
9995 // common, so we handle it intelligently here for compile-time speed.
9996 PhiVal = InVal;
9997 delete NewPN;
9998 } else {
9999 InsertNewInstBefore(NewPN, PN);
10000 PhiVal = NewPN;
10001 }
10002
10003 // Insert and return the new operation.
10004 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010005 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010006 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010007 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010008 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010009 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010010 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010011 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10012
10013 // If this was a volatile load that we are merging, make sure to loop through
10014 // and mark all the input loads as non-volatile. If we don't do this, we will
10015 // insert a new volatile load and the old ones will not be deletable.
10016 if (isVolatile)
10017 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10018 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10019
10020 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010021}
10022
10023/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10024/// that is dead.
10025static bool DeadPHICycle(PHINode *PN,
10026 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10027 if (PN->use_empty()) return true;
10028 if (!PN->hasOneUse()) return false;
10029
10030 // Remember this node, and if we find the cycle, return.
10031 if (!PotentiallyDeadPHIs.insert(PN))
10032 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010033
10034 // Don't scan crazily complex things.
10035 if (PotentiallyDeadPHIs.size() == 16)
10036 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010037
10038 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10039 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10040
10041 return false;
10042}
10043
Chris Lattner27b695d2007-11-06 21:52:06 +000010044/// PHIsEqualValue - Return true if this phi node is always equal to
10045/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10046/// z = some value; x = phi (y, z); y = phi (x, z)
10047static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10048 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10049 // See if we already saw this PHI node.
10050 if (!ValueEqualPHIs.insert(PN))
10051 return true;
10052
10053 // Don't scan crazily complex things.
10054 if (ValueEqualPHIs.size() == 16)
10055 return false;
10056
10057 // Scan the operands to see if they are either phi nodes or are equal to
10058 // the value.
10059 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10060 Value *Op = PN->getIncomingValue(i);
10061 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10062 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10063 return false;
10064 } else if (Op != NonPhiInVal)
10065 return false;
10066 }
10067
10068 return true;
10069}
10070
10071
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010072// PHINode simplification
10073//
10074Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10075 // If LCSSA is around, don't mess with Phi nodes
10076 if (MustPreserveLCSSA) return 0;
10077
10078 if (Value *V = PN.hasConstantValue())
10079 return ReplaceInstUsesWith(PN, V);
10080
10081 // If all PHI operands are the same operation, pull them through the PHI,
10082 // reducing code size.
10083 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10084 PN.getIncomingValue(0)->hasOneUse())
10085 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10086 return Result;
10087
10088 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10089 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10090 // PHI)... break the cycle.
10091 if (PN.hasOneUse()) {
10092 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10093 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10094 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10095 PotentiallyDeadPHIs.insert(&PN);
10096 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10097 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10098 }
10099
10100 // If this phi has a single use, and if that use just computes a value for
10101 // the next iteration of a loop, delete the phi. This occurs with unused
10102 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10103 // common case here is good because the only other things that catch this
10104 // are induction variable analysis (sometimes) and ADCE, which is only run
10105 // late.
10106 if (PHIUser->hasOneUse() &&
10107 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10108 PHIUser->use_back() == &PN) {
10109 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10110 }
10111 }
10112
Chris Lattner27b695d2007-11-06 21:52:06 +000010113 // We sometimes end up with phi cycles that non-obviously end up being the
10114 // same value, for example:
10115 // z = some value; x = phi (y, z); y = phi (x, z)
10116 // where the phi nodes don't necessarily need to be in the same block. Do a
10117 // quick check to see if the PHI node only contains a single non-phi value, if
10118 // so, scan to see if the phi cycle is actually equal to that value.
10119 {
10120 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10121 // Scan for the first non-phi operand.
10122 while (InValNo != NumOperandVals &&
10123 isa<PHINode>(PN.getIncomingValue(InValNo)))
10124 ++InValNo;
10125
10126 if (InValNo != NumOperandVals) {
10127 Value *NonPhiInVal = PN.getOperand(InValNo);
10128
10129 // Scan the rest of the operands to see if there are any conflicts, if so
10130 // there is no need to recursively scan other phis.
10131 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10132 Value *OpVal = PN.getIncomingValue(InValNo);
10133 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10134 break;
10135 }
10136
10137 // If we scanned over all operands, then we have one unique value plus
10138 // phi values. Scan PHI nodes to see if they all merge in each other or
10139 // the value.
10140 if (InValNo == NumOperandVals) {
10141 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10142 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10143 return ReplaceInstUsesWith(PN, NonPhiInVal);
10144 }
10145 }
10146 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010147 return 0;
10148}
10149
10150static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10151 Instruction *InsertPoint,
10152 InstCombiner *IC) {
10153 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10154 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10155 // We must cast correctly to the pointer type. Ensure that we
10156 // sign extend the integer value if it is smaller as this is
10157 // used for address computation.
10158 Instruction::CastOps opcode =
10159 (VTySize < PtrSize ? Instruction::SExt :
10160 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10161 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10162}
10163
10164
10165Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10166 Value *PtrOp = GEP.getOperand(0);
10167 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10168 // If so, eliminate the noop.
10169 if (GEP.getNumOperands() == 1)
10170 return ReplaceInstUsesWith(GEP, PtrOp);
10171
10172 if (isa<UndefValue>(GEP.getOperand(0)))
10173 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10174
10175 bool HasZeroPointerIndex = false;
10176 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10177 HasZeroPointerIndex = C->isNullValue();
10178
10179 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10180 return ReplaceInstUsesWith(GEP, PtrOp);
10181
10182 // Eliminate unneeded casts for indices.
10183 bool MadeChange = false;
10184
10185 gep_type_iterator GTI = gep_type_begin(GEP);
10186 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
10187 if (isa<SequentialType>(*GTI)) {
10188 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
10189 if (CI->getOpcode() == Instruction::ZExt ||
10190 CI->getOpcode() == Instruction::SExt) {
10191 const Type *SrcTy = CI->getOperand(0)->getType();
10192 // We can eliminate a cast from i32 to i64 iff the target
10193 // is a 32-bit pointer target.
10194 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10195 MadeChange = true;
10196 GEP.setOperand(i, CI->getOperand(0));
10197 }
10198 }
10199 }
10200 // If we are using a wider index than needed for this platform, shrink it
10201 // to what we need. If the incoming value needs a cast instruction,
10202 // insert it. This explicit cast can make subsequent optimizations more
10203 // obvious.
10204 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010205 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010206 if (Constant *C = dyn_cast<Constant>(Op)) {
10207 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
10208 MadeChange = true;
10209 } else {
10210 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10211 GEP);
10212 GEP.setOperand(i, Op);
10213 MadeChange = true;
10214 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010215 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010216 }
10217 }
10218 if (MadeChange) return &GEP;
10219
10220 // If this GEP instruction doesn't move the pointer, and if the input operand
10221 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10222 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +000010223 if (GEP.hasAllZeroIndices()) {
10224 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10225 // If the bitcast is of an allocation, and the allocation will be
10226 // converted to match the type of the cast, don't touch this.
10227 if (isa<AllocationInst>(BCI->getOperand(0))) {
10228 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +000010229 if (Instruction *I = visitBitCast(*BCI)) {
10230 if (I != BCI) {
10231 I->takeName(BCI);
10232 BCI->getParent()->getInstList().insert(BCI, I);
10233 ReplaceInstUsesWith(*BCI, I);
10234 }
Chris Lattnerc59171a2007-10-12 05:30:59 +000010235 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +000010236 }
Chris Lattnerc59171a2007-10-12 05:30:59 +000010237 }
10238 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10239 }
10240 }
10241
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010242 // Combine Indices - If the source pointer to this getelementptr instruction
10243 // is a getelementptr instruction, combine the indices of the two
10244 // getelementptr instructions into a single instruction.
10245 //
10246 SmallVector<Value*, 8> SrcGEPOperands;
10247 if (User *Src = dyn_castGetElementPtr(PtrOp))
10248 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10249
10250 if (!SrcGEPOperands.empty()) {
10251 // Note that if our source is a gep chain itself that we wait for that
10252 // chain to be resolved before we perform this transformation. This
10253 // avoids us creating a TON of code in some cases.
10254 //
10255 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10256 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10257 return 0; // Wait until our source is folded to completion.
10258
10259 SmallVector<Value*, 8> Indices;
10260
10261 // Find out whether the last index in the source GEP is a sequential idx.
10262 bool EndsWithSequential = false;
10263 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10264 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10265 EndsWithSequential = !isa<StructType>(*I);
10266
10267 // Can we combine the two pointer arithmetics offsets?
10268 if (EndsWithSequential) {
10269 // Replace: gep (gep %P, long B), long A, ...
10270 // With: T = long A+B; gep %P, T, ...
10271 //
10272 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10273 if (SO1 == Constant::getNullValue(SO1->getType())) {
10274 Sum = GO1;
10275 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10276 Sum = SO1;
10277 } else {
10278 // If they aren't the same type, convert both to an integer of the
10279 // target's pointer size.
10280 if (SO1->getType() != GO1->getType()) {
10281 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10282 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10283 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10284 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10285 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010286 unsigned PS = TD->getPointerSizeInBits();
10287 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010288 // Convert GO1 to SO1's type.
10289 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10290
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010291 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010292 // Convert SO1 to GO1's type.
10293 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10294 } else {
10295 const Type *PT = TD->getIntPtrType();
10296 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10297 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10298 }
10299 }
10300 }
10301 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10302 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10303 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000010304 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010305 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10306 }
10307 }
10308
10309 // Recycle the GEP we already have if possible.
10310 if (SrcGEPOperands.size() == 2) {
10311 GEP.setOperand(0, SrcGEPOperands[0]);
10312 GEP.setOperand(1, Sum);
10313 return &GEP;
10314 } else {
10315 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10316 SrcGEPOperands.end()-1);
10317 Indices.push_back(Sum);
10318 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10319 }
10320 } else if (isa<Constant>(*GEP.idx_begin()) &&
10321 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10322 SrcGEPOperands.size() != 1) {
10323 // Otherwise we can do the fold if the first index of the GEP is a zero
10324 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10325 SrcGEPOperands.end());
10326 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10327 }
10328
10329 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010330 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10331 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010332
10333 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10334 // GEP of global variable. If all of the indices for this GEP are
10335 // constants, we can promote this to a constexpr instead of an instruction.
10336
10337 // Scan for nonconstants...
10338 SmallVector<Constant*, 8> Indices;
10339 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10340 for (; I != E && isa<Constant>(*I); ++I)
10341 Indices.push_back(cast<Constant>(*I));
10342
10343 if (I == E) { // If they are all constants...
10344 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10345 &Indices[0],Indices.size());
10346
10347 // Replace all uses of the GEP with the new constexpr...
10348 return ReplaceInstUsesWith(GEP, CE);
10349 }
10350 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10351 if (!isa<PointerType>(X->getType())) {
10352 // Not interesting. Source pointer must be a cast from pointer.
10353 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010354 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10355 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010356 //
10357 // This occurs when the program declares an array extern like "int X[];"
10358 //
10359 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10360 const PointerType *XTy = cast<PointerType>(X->getType());
10361 if (const ArrayType *XATy =
10362 dyn_cast<ArrayType>(XTy->getElementType()))
10363 if (const ArrayType *CATy =
10364 dyn_cast<ArrayType>(CPTy->getElementType()))
10365 if (CATy->getElementType() == XATy->getElementType()) {
10366 // At this point, we know that the cast source type is a pointer
10367 // to an array of the same type as the destination pointer
10368 // array. Because the array type is never stepped over (there
10369 // is a leading zero) we can fold the cast into this GEP.
10370 GEP.setOperand(0, X);
10371 return &GEP;
10372 }
10373 } else if (GEP.getNumOperands() == 2) {
10374 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010375 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10376 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010377 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10378 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10379 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010380 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10381 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010382 Value *Idx[2];
10383 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10384 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010385 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010386 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010387 // V and GEP are both pointer types --> BitCast
10388 return new BitCastInst(V, GEP.getType());
10389 }
10390
10391 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010392 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010393 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010394 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010395
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010396 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010397 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010398 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010399
10400 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10401 // allow either a mul, shift, or constant here.
10402 Value *NewIdx = 0;
10403 ConstantInt *Scale = 0;
10404 if (ArrayEltSize == 1) {
10405 NewIdx = GEP.getOperand(1);
10406 Scale = ConstantInt::get(NewIdx->getType(), 1);
10407 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10408 NewIdx = ConstantInt::get(CI->getType(), 1);
10409 Scale = CI;
10410 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10411 if (Inst->getOpcode() == Instruction::Shl &&
10412 isa<ConstantInt>(Inst->getOperand(1))) {
10413 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10414 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10415 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10416 NewIdx = Inst->getOperand(0);
10417 } else if (Inst->getOpcode() == Instruction::Mul &&
10418 isa<ConstantInt>(Inst->getOperand(1))) {
10419 Scale = cast<ConstantInt>(Inst->getOperand(1));
10420 NewIdx = Inst->getOperand(0);
10421 }
10422 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010423
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010424 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010425 // out, perform the transformation. Note, we don't know whether Scale is
10426 // signed or not. We'll use unsigned version of division/modulo
10427 // operation after making sure Scale doesn't have the sign bit set.
10428 if (Scale && Scale->getSExtValue() >= 0LL &&
10429 Scale->getZExtValue() % ArrayEltSize == 0) {
10430 Scale = ConstantInt::get(Scale->getType(),
10431 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010432 if (Scale->getZExtValue() != 1) {
10433 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010434 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010435 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010436 NewIdx = InsertNewInstBefore(Sc, GEP);
10437 }
10438
10439 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010440 Value *Idx[2];
10441 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10442 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010443 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010444 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010445 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10446 // The NewGEP must be pointer typed, so must the old one -> BitCast
10447 return new BitCastInst(NewGEP, GEP.getType());
10448 }
10449 }
10450 }
10451 }
10452
10453 return 0;
10454}
10455
10456Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10457 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010458 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010459 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10460 const Type *NewTy =
10461 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10462 AllocationInst *New = 0;
10463
10464 // Create and insert the replacement instruction...
10465 if (isa<MallocInst>(AI))
10466 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10467 else {
10468 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10469 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10470 }
10471
10472 InsertNewInstBefore(New, AI);
10473
10474 // Scan to the end of the allocation instructions, to skip over a block of
10475 // allocas if possible...
10476 //
10477 BasicBlock::iterator It = New;
10478 while (isa<AllocationInst>(*It)) ++It;
10479
10480 // Now that I is pointing to the first non-allocation-inst in the block,
10481 // insert our getelementptr instruction...
10482 //
10483 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010484 Value *Idx[2];
10485 Idx[0] = NullIdx;
10486 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010487 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10488 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010489
10490 // Now make everything use the getelementptr instead of the original
10491 // allocation.
10492 return ReplaceInstUsesWith(AI, V);
10493 } else if (isa<UndefValue>(AI.getArraySize())) {
10494 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10495 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010496 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010497
10498 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10499 // Note that we only do this for alloca's, because malloc should allocate and
10500 // return a unique pointer, even for a zero byte allocation.
10501 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010502 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010503 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10504
10505 return 0;
10506}
10507
10508Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10509 Value *Op = FI.getOperand(0);
10510
10511 // free undef -> unreachable.
10512 if (isa<UndefValue>(Op)) {
10513 // Insert a new store to null because we cannot modify the CFG here.
10514 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010515 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010516 return EraseInstFromFunction(FI);
10517 }
10518
10519 // If we have 'free null' delete the instruction. This can happen in stl code
10520 // when lots of inlining happens.
10521 if (isa<ConstantPointerNull>(Op))
10522 return EraseInstFromFunction(FI);
10523
10524 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10525 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10526 FI.setOperand(0, CI->getOperand(0));
10527 return &FI;
10528 }
10529
10530 // Change free (gep X, 0,0,0,0) into free(X)
10531 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10532 if (GEPI->hasAllZeroIndices()) {
10533 AddToWorkList(GEPI);
10534 FI.setOperand(0, GEPI->getOperand(0));
10535 return &FI;
10536 }
10537 }
10538
10539 // Change free(malloc) into nothing, if the malloc has a single use.
10540 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10541 if (MI->hasOneUse()) {
10542 EraseInstFromFunction(FI);
10543 return EraseInstFromFunction(*MI);
10544 }
10545
10546 return 0;
10547}
10548
10549
10550/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010551static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010552 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010553 User *CI = cast<User>(LI.getOperand(0));
10554 Value *CastOp = CI->getOperand(0);
10555
Devang Patela0f8ea82007-10-18 19:52:32 +000010556 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10557 // Instead of loading constant c string, use corresponding integer value
10558 // directly if string length is small enough.
10559 const std::string &Str = CE->getOperand(0)->getStringValue();
10560 if (!Str.empty()) {
10561 unsigned len = Str.length();
10562 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10563 unsigned numBits = Ty->getPrimitiveSizeInBits();
10564 // Replace LI with immediate integer store.
10565 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010566 APInt StrVal(numBits, 0);
10567 APInt SingleChar(numBits, 0);
10568 if (TD->isLittleEndian()) {
10569 for (signed i = len-1; i >= 0; i--) {
10570 SingleChar = (uint64_t) Str[i];
10571 StrVal = (StrVal << 8) | SingleChar;
10572 }
10573 } else {
10574 for (unsigned i = 0; i < len; i++) {
10575 SingleChar = (uint64_t) Str[i];
10576 StrVal = (StrVal << 8) | SingleChar;
10577 }
10578 // Append NULL at the end.
10579 SingleChar = 0;
10580 StrVal = (StrVal << 8) | SingleChar;
10581 }
10582 Value *NL = ConstantInt::get(StrVal);
10583 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010584 }
10585 }
10586 }
10587
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010588 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10589 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10590 const Type *SrcPTy = SrcTy->getElementType();
10591
10592 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10593 isa<VectorType>(DestPTy)) {
10594 // If the source is an array, the code below will not succeed. Check to
10595 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10596 // constants.
10597 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10598 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10599 if (ASrcTy->getNumElements() != 0) {
10600 Value *Idxs[2];
10601 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10602 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10603 SrcTy = cast<PointerType>(CastOp->getType());
10604 SrcPTy = SrcTy->getElementType();
10605 }
10606
10607 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10608 isa<VectorType>(SrcPTy)) &&
10609 // Do not allow turning this into a load of an integer, which is then
10610 // casted to a pointer, this pessimizes pointer analysis a lot.
10611 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10612 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10613 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10614
10615 // Okay, we are casting from one integer or pointer type to another of
10616 // the same size. Instead of casting the pointer before the load, cast
10617 // the result of the loaded value.
10618 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10619 CI->getName(),
10620 LI.isVolatile()),LI);
10621 // Now cast the result of the load.
10622 return new BitCastInst(NewLoad, LI.getType());
10623 }
10624 }
10625 }
10626 return 0;
10627}
10628
10629/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10630/// from this value cannot trap. If it is not obviously safe to load from the
10631/// specified pointer, we do a quick local scan of the basic block containing
10632/// ScanFrom, to determine if the address is already accessed.
10633static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010634 // If it is an alloca it is always safe to load from.
10635 if (isa<AllocaInst>(V)) return true;
10636
Duncan Sandse40a94a2007-09-19 10:25:38 +000010637 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010638 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010639 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010640 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010641
10642 // Otherwise, be a little bit agressive by scanning the local block where we
10643 // want to check to see if the pointer is already being loaded or stored
10644 // from/to. If so, the previous load or store would have already trapped,
10645 // so there is no harm doing an extra load (also, CSE will later eliminate
10646 // the load entirely).
10647 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10648
10649 while (BBI != E) {
10650 --BBI;
10651
10652 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10653 if (LI->getOperand(0) == V) return true;
10654 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10655 if (SI->getOperand(1) == V) return true;
10656
10657 }
10658 return false;
10659}
10660
Chris Lattner0270a112007-08-11 18:48:48 +000010661/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10662/// until we find the underlying object a pointer is referring to or something
10663/// we don't understand. Note that the returned pointer may be offset from the
10664/// input, because we ignore GEP indices.
10665static Value *GetUnderlyingObject(Value *Ptr) {
10666 while (1) {
10667 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10668 if (CE->getOpcode() == Instruction::BitCast ||
10669 CE->getOpcode() == Instruction::GetElementPtr)
10670 Ptr = CE->getOperand(0);
10671 else
10672 return Ptr;
10673 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10674 Ptr = BCI->getOperand(0);
10675 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10676 Ptr = GEP->getOperand(0);
10677 } else {
10678 return Ptr;
10679 }
10680 }
10681}
10682
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010683Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10684 Value *Op = LI.getOperand(0);
10685
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010686 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010687 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10688 if (KnownAlign >
10689 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10690 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010691 LI.setAlignment(KnownAlign);
10692
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010693 // load (cast X) --> cast (load X) iff safe
10694 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010695 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010696 return Res;
10697
10698 // None of the following transforms are legal for volatile loads.
10699 if (LI.isVolatile()) return 0;
10700
10701 if (&LI.getParent()->front() != &LI) {
10702 BasicBlock::iterator BBI = &LI; --BBI;
10703 // If the instruction immediately before this is a store to the same
10704 // address, do a simple form of store->load forwarding.
10705 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10706 if (SI->getOperand(1) == LI.getOperand(0))
10707 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10708 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10709 if (LIB->getOperand(0) == LI.getOperand(0))
10710 return ReplaceInstUsesWith(LI, LIB);
10711 }
10712
Christopher Lamb2c175392007-12-29 07:56:53 +000010713 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10714 const Value *GEPI0 = GEPI->getOperand(0);
10715 // TODO: Consider a target hook for valid address spaces for this xform.
10716 if (isa<ConstantPointerNull>(GEPI0) &&
10717 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010718 // Insert a new store to null instruction before the load to indicate
10719 // that this code is not reachable. We do this instead of inserting
10720 // an unreachable instruction directly because we cannot modify the
10721 // CFG.
10722 new StoreInst(UndefValue::get(LI.getType()),
10723 Constant::getNullValue(Op->getType()), &LI);
10724 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10725 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010726 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010727
10728 if (Constant *C = dyn_cast<Constant>(Op)) {
10729 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010730 // TODO: Consider a target hook for valid address spaces for this xform.
10731 if (isa<UndefValue>(C) || (C->isNullValue() &&
10732 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010733 // Insert a new store to null instruction before the load to indicate that
10734 // this code is not reachable. We do this instead of inserting an
10735 // unreachable instruction directly because we cannot modify the CFG.
10736 new StoreInst(UndefValue::get(LI.getType()),
10737 Constant::getNullValue(Op->getType()), &LI);
10738 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10739 }
10740
10741 // Instcombine load (constant global) into the value loaded.
10742 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10743 if (GV->isConstant() && !GV->isDeclaration())
10744 return ReplaceInstUsesWith(LI, GV->getInitializer());
10745
10746 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010747 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010748 if (CE->getOpcode() == Instruction::GetElementPtr) {
10749 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10750 if (GV->isConstant() && !GV->isDeclaration())
10751 if (Constant *V =
10752 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10753 return ReplaceInstUsesWith(LI, V);
10754 if (CE->getOperand(0)->isNullValue()) {
10755 // Insert a new store to null instruction before the load to indicate
10756 // that this code is not reachable. We do this instead of inserting
10757 // an unreachable instruction directly because we cannot modify the
10758 // CFG.
10759 new StoreInst(UndefValue::get(LI.getType()),
10760 Constant::getNullValue(Op->getType()), &LI);
10761 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10762 }
10763
10764 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010765 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010766 return Res;
10767 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010768 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010769 }
Chris Lattner0270a112007-08-11 18:48:48 +000010770
10771 // If this load comes from anywhere in a constant global, and if the global
10772 // is all undef or zero, we know what it loads.
10773 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10774 if (GV->isConstant() && GV->hasInitializer()) {
10775 if (GV->getInitializer()->isNullValue())
10776 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10777 else if (isa<UndefValue>(GV->getInitializer()))
10778 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10779 }
10780 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010781
10782 if (Op->hasOneUse()) {
10783 // Change select and PHI nodes to select values instead of addresses: this
10784 // helps alias analysis out a lot, allows many others simplifications, and
10785 // exposes redundancy in the code.
10786 //
10787 // Note that we cannot do the transformation unless we know that the
10788 // introduced loads cannot trap! Something like this is valid as long as
10789 // the condition is always false: load (select bool %C, int* null, int* %G),
10790 // but it would not be valid if we transformed it to load from null
10791 // unconditionally.
10792 //
10793 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10794 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10795 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10796 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10797 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10798 SI->getOperand(1)->getName()+".val"), LI);
10799 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10800 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010801 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010802 }
10803
10804 // load (select (cond, null, P)) -> load P
10805 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10806 if (C->isNullValue()) {
10807 LI.setOperand(0, SI->getOperand(2));
10808 return &LI;
10809 }
10810
10811 // load (select (cond, P, null)) -> load P
10812 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10813 if (C->isNullValue()) {
10814 LI.setOperand(0, SI->getOperand(1));
10815 return &LI;
10816 }
10817 }
10818 }
10819 return 0;
10820}
10821
10822/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10823/// when possible.
10824static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10825 User *CI = cast<User>(SI.getOperand(1));
10826 Value *CastOp = CI->getOperand(0);
10827
10828 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10829 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10830 const Type *SrcPTy = SrcTy->getElementType();
10831
10832 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10833 // If the source is an array, the code below will not succeed. Check to
10834 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10835 // constants.
10836 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10837 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10838 if (ASrcTy->getNumElements() != 0) {
10839 Value* Idxs[2];
10840 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10841 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10842 SrcTy = cast<PointerType>(CastOp->getType());
10843 SrcPTy = SrcTy->getElementType();
10844 }
10845
10846 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10847 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10848 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10849
10850 // Okay, we are casting from one integer or pointer type to another of
10851 // the same size. Instead of casting the pointer before
10852 // the store, cast the value to be stored.
10853 Value *NewCast;
10854 Value *SIOp0 = SI.getOperand(0);
10855 Instruction::CastOps opcode = Instruction::BitCast;
10856 const Type* CastSrcTy = SIOp0->getType();
10857 const Type* CastDstTy = SrcPTy;
10858 if (isa<PointerType>(CastDstTy)) {
10859 if (CastSrcTy->isInteger())
10860 opcode = Instruction::IntToPtr;
10861 } else if (isa<IntegerType>(CastDstTy)) {
10862 if (isa<PointerType>(SIOp0->getType()))
10863 opcode = Instruction::PtrToInt;
10864 }
10865 if (Constant *C = dyn_cast<Constant>(SIOp0))
10866 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10867 else
10868 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010869 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010870 SI);
10871 return new StoreInst(NewCast, CastOp);
10872 }
10873 }
10874 }
10875 return 0;
10876}
10877
10878Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10879 Value *Val = SI.getOperand(0);
10880 Value *Ptr = SI.getOperand(1);
10881
10882 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10883 EraseInstFromFunction(SI);
10884 ++NumCombined;
10885 return 0;
10886 }
10887
10888 // If the RHS is an alloca with a single use, zapify the store, making the
10889 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010890 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010891 if (isa<AllocaInst>(Ptr)) {
10892 EraseInstFromFunction(SI);
10893 ++NumCombined;
10894 return 0;
10895 }
10896
10897 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10898 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10899 GEP->getOperand(0)->hasOneUse()) {
10900 EraseInstFromFunction(SI);
10901 ++NumCombined;
10902 return 0;
10903 }
10904 }
10905
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010906 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010907 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10908 if (KnownAlign >
10909 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10910 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010911 SI.setAlignment(KnownAlign);
10912
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010913 // Do really simple DSE, to catch cases where there are several consequtive
10914 // stores to the same location, separated by a few arithmetic operations. This
10915 // situation often occurs with bitfield accesses.
10916 BasicBlock::iterator BBI = &SI;
10917 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10918 --ScanInsts) {
10919 --BBI;
10920
10921 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10922 // Prev store isn't volatile, and stores to the same location?
10923 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10924 ++NumDeadStore;
10925 ++BBI;
10926 EraseInstFromFunction(*PrevSI);
10927 continue;
10928 }
10929 break;
10930 }
10931
10932 // If this is a load, we have to stop. However, if the loaded value is from
10933 // the pointer we're loading and is producing the pointer we're storing,
10934 // then *this* store is dead (X = load P; store X -> P).
10935 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010936 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010937 EraseInstFromFunction(SI);
10938 ++NumCombined;
10939 return 0;
10940 }
10941 // Otherwise, this is a load from some other location. Stores before it
10942 // may not be dead.
10943 break;
10944 }
10945
10946 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010947 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010948 break;
10949 }
10950
10951
10952 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10953
10954 // store X, null -> turns into 'unreachable' in SimplifyCFG
10955 if (isa<ConstantPointerNull>(Ptr)) {
10956 if (!isa<UndefValue>(Val)) {
10957 SI.setOperand(0, UndefValue::get(Val->getType()));
10958 if (Instruction *U = dyn_cast<Instruction>(Val))
10959 AddToWorkList(U); // Dropped a use.
10960 ++NumCombined;
10961 }
10962 return 0; // Do not modify these!
10963 }
10964
10965 // store undef, Ptr -> noop
10966 if (isa<UndefValue>(Val)) {
10967 EraseInstFromFunction(SI);
10968 ++NumCombined;
10969 return 0;
10970 }
10971
10972 // If the pointer destination is a cast, see if we can fold the cast into the
10973 // source instead.
10974 if (isa<CastInst>(Ptr))
10975 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10976 return Res;
10977 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10978 if (CE->isCast())
10979 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10980 return Res;
10981
10982
10983 // If this store is the last instruction in the basic block, and if the block
10984 // ends with an unconditional branch, try to move it to the successor block.
10985 BBI = &SI; ++BBI;
10986 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10987 if (BI->isUnconditional())
10988 if (SimplifyStoreAtEndOfBlock(SI))
10989 return 0; // xform done!
10990
10991 return 0;
10992}
10993
10994/// SimplifyStoreAtEndOfBlock - Turn things like:
10995/// if () { *P = v1; } else { *P = v2 }
10996/// into a phi node with a store in the successor.
10997///
10998/// Simplify things like:
10999/// *P = v1; if () { *P = v2; }
11000/// into a phi node with a store in the successor.
11001///
11002bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11003 BasicBlock *StoreBB = SI.getParent();
11004
11005 // Check to see if the successor block has exactly two incoming edges. If
11006 // so, see if the other predecessor contains a store to the same location.
11007 // if so, insert a PHI node (if needed) and move the stores down.
11008 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11009
11010 // Determine whether Dest has exactly two predecessors and, if so, compute
11011 // the other predecessor.
11012 pred_iterator PI = pred_begin(DestBB);
11013 BasicBlock *OtherBB = 0;
11014 if (*PI != StoreBB)
11015 OtherBB = *PI;
11016 ++PI;
11017 if (PI == pred_end(DestBB))
11018 return false;
11019
11020 if (*PI != StoreBB) {
11021 if (OtherBB)
11022 return false;
11023 OtherBB = *PI;
11024 }
11025 if (++PI != pred_end(DestBB))
11026 return false;
11027
11028
11029 // Verify that the other block ends in a branch and is not otherwise empty.
11030 BasicBlock::iterator BBI = OtherBB->getTerminator();
11031 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11032 if (!OtherBr || BBI == OtherBB->begin())
11033 return false;
11034
11035 // If the other block ends in an unconditional branch, check for the 'if then
11036 // else' case. there is an instruction before the branch.
11037 StoreInst *OtherStore = 0;
11038 if (OtherBr->isUnconditional()) {
11039 // If this isn't a store, or isn't a store to the same location, bail out.
11040 --BBI;
11041 OtherStore = dyn_cast<StoreInst>(BBI);
11042 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11043 return false;
11044 } else {
11045 // Otherwise, the other block ended with a conditional branch. If one of the
11046 // destinations is StoreBB, then we have the if/then case.
11047 if (OtherBr->getSuccessor(0) != StoreBB &&
11048 OtherBr->getSuccessor(1) != StoreBB)
11049 return false;
11050
11051 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11052 // if/then triangle. See if there is a store to the same ptr as SI that
11053 // lives in OtherBB.
11054 for (;; --BBI) {
11055 // Check to see if we find the matching store.
11056 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11057 if (OtherStore->getOperand(1) != SI.getOperand(1))
11058 return false;
11059 break;
11060 }
11061 // If we find something that may be using the stored value, or if we run
11062 // out of instructions, we can't do the xform.
11063 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11064 BBI == OtherBB->begin())
11065 return false;
11066 }
11067
11068 // In order to eliminate the store in OtherBr, we have to
11069 // make sure nothing reads the stored value in StoreBB.
11070 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11071 // FIXME: This should really be AA driven.
11072 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11073 return false;
11074 }
11075 }
11076
11077 // Insert a PHI node now if we need it.
11078 Value *MergedVal = OtherStore->getOperand(0);
11079 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011080 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011081 PN->reserveOperandSpace(2);
11082 PN->addIncoming(SI.getOperand(0), SI.getParent());
11083 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11084 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11085 }
11086
11087 // Advance to a place where it is safe to insert the new store and
11088 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011089 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011090 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11091 OtherStore->isVolatile()), *BBI);
11092
11093 // Nuke the old stores.
11094 EraseInstFromFunction(SI);
11095 EraseInstFromFunction(*OtherStore);
11096 ++NumCombined;
11097 return true;
11098}
11099
11100
11101Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11102 // Change br (not X), label True, label False to: br X, label False, True
11103 Value *X = 0;
11104 BasicBlock *TrueDest;
11105 BasicBlock *FalseDest;
11106 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11107 !isa<Constant>(X)) {
11108 // Swap Destinations and condition...
11109 BI.setCondition(X);
11110 BI.setSuccessor(0, FalseDest);
11111 BI.setSuccessor(1, TrueDest);
11112 return &BI;
11113 }
11114
11115 // Cannonicalize fcmp_one -> fcmp_oeq
11116 FCmpInst::Predicate FPred; Value *Y;
11117 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11118 TrueDest, FalseDest)))
11119 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11120 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11121 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11122 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11123 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11124 NewSCC->takeName(I);
11125 // Swap Destinations and condition...
11126 BI.setCondition(NewSCC);
11127 BI.setSuccessor(0, FalseDest);
11128 BI.setSuccessor(1, TrueDest);
11129 RemoveFromWorkList(I);
11130 I->eraseFromParent();
11131 AddToWorkList(NewSCC);
11132 return &BI;
11133 }
11134
11135 // Cannonicalize icmp_ne -> icmp_eq
11136 ICmpInst::Predicate IPred;
11137 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11138 TrueDest, FalseDest)))
11139 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11140 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11141 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11142 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11143 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11144 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11145 NewSCC->takeName(I);
11146 // Swap Destinations and condition...
11147 BI.setCondition(NewSCC);
11148 BI.setSuccessor(0, FalseDest);
11149 BI.setSuccessor(1, TrueDest);
11150 RemoveFromWorkList(I);
11151 I->eraseFromParent();;
11152 AddToWorkList(NewSCC);
11153 return &BI;
11154 }
11155
11156 return 0;
11157}
11158
11159Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11160 Value *Cond = SI.getCondition();
11161 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11162 if (I->getOpcode() == Instruction::Add)
11163 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11164 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11165 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11166 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11167 AddRHS));
11168 SI.setOperand(0, I->getOperand(0));
11169 AddToWorkList(I);
11170 return &SI;
11171 }
11172 }
11173 return 0;
11174}
11175
11176/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11177/// is to leave as a vector operation.
11178static bool CheapToScalarize(Value *V, bool isConstant) {
11179 if (isa<ConstantAggregateZero>(V))
11180 return true;
11181 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11182 if (isConstant) return true;
11183 // If all elts are the same, we can extract.
11184 Constant *Op0 = C->getOperand(0);
11185 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11186 if (C->getOperand(i) != Op0)
11187 return false;
11188 return true;
11189 }
11190 Instruction *I = dyn_cast<Instruction>(V);
11191 if (!I) return false;
11192
11193 // Insert element gets simplified to the inserted element or is deleted if
11194 // this is constant idx extract element and its a constant idx insertelt.
11195 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11196 isa<ConstantInt>(I->getOperand(2)))
11197 return true;
11198 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11199 return true;
11200 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11201 if (BO->hasOneUse() &&
11202 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11203 CheapToScalarize(BO->getOperand(1), isConstant)))
11204 return true;
11205 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11206 if (CI->hasOneUse() &&
11207 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11208 CheapToScalarize(CI->getOperand(1), isConstant)))
11209 return true;
11210
11211 return false;
11212}
11213
11214/// Read and decode a shufflevector mask.
11215///
11216/// It turns undef elements into values that are larger than the number of
11217/// elements in the input.
11218static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11219 unsigned NElts = SVI->getType()->getNumElements();
11220 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11221 return std::vector<unsigned>(NElts, 0);
11222 if (isa<UndefValue>(SVI->getOperand(2)))
11223 return std::vector<unsigned>(NElts, 2*NElts);
11224
11225 std::vector<unsigned> Result;
11226 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11227 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11228 if (isa<UndefValue>(CP->getOperand(i)))
11229 Result.push_back(NElts*2); // undef -> 8
11230 else
11231 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
11232 return Result;
11233}
11234
11235/// FindScalarElement - Given a vector and an element number, see if the scalar
11236/// value is already around as a register, for example if it were inserted then
11237/// extracted from the vector.
11238static Value *FindScalarElement(Value *V, unsigned EltNo) {
11239 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11240 const VectorType *PTy = cast<VectorType>(V->getType());
11241 unsigned Width = PTy->getNumElements();
11242 if (EltNo >= Width) // Out of range access.
11243 return UndefValue::get(PTy->getElementType());
11244
11245 if (isa<UndefValue>(V))
11246 return UndefValue::get(PTy->getElementType());
11247 else if (isa<ConstantAggregateZero>(V))
11248 return Constant::getNullValue(PTy->getElementType());
11249 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11250 return CP->getOperand(EltNo);
11251 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11252 // If this is an insert to a variable element, we don't know what it is.
11253 if (!isa<ConstantInt>(III->getOperand(2)))
11254 return 0;
11255 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11256
11257 // If this is an insert to the element we are looking for, return the
11258 // inserted value.
11259 if (EltNo == IIElt)
11260 return III->getOperand(1);
11261
11262 // Otherwise, the insertelement doesn't modify the value, recurse on its
11263 // vector input.
11264 return FindScalarElement(III->getOperand(0), EltNo);
11265 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11266 unsigned InEl = getShuffleMask(SVI)[EltNo];
11267 if (InEl < Width)
11268 return FindScalarElement(SVI->getOperand(0), InEl);
11269 else if (InEl < Width*2)
11270 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11271 else
11272 return UndefValue::get(PTy->getElementType());
11273 }
11274
11275 // Otherwise, we don't know.
11276 return 0;
11277}
11278
11279Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11280
11281 // If vector val is undef, replace extract with scalar undef.
11282 if (isa<UndefValue>(EI.getOperand(0)))
11283 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11284
11285 // If vector val is constant 0, replace extract with scalar 0.
11286 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11287 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11288
11289 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11290 // If vector val is constant with uniform operands, replace EI
11291 // with that operand
11292 Constant *op0 = C->getOperand(0);
11293 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11294 if (C->getOperand(i) != op0) {
11295 op0 = 0;
11296 break;
11297 }
11298 if (op0)
11299 return ReplaceInstUsesWith(EI, op0);
11300 }
11301
11302 // If extracting a specified index from the vector, see if we can recursively
11303 // find a previously computed scalar that was inserted into the vector.
11304 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11305 unsigned IndexVal = IdxC->getZExtValue();
11306 unsigned VectorWidth =
11307 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11308
11309 // If this is extracting an invalid index, turn this into undef, to avoid
11310 // crashing the code below.
11311 if (IndexVal >= VectorWidth)
11312 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11313
11314 // This instruction only demands the single element from the input vector.
11315 // If the input vector has a single use, simplify it based on this use
11316 // property.
11317 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11318 uint64_t UndefElts;
11319 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11320 1 << IndexVal,
11321 UndefElts)) {
11322 EI.setOperand(0, V);
11323 return &EI;
11324 }
11325 }
11326
11327 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11328 return ReplaceInstUsesWith(EI, Elt);
11329
11330 // If the this extractelement is directly using a bitcast from a vector of
11331 // the same number of elements, see if we can find the source element from
11332 // it. In this case, we will end up needing to bitcast the scalars.
11333 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11334 if (const VectorType *VT =
11335 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11336 if (VT->getNumElements() == VectorWidth)
11337 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11338 return new BitCastInst(Elt, EI.getType());
11339 }
11340 }
11341
11342 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11343 if (I->hasOneUse()) {
11344 // Push extractelement into predecessor operation if legal and
11345 // profitable to do so
11346 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11347 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11348 if (CheapToScalarize(BO, isConstantElt)) {
11349 ExtractElementInst *newEI0 =
11350 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11351 EI.getName()+".lhs");
11352 ExtractElementInst *newEI1 =
11353 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11354 EI.getName()+".rhs");
11355 InsertNewInstBefore(newEI0, EI);
11356 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011357 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011358 }
11359 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011360 unsigned AS =
11361 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011362 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11363 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011364 GetElementPtrInst *GEP =
11365 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011366 InsertNewInstBefore(GEP, EI);
11367 return new LoadInst(GEP);
11368 }
11369 }
11370 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11371 // Extracting the inserted element?
11372 if (IE->getOperand(2) == EI.getOperand(1))
11373 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11374 // If the inserted and extracted elements are constants, they must not
11375 // be the same value, extract from the pre-inserted value instead.
11376 if (isa<Constant>(IE->getOperand(2)) &&
11377 isa<Constant>(EI.getOperand(1))) {
11378 AddUsesToWorkList(EI);
11379 EI.setOperand(0, IE->getOperand(0));
11380 return &EI;
11381 }
11382 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11383 // If this is extracting an element from a shufflevector, figure out where
11384 // it came from and extract from the appropriate input element instead.
11385 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11386 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11387 Value *Src;
11388 if (SrcIdx < SVI->getType()->getNumElements())
11389 Src = SVI->getOperand(0);
11390 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11391 SrcIdx -= SVI->getType()->getNumElements();
11392 Src = SVI->getOperand(1);
11393 } else {
11394 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11395 }
11396 return new ExtractElementInst(Src, SrcIdx);
11397 }
11398 }
11399 }
11400 return 0;
11401}
11402
11403/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11404/// elements from either LHS or RHS, return the shuffle mask and true.
11405/// Otherwise, return false.
11406static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11407 std::vector<Constant*> &Mask) {
11408 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11409 "Invalid CollectSingleShuffleElements");
11410 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11411
11412 if (isa<UndefValue>(V)) {
11413 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11414 return true;
11415 } else if (V == LHS) {
11416 for (unsigned i = 0; i != NumElts; ++i)
11417 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11418 return true;
11419 } else if (V == RHS) {
11420 for (unsigned i = 0; i != NumElts; ++i)
11421 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11422 return true;
11423 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11424 // If this is an insert of an extract from some other vector, include it.
11425 Value *VecOp = IEI->getOperand(0);
11426 Value *ScalarOp = IEI->getOperand(1);
11427 Value *IdxOp = IEI->getOperand(2);
11428
11429 if (!isa<ConstantInt>(IdxOp))
11430 return false;
11431 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11432
11433 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11434 // Okay, we can handle this if the vector we are insertinting into is
11435 // transitively ok.
11436 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11437 // If so, update the mask to reflect the inserted undef.
11438 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11439 return true;
11440 }
11441 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11442 if (isa<ConstantInt>(EI->getOperand(1)) &&
11443 EI->getOperand(0)->getType() == V->getType()) {
11444 unsigned ExtractedIdx =
11445 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11446
11447 // This must be extracting from either LHS or RHS.
11448 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11449 // Okay, we can handle this if the vector we are insertinting into is
11450 // transitively ok.
11451 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11452 // If so, update the mask to reflect the inserted value.
11453 if (EI->getOperand(0) == LHS) {
11454 Mask[InsertedIdx & (NumElts-1)] =
11455 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11456 } else {
11457 assert(EI->getOperand(0) == RHS);
11458 Mask[InsertedIdx & (NumElts-1)] =
11459 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11460
11461 }
11462 return true;
11463 }
11464 }
11465 }
11466 }
11467 }
11468 // TODO: Handle shufflevector here!
11469
11470 return false;
11471}
11472
11473/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11474/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11475/// that computes V and the LHS value of the shuffle.
11476static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11477 Value *&RHS) {
11478 assert(isa<VectorType>(V->getType()) &&
11479 (RHS == 0 || V->getType() == RHS->getType()) &&
11480 "Invalid shuffle!");
11481 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11482
11483 if (isa<UndefValue>(V)) {
11484 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11485 return V;
11486 } else if (isa<ConstantAggregateZero>(V)) {
11487 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11488 return V;
11489 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11490 // If this is an insert of an extract from some other vector, include it.
11491 Value *VecOp = IEI->getOperand(0);
11492 Value *ScalarOp = IEI->getOperand(1);
11493 Value *IdxOp = IEI->getOperand(2);
11494
11495 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11496 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11497 EI->getOperand(0)->getType() == V->getType()) {
11498 unsigned ExtractedIdx =
11499 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11500 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11501
11502 // Either the extracted from or inserted into vector must be RHSVec,
11503 // otherwise we'd end up with a shuffle of three inputs.
11504 if (EI->getOperand(0) == RHS || RHS == 0) {
11505 RHS = EI->getOperand(0);
11506 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11507 Mask[InsertedIdx & (NumElts-1)] =
11508 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11509 return V;
11510 }
11511
11512 if (VecOp == RHS) {
11513 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11514 // Everything but the extracted element is replaced with the RHS.
11515 for (unsigned i = 0; i != NumElts; ++i) {
11516 if (i != InsertedIdx)
11517 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11518 }
11519 return V;
11520 }
11521
11522 // If this insertelement is a chain that comes from exactly these two
11523 // vectors, return the vector and the effective shuffle.
11524 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11525 return EI->getOperand(0);
11526
11527 }
11528 }
11529 }
11530 // TODO: Handle shufflevector here!
11531
11532 // Otherwise, can't do anything fancy. Return an identity vector.
11533 for (unsigned i = 0; i != NumElts; ++i)
11534 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11535 return V;
11536}
11537
11538Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11539 Value *VecOp = IE.getOperand(0);
11540 Value *ScalarOp = IE.getOperand(1);
11541 Value *IdxOp = IE.getOperand(2);
11542
11543 // Inserting an undef or into an undefined place, remove this.
11544 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11545 ReplaceInstUsesWith(IE, VecOp);
11546
11547 // If the inserted element was extracted from some other vector, and if the
11548 // indexes are constant, try to turn this into a shufflevector operation.
11549 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11550 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11551 EI->getOperand(0)->getType() == IE.getType()) {
11552 unsigned NumVectorElts = IE.getType()->getNumElements();
11553 unsigned ExtractedIdx =
11554 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11555 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11556
11557 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11558 return ReplaceInstUsesWith(IE, VecOp);
11559
11560 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11561 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11562
11563 // If we are extracting a value from a vector, then inserting it right
11564 // back into the same place, just use the input vector.
11565 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11566 return ReplaceInstUsesWith(IE, VecOp);
11567
11568 // We could theoretically do this for ANY input. However, doing so could
11569 // turn chains of insertelement instructions into a chain of shufflevector
11570 // instructions, and right now we do not merge shufflevectors. As such,
11571 // only do this in a situation where it is clear that there is benefit.
11572 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11573 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11574 // the values of VecOp, except then one read from EIOp0.
11575 // Build a new shuffle mask.
11576 std::vector<Constant*> Mask;
11577 if (isa<UndefValue>(VecOp))
11578 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11579 else {
11580 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11581 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11582 NumVectorElts));
11583 }
11584 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11585 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11586 ConstantVector::get(Mask));
11587 }
11588
11589 // If this insertelement isn't used by some other insertelement, turn it
11590 // (and any insertelements it points to), into one big shuffle.
11591 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11592 std::vector<Constant*> Mask;
11593 Value *RHS = 0;
11594 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11595 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11596 // We now have a shuffle of LHS, RHS, Mask.
11597 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11598 }
11599 }
11600 }
11601
11602 return 0;
11603}
11604
11605
11606Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11607 Value *LHS = SVI.getOperand(0);
11608 Value *RHS = SVI.getOperand(1);
11609 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11610
11611 bool MadeChange = false;
11612
11613 // Undefined shuffle mask -> undefined value.
11614 if (isa<UndefValue>(SVI.getOperand(2)))
11615 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11616
11617 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11618 // the undef, change them to undefs.
11619 if (isa<UndefValue>(SVI.getOperand(1))) {
11620 // Scan to see if there are any references to the RHS. If so, replace them
11621 // with undef element refs and set MadeChange to true.
11622 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11623 if (Mask[i] >= e && Mask[i] != 2*e) {
11624 Mask[i] = 2*e;
11625 MadeChange = true;
11626 }
11627 }
11628
11629 if (MadeChange) {
11630 // Remap any references to RHS to use LHS.
11631 std::vector<Constant*> Elts;
11632 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11633 if (Mask[i] == 2*e)
11634 Elts.push_back(UndefValue::get(Type::Int32Ty));
11635 else
11636 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11637 }
11638 SVI.setOperand(2, ConstantVector::get(Elts));
11639 }
11640 }
11641
11642 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11643 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11644 if (LHS == RHS || isa<UndefValue>(LHS)) {
11645 if (isa<UndefValue>(LHS) && LHS == RHS) {
11646 // shuffle(undef,undef,mask) -> undef.
11647 return ReplaceInstUsesWith(SVI, LHS);
11648 }
11649
11650 // Remap any references to RHS to use LHS.
11651 std::vector<Constant*> Elts;
11652 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11653 if (Mask[i] >= 2*e)
11654 Elts.push_back(UndefValue::get(Type::Int32Ty));
11655 else {
11656 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11657 (Mask[i] < e && isa<UndefValue>(LHS)))
11658 Mask[i] = 2*e; // Turn into undef.
11659 else
11660 Mask[i] &= (e-1); // Force to LHS.
11661 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11662 }
11663 }
11664 SVI.setOperand(0, SVI.getOperand(1));
11665 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11666 SVI.setOperand(2, ConstantVector::get(Elts));
11667 LHS = SVI.getOperand(0);
11668 RHS = SVI.getOperand(1);
11669 MadeChange = true;
11670 }
11671
11672 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11673 bool isLHSID = true, isRHSID = true;
11674
11675 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11676 if (Mask[i] >= e*2) continue; // Ignore undef values.
11677 // Is this an identity shuffle of the LHS value?
11678 isLHSID &= (Mask[i] == i);
11679
11680 // Is this an identity shuffle of the RHS value?
11681 isRHSID &= (Mask[i]-e == i);
11682 }
11683
11684 // Eliminate identity shuffles.
11685 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11686 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11687
11688 // If the LHS is a shufflevector itself, see if we can combine it with this
11689 // one without producing an unusual shuffle. Here we are really conservative:
11690 // we are absolutely afraid of producing a shuffle mask not in the input
11691 // program, because the code gen may not be smart enough to turn a merged
11692 // shuffle into two specific shuffles: it may produce worse code. As such,
11693 // we only merge two shuffles if the result is one of the two input shuffle
11694 // masks. In this case, merging the shuffles just removes one instruction,
11695 // which we know is safe. This is good for things like turning:
11696 // (splat(splat)) -> splat.
11697 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11698 if (isa<UndefValue>(RHS)) {
11699 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11700
11701 std::vector<unsigned> NewMask;
11702 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11703 if (Mask[i] >= 2*e)
11704 NewMask.push_back(2*e);
11705 else
11706 NewMask.push_back(LHSMask[Mask[i]]);
11707
11708 // If the result mask is equal to the src shuffle or this shuffle mask, do
11709 // the replacement.
11710 if (NewMask == LHSMask || NewMask == Mask) {
11711 std::vector<Constant*> Elts;
11712 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11713 if (NewMask[i] >= e*2) {
11714 Elts.push_back(UndefValue::get(Type::Int32Ty));
11715 } else {
11716 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11717 }
11718 }
11719 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11720 LHSSVI->getOperand(1),
11721 ConstantVector::get(Elts));
11722 }
11723 }
11724 }
11725
11726 return MadeChange ? &SVI : 0;
11727}
11728
11729
11730
11731
11732/// TryToSinkInstruction - Try to move the specified instruction from its
11733/// current block into the beginning of DestBlock, which can only happen if it's
11734/// safe to move the instruction past all of the instructions between it and the
11735/// end of its block.
11736static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11737 assert(I->hasOneUse() && "Invariants didn't hold!");
11738
11739 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011740 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11741 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011742
11743 // Do not sink alloca instructions out of the entry block.
11744 if (isa<AllocaInst>(I) && I->getParent() ==
11745 &DestBlock->getParent()->getEntryBlock())
11746 return false;
11747
11748 // We can only sink load instructions if there is nothing between the load and
11749 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011750 if (I->mayReadFromMemory()) {
11751 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011752 Scan != E; ++Scan)
11753 if (Scan->mayWriteToMemory())
11754 return false;
11755 }
11756
Dan Gohman514277c2008-05-23 21:05:58 +000011757 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011758
11759 I->moveBefore(InsertPos);
11760 ++NumSunkInst;
11761 return true;
11762}
11763
11764
11765/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11766/// all reachable code to the worklist.
11767///
11768/// This has a couple of tricks to make the code faster and more powerful. In
11769/// particular, we constant fold and DCE instructions as we go, to avoid adding
11770/// them to the worklist (this significantly speeds up instcombine on code where
11771/// many instructions are dead or constant). Additionally, if we find a branch
11772/// whose condition is a known constant, we only visit the reachable successors.
11773///
11774static void AddReachableCodeToWorklist(BasicBlock *BB,
11775 SmallPtrSet<BasicBlock*, 64> &Visited,
11776 InstCombiner &IC,
11777 const TargetData *TD) {
11778 std::vector<BasicBlock*> Worklist;
11779 Worklist.push_back(BB);
11780
11781 while (!Worklist.empty()) {
11782 BB = Worklist.back();
11783 Worklist.pop_back();
11784
11785 // We have now visited this block! If we've already been here, ignore it.
11786 if (!Visited.insert(BB)) continue;
11787
11788 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11789 Instruction *Inst = BBI++;
11790
11791 // DCE instruction if trivially dead.
11792 if (isInstructionTriviallyDead(Inst)) {
11793 ++NumDeadInst;
11794 DOUT << "IC: DCE: " << *Inst;
11795 Inst->eraseFromParent();
11796 continue;
11797 }
11798
11799 // ConstantProp instruction if trivially constant.
11800 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11801 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11802 Inst->replaceAllUsesWith(C);
11803 ++NumConstProp;
11804 Inst->eraseFromParent();
11805 continue;
11806 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011807
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011808 IC.AddToWorkList(Inst);
11809 }
11810
11811 // Recursively visit successors. If this is a branch or switch on a
11812 // constant, only visit the reachable successor.
11813 TerminatorInst *TI = BB->getTerminator();
11814 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11815 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11816 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011817 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011818 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011819 continue;
11820 }
11821 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11822 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11823 // See if this is an explicit destination.
11824 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11825 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011826 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011827 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011828 continue;
11829 }
11830
11831 // Otherwise it is the default destination.
11832 Worklist.push_back(SI->getSuccessor(0));
11833 continue;
11834 }
11835 }
11836
11837 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11838 Worklist.push_back(TI->getSuccessor(i));
11839 }
11840}
11841
11842bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11843 bool Changed = false;
11844 TD = &getAnalysis<TargetData>();
11845
11846 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11847 << F.getNameStr() << "\n");
11848
11849 {
11850 // Do a depth-first traversal of the function, populate the worklist with
11851 // the reachable instructions. Ignore blocks that are not reachable. Keep
11852 // track of which blocks we visit.
11853 SmallPtrSet<BasicBlock*, 64> Visited;
11854 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11855
11856 // Do a quick scan over the function. If we find any blocks that are
11857 // unreachable, remove any instructions inside of them. This prevents
11858 // the instcombine code from having to deal with some bad special cases.
11859 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11860 if (!Visited.count(BB)) {
11861 Instruction *Term = BB->getTerminator();
11862 while (Term != BB->begin()) { // Remove instrs bottom-up
11863 BasicBlock::iterator I = Term; --I;
11864
11865 DOUT << "IC: DCE: " << *I;
11866 ++NumDeadInst;
11867
11868 if (!I->use_empty())
11869 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11870 I->eraseFromParent();
11871 }
11872 }
11873 }
11874
11875 while (!Worklist.empty()) {
11876 Instruction *I = RemoveOneFromWorkList();
11877 if (I == 0) continue; // skip null values.
11878
11879 // Check to see if we can DCE the instruction.
11880 if (isInstructionTriviallyDead(I)) {
11881 // Add operands to the worklist.
11882 if (I->getNumOperands() < 4)
11883 AddUsesToWorkList(*I);
11884 ++NumDeadInst;
11885
11886 DOUT << "IC: DCE: " << *I;
11887
11888 I->eraseFromParent();
11889 RemoveFromWorkList(I);
11890 continue;
11891 }
11892
11893 // Instruction isn't dead, see if we can constant propagate it.
11894 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11895 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11896
11897 // Add operands to the worklist.
11898 AddUsesToWorkList(*I);
11899 ReplaceInstUsesWith(*I, C);
11900
11901 ++NumConstProp;
11902 I->eraseFromParent();
11903 RemoveFromWorkList(I);
11904 continue;
11905 }
11906
Nick Lewyckyadb67922008-05-25 20:56:15 +000011907 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11908 // See if we can constant fold its operands.
11909 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11910 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11911 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11912 i->set(NewC);
11913 }
11914 }
11915 }
11916
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011917 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011918 // FIXME: Remove GetResultInst test when first class support for aggregates
11919 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011920 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011921 BasicBlock *BB = I->getParent();
11922 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11923 if (UserParent != BB) {
11924 bool UserIsSuccessor = false;
11925 // See if the user is one of our successors.
11926 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11927 if (*SI == UserParent) {
11928 UserIsSuccessor = true;
11929 break;
11930 }
11931
11932 // If the user is one of our immediate successors, and if that successor
11933 // only has us as a predecessors (we'd have to split the critical edge
11934 // otherwise), we can keep going.
11935 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11936 next(pred_begin(UserParent)) == pred_end(UserParent))
11937 // Okay, the CFG is simple enough, try to sink this instruction.
11938 Changed |= TryToSinkInstruction(I, UserParent);
11939 }
11940 }
11941
11942 // Now that we have an instruction, try combining it to simplify it...
11943#ifndef NDEBUG
11944 std::string OrigI;
11945#endif
11946 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11947 if (Instruction *Result = visit(*I)) {
11948 ++NumCombined;
11949 // Should we replace the old instruction with a new one?
11950 if (Result != I) {
11951 DOUT << "IC: Old = " << *I
11952 << " New = " << *Result;
11953
11954 // Everything uses the new instruction now.
11955 I->replaceAllUsesWith(Result);
11956
11957 // Push the new instruction and any users onto the worklist.
11958 AddToWorkList(Result);
11959 AddUsersToWorkList(*Result);
11960
11961 // Move the name to the new instruction first.
11962 Result->takeName(I);
11963
11964 // Insert the new instruction into the basic block...
11965 BasicBlock *InstParent = I->getParent();
11966 BasicBlock::iterator InsertPos = I;
11967
11968 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11969 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11970 ++InsertPos;
11971
11972 InstParent->getInstList().insert(InsertPos, Result);
11973
11974 // Make sure that we reprocess all operands now that we reduced their
11975 // use counts.
11976 AddUsesToWorkList(*I);
11977
11978 // Instructions can end up on the worklist more than once. Make sure
11979 // we do not process an instruction that has been deleted.
11980 RemoveFromWorkList(I);
11981
11982 // Erase the old instruction.
11983 InstParent->getInstList().erase(I);
11984 } else {
11985#ifndef NDEBUG
11986 DOUT << "IC: Mod = " << OrigI
11987 << " New = " << *I;
11988#endif
11989
11990 // If the instruction was modified, it's possible that it is now dead.
11991 // if so, remove it.
11992 if (isInstructionTriviallyDead(I)) {
11993 // Make sure we process all operands now that we are reducing their
11994 // use counts.
11995 AddUsesToWorkList(*I);
11996
11997 // Instructions may end up in the worklist more than once. Erase all
11998 // occurrences of this instruction.
11999 RemoveFromWorkList(I);
12000 I->eraseFromParent();
12001 } else {
12002 AddToWorkList(I);
12003 AddUsersToWorkList(*I);
12004 }
12005 }
12006 Changed = true;
12007 }
12008 }
12009
12010 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000012011
12012 // Do an explicit clear, this shrinks the map if needed.
12013 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012014 return Changed;
12015}
12016
12017
12018bool InstCombiner::runOnFunction(Function &F) {
12019 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12020
12021 bool EverMadeChange = false;
12022
12023 // Iterate while there is work to do.
12024 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012025 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012026 EverMadeChange = true;
12027 return EverMadeChange;
12028}
12029
12030FunctionPass *llvm::createInstructionCombiningPass() {
12031 return new InstCombiner();
12032}
12033