blob: 42cfd8a8f2b48641dcdcc65cdeca8f7480a7ee77 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
39#include "llvm/Pass.h"
40#include "llvm/DerivedTypes.h"
41#include "llvm/GlobalVariable.h"
42#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000061#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include <sstream>
63using namespace llvm;
64using namespace llvm::PatternMatch;
65
66STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72namespace {
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
77 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
79 TargetData *TD;
80 bool MustPreserveLCSSA;
81 public:
82 static char ID; // Pass identification, replacement for typeid
83 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
109
110
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 UI != UE; ++UI)
118 AddToWorkList(cast<Instruction>(*UI));
119 }
120
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 AddToWorkList(Op);
128 }
129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif17396002008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
Gabor Greif17396002008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
145
146 return R;
147 }
148
149 public:
150 virtual bool runOnFunction(Function &F);
151
152 bool DoOneIteration(Function &F, unsigned ItNum);
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
158 }
159
160 TargetData &getTargetData() const { return *TD; }
161
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
168 //
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 Instruction *commonRemTransforms(BinaryOperator &I);
176 Instruction *commonIRemTransforms(BinaryOperator &I);
177 Instruction *commonDivTransforms(BinaryOperator &I);
178 Instruction *commonIDivTransforms(BinaryOperator &I);
179 Instruction *visitUDiv(BinaryOperator &I);
180 Instruction *visitSDiv(BinaryOperator &I);
181 Instruction *visitFDiv(BinaryOperator &I);
182 Instruction *visitAnd(BinaryOperator &I);
183 Instruction *visitOr (BinaryOperator &I);
184 Instruction *visitXor(BinaryOperator &I);
185 Instruction *visitShl(BinaryOperator &I);
186 Instruction *visitAShr(BinaryOperator &I);
187 Instruction *visitLShr(BinaryOperator &I);
188 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000189 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 Instruction *visitFCmpInst(FCmpInst &I);
192 Instruction *visitICmpInst(ICmpInst &I);
193 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195 Instruction *LHS,
196 ConstantInt *RHS);
197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
199
200 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201 ICmpInst::Predicate Cond, Instruction &I);
202 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203 BinaryOperator &I);
204 Instruction *commonCastTransforms(CastInst &CI);
205 Instruction *commonIntCastTransforms(CastInst &CI);
206 Instruction *commonPointerCastTransforms(CastInst &CI);
207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000210 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000217 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 Instruction *visitBitCast(BitCastInst &CI);
219 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220 Instruction *FI);
221 Instruction *visitSelectInst(SelectInst &CI);
222 Instruction *visitCallInst(CallInst &CI);
223 Instruction *visitInvokeInst(InvokeInst &II);
224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226 Instruction *visitAllocationInst(AllocationInst &AI);
227 Instruction *visitFreeInst(FreeInst &FI);
228 Instruction *visitLoadInst(LoadInst &LI);
229 Instruction *visitStoreInst(StoreInst &SI);
230 Instruction *visitBranchInst(BranchInst &BI);
231 Instruction *visitSwitchInst(SwitchInst &SI);
232 Instruction *visitInsertElementInst(InsertElementInst &IE);
233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000235 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236
237 // visitInstruction - Specify what to return for unhandled instructions...
238 Instruction *visitInstruction(Instruction &I) { return 0; }
239
240 private:
241 Instruction *visitCallSite(CallSite CS);
242 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000243 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000244 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000246 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247
248 public:
249 // InsertNewInstBefore - insert an instruction New before instruction Old
250 // in the program. Add the new instruction to the worklist.
251 //
252 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253 assert(New && New->getParent() == 0 &&
254 "New instruction already inserted into a basic block!");
255 BasicBlock *BB = Old.getParent();
256 BB->getInstList().insert(&Old, New); // Insert inst
257 AddToWorkList(New);
258 return New;
259 }
260
261 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262 /// This also adds the cast to the worklist. Finally, this returns the
263 /// cast.
264 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265 Instruction &Pos) {
266 if (V->getType() == Ty) return V;
267
268 if (Constant *CV = dyn_cast<Constant>(V))
269 return ConstantExpr::getCast(opc, CV, Ty);
270
Gabor Greifa645dd32008-05-16 19:29:10 +0000271 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 AddToWorkList(C);
273 return C;
274 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000275
276 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278 }
279
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280
281 // ReplaceInstUsesWith - This method is to be used when an instruction is
282 // found to be dead, replacable with another preexisting expression. Here
283 // we add all uses of I to the worklist, replace all uses of I with the new
284 // value, then return I, so that the inst combiner will know that I was
285 // modified.
286 //
287 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288 AddUsersToWorkList(I); // Add all modified instrs to worklist
289 if (&I != V) {
290 I.replaceAllUsesWith(V);
291 return &I;
292 } else {
293 // If we are replacing the instruction with itself, this must be in a
294 // segment of unreachable code, so just clobber the instruction.
295 I.replaceAllUsesWith(UndefValue::get(I.getType()));
296 return &I;
297 }
298 }
299
300 // UpdateValueUsesWith - This method is to be used when an value is
301 // found to be replacable with another preexisting expression or was
302 // updated. Here we add all uses of I to the worklist, replace all uses of
303 // I with the new value (unless the instruction was just updated), then
304 // return true, so that the inst combiner will know that I was modified.
305 //
306 bool UpdateValueUsesWith(Value *Old, Value *New) {
307 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
308 if (Old != New)
309 Old->replaceAllUsesWith(New);
310 if (Instruction *I = dyn_cast<Instruction>(Old))
311 AddToWorkList(I);
312 if (Instruction *I = dyn_cast<Instruction>(New))
313 AddToWorkList(I);
314 return true;
315 }
316
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
324 RemoveFromWorkList(&I);
325 I.eraseFromParent();
326 return 0; // Don't do anything with FI
327 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341
342 private:
343 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344 /// InsertBefore instruction. This is specialized a bit to avoid inserting
345 /// casts that are known to not do anything...
346 ///
347 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348 Value *V, const Type *DestTy,
349 Instruction *InsertBefore);
350
351 /// SimplifyCommutative - This performs a few simplifications for
352 /// commutative operators.
353 bool SimplifyCommutative(BinaryOperator &I);
354
355 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356 /// most-complex to least-complex order.
357 bool SimplifyCompare(CmpInst &I);
358
359 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360 /// on the demanded bits.
361 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
362 APInt& KnownZero, APInt& KnownOne,
363 unsigned Depth = 0);
364
365 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366 uint64_t &UndefElts, unsigned Depth = 0);
367
368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378
379
380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
382
383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384 bool isSub, Instruction &I);
385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386 bool isSigned, bool Inside, Instruction &IB);
387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388 Instruction *MatchBSwap(BinaryOperator &I);
389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000391 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000392
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393
394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000395
Dan Gohman2d648bb2008-04-10 18:43:06 +0000396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397 unsigned CastOpc,
398 int &NumCastsRemoved);
399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000401
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403}
404
Dan Gohman089efff2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411static unsigned getComplexity(Value *V) {
412 if (isa<Instruction>(V)) {
413 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414 return 3;
415 return 4;
416 }
417 if (isa<Argument>(V)) return 3;
418 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419}
420
421// isOnlyUse - Return true if this instruction will be deleted if we stop using
422// it.
423static bool isOnlyUse(Value *V) {
424 return V->hasOneUse() || isa<Constant>(V);
425}
426
427// getPromotedType - Return the specified type promoted as it would be to pass
428// though a va_arg area...
429static const Type *getPromotedType(const Type *Ty) {
430 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431 if (ITy->getBitWidth() < 32)
432 return Type::Int32Ty;
433 }
434 return Ty;
435}
436
437/// getBitCastOperand - If the specified operand is a CastInst or a constant
438/// expression bitcast, return the operand value, otherwise return null.
439static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441 return I->getOperand(0);
442 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
443 if (CE->getOpcode() == Instruction::BitCast)
444 return CE->getOperand(0);
445 return 0;
446}
447
448/// This function is a wrapper around CastInst::isEliminableCastPair. It
449/// simply extracts arguments and returns what that function returns.
450static Instruction::CastOps
451isEliminableCastPair(
452 const CastInst *CI, ///< The first cast instruction
453 unsigned opcode, ///< The opcode of the second cast instruction
454 const Type *DstTy, ///< The target type for the second cast instruction
455 TargetData *TD ///< The target data for pointer size
456) {
457
458 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
459 const Type *MidTy = CI->getType(); // B from above
460
461 // Get the opcodes of the two Cast instructions
462 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
464
465 return Instruction::CastOps(
466 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467 DstTy, TD->getIntPtrType()));
468}
469
470/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471/// in any code being generated. It does not require codegen if V is simple
472/// enough or if the cast can be folded into other casts.
473static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
474 const Type *Ty, TargetData *TD) {
475 if (V->getType() == Ty || isa<Constant>(V)) return false;
476
477 // If this is another cast that can be eliminated, it isn't codegen either.
478 if (const CastInst *CI = dyn_cast<CastInst>(V))
479 if (isEliminableCastPair(CI, opcode, Ty, TD))
480 return false;
481 return true;
482}
483
484/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485/// InsertBefore instruction. This is specialized a bit to avoid inserting
486/// casts that are known to not do anything...
487///
488Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489 Value *V, const Type *DestTy,
490 Instruction *InsertBefore) {
491 if (V->getType() == DestTy) return V;
492 if (Constant *C = dyn_cast<Constant>(V))
493 return ConstantExpr::getCast(opcode, C, DestTy);
494
495 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
496}
497
498// SimplifyCommutative - This performs a few simplifications for commutative
499// operators:
500//
501// 1. Order operands such that they are listed from right (least complex) to
502// left (most complex). This puts constants before unary operators before
503// binary operators.
504//
505// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
507//
508bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509 bool Changed = false;
510 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511 Changed = !I.swapOperands();
512
513 if (!I.isAssociative()) return Changed;
514 Instruction::BinaryOps Opcode = I.getOpcode();
515 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517 if (isa<Constant>(I.getOperand(1))) {
518 Constant *Folded = ConstantExpr::get(I.getOpcode(),
519 cast<Constant>(I.getOperand(1)),
520 cast<Constant>(Op->getOperand(1)));
521 I.setOperand(0, Op->getOperand(0));
522 I.setOperand(1, Folded);
523 return true;
524 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526 isOnlyUse(Op) && isOnlyUse(Op1)) {
527 Constant *C1 = cast<Constant>(Op->getOperand(1));
528 Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000532 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 Op1->getOperand(0),
534 Op1->getName(), &I);
535 AddToWorkList(New);
536 I.setOperand(0, New);
537 I.setOperand(1, Folded);
538 return true;
539 }
540 }
541 return Changed;
542}
543
544/// SimplifyCompare - For a CmpInst this function just orders the operands
545/// so that theyare listed from right (least complex) to left (most complex).
546/// This puts constants before unary operators before binary operators.
547bool InstCombiner::SimplifyCompare(CmpInst &I) {
548 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
549 return false;
550 I.swapOperands();
551 // Compare instructions are not associative so there's nothing else we can do.
552 return true;
553}
554
555// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556// if the LHS is a constant zero (which is the 'negate' form).
557//
558static inline Value *dyn_castNegVal(Value *V) {
559 if (BinaryOperator::isNeg(V))
560 return BinaryOperator::getNegArgument(V);
561
562 // Constants can be considered to be negated values if they can be folded.
563 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000565
566 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567 if (C->getType()->getElementType()->isInteger())
568 return ConstantExpr::getNeg(C);
569
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570 return 0;
571}
572
573static inline Value *dyn_castNotVal(Value *V) {
574 if (BinaryOperator::isNot(V))
575 return BinaryOperator::getNotArgument(V);
576
577 // Constants can be considered to be not'ed values...
578 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579 return ConstantInt::get(~C->getValue());
580 return 0;
581}
582
583// dyn_castFoldableMul - If this value is a multiply that can be folded into
584// other computations (because it has a constant operand), return the
585// non-constant operand of the multiply, and set CST to point to the multiplier.
586// Otherwise, return null.
587//
588static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
589 if (V->hasOneUse() && V->getType()->isInteger())
590 if (Instruction *I = dyn_cast<Instruction>(V)) {
591 if (I->getOpcode() == Instruction::Mul)
592 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
593 return I->getOperand(0);
594 if (I->getOpcode() == Instruction::Shl)
595 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
596 // The multiplier is really 1 << CST.
597 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
598 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
599 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
600 return I->getOperand(0);
601 }
602 }
603 return 0;
604}
605
606/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607/// expression, return it.
608static User *dyn_castGetElementPtr(Value *V) {
609 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611 if (CE->getOpcode() == Instruction::GetElementPtr)
612 return cast<User>(V);
613 return false;
614}
615
Dan Gohman2d648bb2008-04-10 18:43:06 +0000616/// getOpcode - If this is an Instruction or a ConstantExpr, return the
617/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000618static unsigned getOpcode(const Value *V) {
619 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000620 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000621 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000622 return CE->getOpcode();
623 // Use UserOp1 to mean there's no opcode.
624 return Instruction::UserOp1;
625}
626
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627/// AddOne - Add one to a ConstantInt
628static ConstantInt *AddOne(ConstantInt *C) {
629 APInt Val(C->getValue());
630 return ConstantInt::get(++Val);
631}
632/// SubOne - Subtract one from a ConstantInt
633static ConstantInt *SubOne(ConstantInt *C) {
634 APInt Val(C->getValue());
635 return ConstantInt::get(--Val);
636}
637/// Add - Add two ConstantInts together
638static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() + C2->getValue());
640}
641/// And - Bitwise AND two ConstantInts together
642static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() & C2->getValue());
644}
645/// Subtract - Subtract one ConstantInt from another
646static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() - C2->getValue());
648}
649/// Multiply - Multiply two ConstantInts together
650static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651 return ConstantInt::get(C1->getValue() * C2->getValue());
652}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000653/// MultiplyOverflows - True if the multiply can not be expressed in an int
654/// this size.
655static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656 uint32_t W = C1->getBitWidth();
657 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
658 if (sign) {
659 LHSExt.sext(W * 2);
660 RHSExt.sext(W * 2);
661 } else {
662 LHSExt.zext(W * 2);
663 RHSExt.zext(W * 2);
664 }
665
666 APInt MulExt = LHSExt * RHSExt;
667
668 if (sign) {
669 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671 return MulExt.slt(Min) || MulExt.sgt(Max);
672 } else
673 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
674}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676
677/// ShrinkDemandedConstant - Check to see if the specified operand of the
678/// specified instruction is a constant integer. If so, check to see if there
679/// are any bits set in the constant that are not demanded. If so, shrink the
680/// constant and return true.
681static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
682 APInt Demanded) {
683 assert(I && "No instruction?");
684 assert(OpNo < I->getNumOperands() && "Operand index too large");
685
686 // If the operand is not a constant integer, nothing to do.
687 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688 if (!OpC) return false;
689
690 // If there are no bits set that aren't demanded, nothing to do.
691 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692 if ((~Demanded & OpC->getValue()) == 0)
693 return false;
694
695 // This instruction is producing bits that are not demanded. Shrink the RHS.
696 Demanded &= OpC->getValue();
697 I->setOperand(OpNo, ConstantInt::get(Demanded));
698 return true;
699}
700
701// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
702// set of known zero and one bits, compute the maximum and minimum values that
703// could have the specified known zero and known one bits, returning them in
704// min/max.
705static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
706 const APInt& KnownZero,
707 const APInt& KnownOne,
708 APInt& Min, APInt& Max) {
709 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710 assert(KnownZero.getBitWidth() == BitWidth &&
711 KnownOne.getBitWidth() == BitWidth &&
712 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
714 APInt UnknownBits = ~(KnownZero|KnownOne);
715
716 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717 // bit if it is unknown.
718 Min = KnownOne;
719 Max = KnownOne|UnknownBits;
720
721 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
722 Min.set(BitWidth-1);
723 Max.clear(BitWidth-1);
724 }
725}
726
727// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728// a set of known zero and one bits, compute the maximum and minimum values that
729// could have the specified known zero and known one bits, returning them in
730// min/max.
731static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000732 const APInt &KnownZero,
733 const APInt &KnownOne,
734 APInt &Min, APInt &Max) {
735 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 assert(KnownZero.getBitWidth() == BitWidth &&
737 KnownOne.getBitWidth() == BitWidth &&
738 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
740 APInt UnknownBits = ~(KnownZero|KnownOne);
741
742 // The minimum value is when the unknown bits are all zeros.
743 Min = KnownOne;
744 // The maximum value is when the unknown bits are all ones.
745 Max = KnownOne|UnknownBits;
746}
747
748/// SimplifyDemandedBits - This function attempts to replace V with a simpler
749/// value based on the demanded bits. When this function is called, it is known
750/// that only the bits set in DemandedMask of the result of V are ever used
751/// downstream. Consequently, depending on the mask and V, it may be possible
752/// to replace V with a constant or one of its operands. In such cases, this
753/// function does the replacement and returns true. In all other cases, it
754/// returns false after analyzing the expression and setting KnownOne and known
755/// to be one in the expression. KnownZero contains all the bits that are known
756/// to be zero in the expression. These are provided to potentially allow the
757/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758/// the expression. KnownOne and KnownZero always follow the invariant that
759/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760/// the bits in KnownOne and KnownZero may only be accurate for those bits set
761/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762/// and KnownOne must all be the same.
763bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764 APInt& KnownZero, APInt& KnownOne,
765 unsigned Depth) {
766 assert(V != 0 && "Null pointer of Value???");
767 assert(Depth <= 6 && "Limit Search Depth");
768 uint32_t BitWidth = DemandedMask.getBitWidth();
769 const IntegerType *VTy = cast<IntegerType>(V->getType());
770 assert(VTy->getBitWidth() == BitWidth &&
771 KnownZero.getBitWidth() == BitWidth &&
772 KnownOne.getBitWidth() == BitWidth &&
773 "Value *V, DemandedMask, KnownZero and KnownOne \
774 must have same BitWidth");
775 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776 // We know all of the bits for a constant!
777 KnownOne = CI->getValue() & DemandedMask;
778 KnownZero = ~KnownOne & DemandedMask;
779 return false;
780 }
781
782 KnownZero.clear();
783 KnownOne.clear();
784 if (!V->hasOneUse()) { // Other users may use these bits.
785 if (Depth != 0) { // Not at the root.
786 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
788 return false;
789 }
790 // If this is the root being simplified, allow it to have multiple uses,
791 // just set the DemandedMask to all bits.
792 DemandedMask = APInt::getAllOnesValue(BitWidth);
793 } else if (DemandedMask == 0) { // Not demanding any bits from V.
794 if (V != UndefValue::get(VTy))
795 return UpdateValueUsesWith(V, UndefValue::get(VTy));
796 return false;
797 } else if (Depth == 6) { // Limit search depth.
798 return false;
799 }
800
801 Instruction *I = dyn_cast<Instruction>(V);
802 if (!I) return false; // Only analyze instructions.
803
804 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000807 default:
808 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
809 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 case Instruction::And:
811 // If either the LHS or the RHS are Zero, the result is zero.
812 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813 RHSKnownZero, RHSKnownOne, Depth+1))
814 return true;
815 assert((RHSKnownZero & RHSKnownOne) == 0 &&
816 "Bits known to be one AND zero?");
817
818 // If something is known zero on the RHS, the bits aren't demanded on the
819 // LHS.
820 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821 LHSKnownZero, LHSKnownOne, Depth+1))
822 return true;
823 assert((LHSKnownZero & LHSKnownOne) == 0 &&
824 "Bits known to be one AND zero?");
825
826 // If all of the demanded bits are known 1 on one side, return the other.
827 // These bits cannot contribute to the result of the 'and'.
828 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
829 (DemandedMask & ~LHSKnownZero))
830 return UpdateValueUsesWith(I, I->getOperand(0));
831 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
832 (DemandedMask & ~RHSKnownZero))
833 return UpdateValueUsesWith(I, I->getOperand(1));
834
835 // If all of the demanded bits in the inputs are known zeros, return zero.
836 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
838
839 // If the RHS is a constant, see if we can simplify it.
840 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841 return UpdateValueUsesWith(I, I);
842
843 // Output known-1 bits are only known if set in both the LHS & RHS.
844 RHSKnownOne &= LHSKnownOne;
845 // Output known-0 are known to be clear if zero in either the LHS | RHS.
846 RHSKnownZero |= LHSKnownZero;
847 break;
848 case Instruction::Or:
849 // If either the LHS or the RHS are One, the result is One.
850 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1))
852 return true;
853 assert((RHSKnownZero & RHSKnownOne) == 0 &&
854 "Bits known to be one AND zero?");
855 // If something is known one on the RHS, the bits aren't demanded on the
856 // LHS.
857 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
858 LHSKnownZero, LHSKnownOne, Depth+1))
859 return true;
860 assert((LHSKnownZero & LHSKnownOne) == 0 &&
861 "Bits known to be one AND zero?");
862
863 // If all of the demanded bits are known zero on one side, return the other.
864 // These bits cannot contribute to the result of the 'or'.
865 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
866 (DemandedMask & ~LHSKnownOne))
867 return UpdateValueUsesWith(I, I->getOperand(0));
868 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
869 (DemandedMask & ~RHSKnownOne))
870 return UpdateValueUsesWith(I, I->getOperand(1));
871
872 // If all of the potentially set bits on one side are known to be set on
873 // the other side, just use the 'other' side.
874 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
875 (DemandedMask & (~RHSKnownZero)))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
878 (DemandedMask & (~LHSKnownZero)))
879 return UpdateValueUsesWith(I, I->getOperand(1));
880
881 // If the RHS is a constant, see if we can simplify it.
882 if (ShrinkDemandedConstant(I, 1, DemandedMask))
883 return UpdateValueUsesWith(I, I);
884
885 // Output known-0 bits are only known if clear in both the LHS & RHS.
886 RHSKnownZero &= LHSKnownZero;
887 // Output known-1 are known to be set if set in either the LHS | RHS.
888 RHSKnownOne |= LHSKnownOne;
889 break;
890 case Instruction::Xor: {
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 RHSKnownZero, RHSKnownOne, Depth+1))
893 return true;
894 assert((RHSKnownZero & RHSKnownOne) == 0 &&
895 "Bits known to be one AND zero?");
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
897 LHSKnownZero, LHSKnownOne, Depth+1))
898 return true;
899 assert((LHSKnownZero & LHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
901
902 // If all of the demanded bits are known zero on one side, return the other.
903 // These bits cannot contribute to the result of the 'xor'.
904 if ((DemandedMask & RHSKnownZero) == DemandedMask)
905 return UpdateValueUsesWith(I, I->getOperand(0));
906 if ((DemandedMask & LHSKnownZero) == DemandedMask)
907 return UpdateValueUsesWith(I, I->getOperand(1));
908
909 // Output known-0 bits are known if clear or set in both the LHS & RHS.
910 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
911 (RHSKnownOne & LHSKnownOne);
912 // Output known-1 are known to be set if set in only one of the LHS, RHS.
913 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
914 (RHSKnownOne & LHSKnownZero);
915
916 // If all of the demanded bits are known to be zero on one side or the
917 // other, turn this into an *inclusive* or.
918 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
920 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +0000921 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 I->getName());
923 InsertNewInstBefore(Or, *I);
924 return UpdateValueUsesWith(I, Or);
925 }
926
927 // If all of the demanded bits on one side are known, and all of the set
928 // bits on that side are also known to be set on the other side, turn this
929 // into an AND, as we know the bits will be cleared.
930 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
932 // all known
933 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
935 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +0000936 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937 InsertNewInstBefore(And, *I);
938 return UpdateValueUsesWith(I, And);
939 }
940 }
941
942 // If the RHS is a constant, see if we can simplify it.
943 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944 if (ShrinkDemandedConstant(I, 1, DemandedMask))
945 return UpdateValueUsesWith(I, I);
946
947 RHSKnownZero = KnownZeroOut;
948 RHSKnownOne = KnownOneOut;
949 break;
950 }
951 case Instruction::Select:
952 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1))
954 return true;
955 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
956 LHSKnownZero, LHSKnownOne, Depth+1))
957 return true;
958 assert((RHSKnownZero & RHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960 assert((LHSKnownZero & LHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
962
963 // If the operands are constants, see if we can simplify them.
964 if (ShrinkDemandedConstant(I, 1, DemandedMask))
965 return UpdateValueUsesWith(I, I);
966 if (ShrinkDemandedConstant(I, 2, DemandedMask))
967 return UpdateValueUsesWith(I, I);
968
969 // Only known if known in both the LHS and RHS.
970 RHSKnownOne &= LHSKnownOne;
971 RHSKnownZero &= LHSKnownZero;
972 break;
973 case Instruction::Trunc: {
974 uint32_t truncBf =
975 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
976 DemandedMask.zext(truncBf);
977 RHSKnownZero.zext(truncBf);
978 RHSKnownOne.zext(truncBf);
979 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
980 RHSKnownZero, RHSKnownOne, Depth+1))
981 return true;
982 DemandedMask.trunc(BitWidth);
983 RHSKnownZero.trunc(BitWidth);
984 RHSKnownOne.trunc(BitWidth);
985 assert((RHSKnownZero & RHSKnownOne) == 0 &&
986 "Bits known to be one AND zero?");
987 break;
988 }
989 case Instruction::BitCast:
990 if (!I->getOperand(0)->getType()->isInteger())
991 return false;
992
993 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994 RHSKnownZero, RHSKnownOne, Depth+1))
995 return true;
996 assert((RHSKnownZero & RHSKnownOne) == 0 &&
997 "Bits known to be one AND zero?");
998 break;
999 case Instruction::ZExt: {
1000 // Compute the bits in the result that are not present in the input.
1001 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1002 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1003
1004 DemandedMask.trunc(SrcBitWidth);
1005 RHSKnownZero.trunc(SrcBitWidth);
1006 RHSKnownOne.trunc(SrcBitWidth);
1007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1))
1009 return true;
1010 DemandedMask.zext(BitWidth);
1011 RHSKnownZero.zext(BitWidth);
1012 RHSKnownOne.zext(BitWidth);
1013 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1014 "Bits known to be one AND zero?");
1015 // The top bits are known to be zero.
1016 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1017 break;
1018 }
1019 case Instruction::SExt: {
1020 // Compute the bits in the result that are not present in the input.
1021 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1022 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1023
1024 APInt InputDemandedBits = DemandedMask &
1025 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1026
1027 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1028 // If any of the sign extended bits are demanded, we know that the sign
1029 // bit is demanded.
1030 if ((NewBits & DemandedMask) != 0)
1031 InputDemandedBits.set(SrcBitWidth-1);
1032
1033 InputDemandedBits.trunc(SrcBitWidth);
1034 RHSKnownZero.trunc(SrcBitWidth);
1035 RHSKnownOne.trunc(SrcBitWidth);
1036 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037 RHSKnownZero, RHSKnownOne, Depth+1))
1038 return true;
1039 InputDemandedBits.zext(BitWidth);
1040 RHSKnownZero.zext(BitWidth);
1041 RHSKnownOne.zext(BitWidth);
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1044
1045 // If the sign bit of the input is known set or clear, then we know the
1046 // top bits of the result.
1047
1048 // If the input sign bit is known zero, or if the NewBits are not demanded
1049 // convert this into a zero extension.
1050 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1051 {
1052 // Convert to ZExt cast
1053 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054 return UpdateValueUsesWith(I, NewCast);
1055 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1056 RHSKnownOne |= NewBits;
1057 }
1058 break;
1059 }
1060 case Instruction::Add: {
1061 // Figure out what the input bits are. If the top bits of the and result
1062 // are not demanded, then the add doesn't demand them from its input
1063 // either.
1064 uint32_t NLZ = DemandedMask.countLeadingZeros();
1065
1066 // If there is a constant on the RHS, there are a variety of xformations
1067 // we can do.
1068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069 // If null, this should be simplified elsewhere. Some of the xforms here
1070 // won't work if the RHS is zero.
1071 if (RHS->isZero())
1072 break;
1073
1074 // If the top bit of the output is demanded, demand everything from the
1075 // input. Otherwise, we demand all the input bits except NLZ top bits.
1076 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1077
1078 // Find information about known zero/one bits in the input.
1079 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1080 LHSKnownZero, LHSKnownOne, Depth+1))
1081 return true;
1082
1083 // If the RHS of the add has bits set that can't affect the input, reduce
1084 // the constant.
1085 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086 return UpdateValueUsesWith(I, I);
1087
1088 // Avoid excess work.
1089 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1090 break;
1091
1092 // Turn it into OR if input bits are zero.
1093 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1094 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001095 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 I->getName());
1097 InsertNewInstBefore(Or, *I);
1098 return UpdateValueUsesWith(I, Or);
1099 }
1100
1101 // We can say something about the output known-zero and known-one bits,
1102 // depending on potential carries from the input constant and the
1103 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1104 // bits set and the RHS constant is 0x01001, then we know we have a known
1105 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1106
1107 // To compute this, we first compute the potential carry bits. These are
1108 // the bits which may be modified. I'm not aware of a better way to do
1109 // this scan.
1110 const APInt& RHSVal = RHS->getValue();
1111 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1112
1113 // Now that we know which bits have carries, compute the known-1/0 sets.
1114
1115 // Bits are known one if they are known zero in one operand and one in the
1116 // other, and there is no input carry.
1117 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1118 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1119
1120 // Bits are known zero if they are known zero in both operands and there
1121 // is no input carry.
1122 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1123 } else {
1124 // If the high-bits of this ADD are not demanded, then it does not demand
1125 // the high bits of its LHS or RHS.
1126 if (DemandedMask[BitWidth-1] == 0) {
1127 // Right fill the mask of bits for this ADD to demand the most
1128 // significant bit and all those below it.
1129 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1130 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131 LHSKnownZero, LHSKnownOne, Depth+1))
1132 return true;
1133 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134 LHSKnownZero, LHSKnownOne, Depth+1))
1135 return true;
1136 }
1137 }
1138 break;
1139 }
1140 case Instruction::Sub:
1141 // If the high-bits of this SUB are not demanded, then it does not demand
1142 // the high bits of its LHS or RHS.
1143 if (DemandedMask[BitWidth-1] == 0) {
1144 // Right fill the mask of bits for this SUB to demand the most
1145 // significant bit and all those below it.
1146 uint32_t NLZ = DemandedMask.countLeadingZeros();
1147 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1148 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149 LHSKnownZero, LHSKnownOne, Depth+1))
1150 return true;
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152 LHSKnownZero, LHSKnownOne, Depth+1))
1153 return true;
1154 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001155 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156 // the known zeros and ones.
1157 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 break;
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1164 RHSKnownZero, RHSKnownOne, Depth+1))
1165 return true;
1166 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1167 "Bits known to be one AND zero?");
1168 RHSKnownZero <<= ShiftAmt;
1169 RHSKnownOne <<= ShiftAmt;
1170 // low bits known zero.
1171 if (ShiftAmt)
1172 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1173 }
1174 break;
1175 case Instruction::LShr:
1176 // For a logical shift right
1177 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1179
1180 // Unsigned shift right.
1181 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1183 RHSKnownZero, RHSKnownOne, Depth+1))
1184 return true;
1185 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1186 "Bits known to be one AND zero?");
1187 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1189 if (ShiftAmt) {
1190 // Compute the new bits that are at the top now.
1191 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1192 RHSKnownZero |= HighBits; // high bits known zero.
1193 }
1194 }
1195 break;
1196 case Instruction::AShr:
1197 // If this is an arithmetic shift right and only the low-bit is set, we can
1198 // always convert this into a logical shr, even if the shift amount is
1199 // variable. The low bit of the shift cannot be an input sign bit unless
1200 // the shift amount is >= the size of the datatype, which is undefined.
1201 if (DemandedMask == 1) {
1202 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001203 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 I->getOperand(0), I->getOperand(1), I->getName());
1205 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206 return UpdateValueUsesWith(I, NewVal);
1207 }
1208
1209 // If the sign bit is the only bit demanded by this ashr, then there is no
1210 // need to do it, the shift doesn't change the high bit.
1211 if (DemandedMask.isSignBit())
1212 return UpdateValueUsesWith(I, I->getOperand(0));
1213
1214 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1216
1217 // Signed shift right.
1218 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1219 // If any of the "high bits" are demanded, we should set the sign bit as
1220 // demanded.
1221 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222 DemandedMaskIn.set(BitWidth-1);
1223 if (SimplifyDemandedBits(I->getOperand(0),
1224 DemandedMaskIn,
1225 RHSKnownZero, RHSKnownOne, Depth+1))
1226 return true;
1227 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1228 "Bits known to be one AND zero?");
1229 // Compute the new bits that are at the top now.
1230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1233
1234 // Handle the sign bits.
1235 APInt SignBit(APInt::getSignBit(BitWidth));
1236 // Adjust to where it is now in the mask.
1237 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1238
1239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001241 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001242 (HighBits & ~DemandedMask) == HighBits) {
1243 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001244 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 I->getOperand(0), SA, I->getName());
1246 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247 return UpdateValueUsesWith(I, NewVal);
1248 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249 RHSKnownOne |= HighBits;
1250 }
1251 }
1252 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001253 case Instruction::SRem:
1254 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255 APInt RA = Rem->getValue();
1256 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001257 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001258 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1259 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1260 LHSKnownZero, LHSKnownOne, Depth+1))
1261 return true;
1262
1263 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1264 LHSKnownZero |= ~LowBits;
1265 else if (LHSKnownOne[BitWidth-1])
1266 LHSKnownOne |= ~LowBits;
1267
1268 KnownZero |= LHSKnownZero & DemandedMask;
1269 KnownOne |= LHSKnownOne & DemandedMask;
1270
1271 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1272 }
1273 }
1274 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001275 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001276 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001278 if (RA.isPowerOf2()) {
1279 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001280 APInt Mask2 = LowBits & DemandedMask;
1281 KnownZero |= ~LowBits & DemandedMask;
1282 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1283 KnownZero, KnownOne, Depth+1))
1284 return true;
1285
1286 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001287 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001288 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001289 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001290
1291 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1292 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001293 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1294 KnownZero2, KnownOne2, Depth+1))
1295 return true;
1296
Dan Gohmanbec16052008-04-28 17:02:21 +00001297 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001298 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001299 KnownZero2, KnownOne2, Depth+1))
1300 return true;
1301
1302 Leaders = std::max(Leaders,
1303 KnownZero2.countLeadingOnes());
1304 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001305 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001307 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308
1309 // If the client is only demanding bits that we know, return the known
1310 // constant.
1311 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1312 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1313 return false;
1314}
1315
1316
1317/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1318/// 64 or fewer elements. DemandedElts contains the set of elements that are
1319/// actually used by the caller. This method analyzes which elements of the
1320/// operand are undef and returns that information in UndefElts.
1321///
1322/// If the information about demanded elements can be used to simplify the
1323/// operation, the operation is simplified, then the resultant value is
1324/// returned. This returns null if no change was made.
1325Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1326 uint64_t &UndefElts,
1327 unsigned Depth) {
1328 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1329 assert(VWidth <= 64 && "Vector too wide to analyze!");
1330 uint64_t EltMask = ~0ULL >> (64-VWidth);
1331 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1332 "Invalid DemandedElts!");
1333
1334 if (isa<UndefValue>(V)) {
1335 // If the entire vector is undefined, just return this info.
1336 UndefElts = EltMask;
1337 return 0;
1338 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1339 UndefElts = EltMask;
1340 return UndefValue::get(V->getType());
1341 }
1342
1343 UndefElts = 0;
1344 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1345 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1346 Constant *Undef = UndefValue::get(EltTy);
1347
1348 std::vector<Constant*> Elts;
1349 for (unsigned i = 0; i != VWidth; ++i)
1350 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1351 Elts.push_back(Undef);
1352 UndefElts |= (1ULL << i);
1353 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1354 Elts.push_back(Undef);
1355 UndefElts |= (1ULL << i);
1356 } else { // Otherwise, defined.
1357 Elts.push_back(CP->getOperand(i));
1358 }
1359
1360 // If we changed the constant, return it.
1361 Constant *NewCP = ConstantVector::get(Elts);
1362 return NewCP != CP ? NewCP : 0;
1363 } else if (isa<ConstantAggregateZero>(V)) {
1364 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1365 // set to undef.
1366 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1367 Constant *Zero = Constant::getNullValue(EltTy);
1368 Constant *Undef = UndefValue::get(EltTy);
1369 std::vector<Constant*> Elts;
1370 for (unsigned i = 0; i != VWidth; ++i)
1371 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1372 UndefElts = DemandedElts ^ EltMask;
1373 return ConstantVector::get(Elts);
1374 }
1375
1376 if (!V->hasOneUse()) { // Other users may use these bits.
1377 if (Depth != 0) { // Not at the root.
1378 // TODO: Just compute the UndefElts information recursively.
1379 return false;
1380 }
1381 return false;
1382 } else if (Depth == 10) { // Limit search depth.
1383 return false;
1384 }
1385
1386 Instruction *I = dyn_cast<Instruction>(V);
1387 if (!I) return false; // Only analyze instructions.
1388
1389 bool MadeChange = false;
1390 uint64_t UndefElts2;
1391 Value *TmpV;
1392 switch (I->getOpcode()) {
1393 default: break;
1394
1395 case Instruction::InsertElement: {
1396 // If this is a variable index, we don't know which element it overwrites.
1397 // demand exactly the same input as we produce.
1398 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1399 if (Idx == 0) {
1400 // Note that we can't propagate undef elt info, because we don't know
1401 // which elt is getting updated.
1402 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1403 UndefElts2, Depth+1);
1404 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1405 break;
1406 }
1407
1408 // If this is inserting an element that isn't demanded, remove this
1409 // insertelement.
1410 unsigned IdxNo = Idx->getZExtValue();
1411 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1412 return AddSoonDeadInstToWorklist(*I, 0);
1413
1414 // Otherwise, the element inserted overwrites whatever was there, so the
1415 // input demanded set is simpler than the output set.
1416 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1417 DemandedElts & ~(1ULL << IdxNo),
1418 UndefElts, Depth+1);
1419 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1420
1421 // The inserted element is defined.
1422 UndefElts |= 1ULL << IdxNo;
1423 break;
1424 }
1425 case Instruction::BitCast: {
1426 // Vector->vector casts only.
1427 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1428 if (!VTy) break;
1429 unsigned InVWidth = VTy->getNumElements();
1430 uint64_t InputDemandedElts = 0;
1431 unsigned Ratio;
1432
1433 if (VWidth == InVWidth) {
1434 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1435 // elements as are demanded of us.
1436 Ratio = 1;
1437 InputDemandedElts = DemandedElts;
1438 } else if (VWidth > InVWidth) {
1439 // Untested so far.
1440 break;
1441
1442 // If there are more elements in the result than there are in the source,
1443 // then an input element is live if any of the corresponding output
1444 // elements are live.
1445 Ratio = VWidth/InVWidth;
1446 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1447 if (DemandedElts & (1ULL << OutIdx))
1448 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1449 }
1450 } else {
1451 // Untested so far.
1452 break;
1453
1454 // If there are more elements in the source than there are in the result,
1455 // then an input element is live if the corresponding output element is
1456 // live.
1457 Ratio = InVWidth/VWidth;
1458 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1459 if (DemandedElts & (1ULL << InIdx/Ratio))
1460 InputDemandedElts |= 1ULL << InIdx;
1461 }
1462
1463 // div/rem demand all inputs, because they don't want divide by zero.
1464 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1465 UndefElts2, Depth+1);
1466 if (TmpV) {
1467 I->setOperand(0, TmpV);
1468 MadeChange = true;
1469 }
1470
1471 UndefElts = UndefElts2;
1472 if (VWidth > InVWidth) {
1473 assert(0 && "Unimp");
1474 // If there are more elements in the result than there are in the source,
1475 // then an output element is undef if the corresponding input element is
1476 // undef.
1477 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1478 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1479 UndefElts |= 1ULL << OutIdx;
1480 } else if (VWidth < InVWidth) {
1481 assert(0 && "Unimp");
1482 // If there are more elements in the source than there are in the result,
1483 // then a result element is undef if all of the corresponding input
1484 // elements are undef.
1485 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1486 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1487 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1488 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1489 }
1490 break;
1491 }
1492 case Instruction::And:
1493 case Instruction::Or:
1494 case Instruction::Xor:
1495 case Instruction::Add:
1496 case Instruction::Sub:
1497 case Instruction::Mul:
1498 // div/rem demand all inputs, because they don't want divide by zero.
1499 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1500 UndefElts, Depth+1);
1501 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1502 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1503 UndefElts2, Depth+1);
1504 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1505
1506 // Output elements are undefined if both are undefined. Consider things
1507 // like undef&0. The result is known zero, not undef.
1508 UndefElts &= UndefElts2;
1509 break;
1510
1511 case Instruction::Call: {
1512 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1513 if (!II) break;
1514 switch (II->getIntrinsicID()) {
1515 default: break;
1516
1517 // Binary vector operations that work column-wise. A dest element is a
1518 // function of the corresponding input elements from the two inputs.
1519 case Intrinsic::x86_sse_sub_ss:
1520 case Intrinsic::x86_sse_mul_ss:
1521 case Intrinsic::x86_sse_min_ss:
1522 case Intrinsic::x86_sse_max_ss:
1523 case Intrinsic::x86_sse2_sub_sd:
1524 case Intrinsic::x86_sse2_mul_sd:
1525 case Intrinsic::x86_sse2_min_sd:
1526 case Intrinsic::x86_sse2_max_sd:
1527 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1528 UndefElts, Depth+1);
1529 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1530 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1531 UndefElts2, Depth+1);
1532 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1533
1534 // If only the low elt is demanded and this is a scalarizable intrinsic,
1535 // scalarize it now.
1536 if (DemandedElts == 1) {
1537 switch (II->getIntrinsicID()) {
1538 default: break;
1539 case Intrinsic::x86_sse_sub_ss:
1540 case Intrinsic::x86_sse_mul_ss:
1541 case Intrinsic::x86_sse2_sub_sd:
1542 case Intrinsic::x86_sse2_mul_sd:
1543 // TODO: Lower MIN/MAX/ABS/etc
1544 Value *LHS = II->getOperand(1);
1545 Value *RHS = II->getOperand(2);
1546 // Extract the element as scalars.
1547 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1548 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1549
1550 switch (II->getIntrinsicID()) {
1551 default: assert(0 && "Case stmts out of sync!");
1552 case Intrinsic::x86_sse_sub_ss:
1553 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001554 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001555 II->getName()), *II);
1556 break;
1557 case Intrinsic::x86_sse_mul_ss:
1558 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001559 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 II->getName()), *II);
1561 break;
1562 }
1563
1564 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001565 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1566 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001567 InsertNewInstBefore(New, *II);
1568 AddSoonDeadInstToWorklist(*II, 0);
1569 return New;
1570 }
1571 }
1572
1573 // Output elements are undefined if both are undefined. Consider things
1574 // like undef&0. The result is known zero, not undef.
1575 UndefElts &= UndefElts2;
1576 break;
1577 }
1578 break;
1579 }
1580 }
1581 return MadeChange ? I : 0;
1582}
1583
Dan Gohman5d56fd42008-05-19 22:14:15 +00001584
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585/// AssociativeOpt - Perform an optimization on an associative operator. This
1586/// function is designed to check a chain of associative operators for a
1587/// potential to apply a certain optimization. Since the optimization may be
1588/// applicable if the expression was reassociated, this checks the chain, then
1589/// reassociates the expression as necessary to expose the optimization
1590/// opportunity. This makes use of a special Functor, which must define
1591/// 'shouldApply' and 'apply' methods.
1592///
1593template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001594static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001595 unsigned Opcode = Root.getOpcode();
1596 Value *LHS = Root.getOperand(0);
1597
1598 // Quick check, see if the immediate LHS matches...
1599 if (F.shouldApply(LHS))
1600 return F.apply(Root);
1601
1602 // Otherwise, if the LHS is not of the same opcode as the root, return.
1603 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1604 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1605 // Should we apply this transform to the RHS?
1606 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1607
1608 // If not to the RHS, check to see if we should apply to the LHS...
1609 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1610 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1611 ShouldApply = true;
1612 }
1613
1614 // If the functor wants to apply the optimization to the RHS of LHSI,
1615 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1616 if (ShouldApply) {
1617 BasicBlock *BB = Root.getParent();
1618
1619 // Now all of the instructions are in the current basic block, go ahead
1620 // and perform the reassociation.
1621 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1622
1623 // First move the selected RHS to the LHS of the root...
1624 Root.setOperand(0, LHSI->getOperand(1));
1625
1626 // Make what used to be the LHS of the root be the user of the root...
1627 Value *ExtraOperand = TmpLHSI->getOperand(1);
1628 if (&Root == TmpLHSI) {
1629 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1630 return 0;
1631 }
1632 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1633 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1634 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1635 BasicBlock::iterator ARI = &Root; ++ARI;
1636 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1637 ARI = Root;
1638
1639 // Now propagate the ExtraOperand down the chain of instructions until we
1640 // get to LHSI.
1641 while (TmpLHSI != LHSI) {
1642 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1643 // Move the instruction to immediately before the chain we are
1644 // constructing to avoid breaking dominance properties.
1645 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1646 BB->getInstList().insert(ARI, NextLHSI);
1647 ARI = NextLHSI;
1648
1649 Value *NextOp = NextLHSI->getOperand(1);
1650 NextLHSI->setOperand(1, ExtraOperand);
1651 TmpLHSI = NextLHSI;
1652 ExtraOperand = NextOp;
1653 }
1654
1655 // Now that the instructions are reassociated, have the functor perform
1656 // the transformation...
1657 return F.apply(Root);
1658 }
1659
1660 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1661 }
1662 return 0;
1663}
1664
Dan Gohman089efff2008-05-13 00:00:25 +00001665namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666
Nick Lewycky27f6c132008-05-23 04:34:58 +00001667// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668struct AddRHS {
1669 Value *RHS;
1670 AddRHS(Value *rhs) : RHS(rhs) {}
1671 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1672 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001673 return BinaryOperator::CreateShl(Add.getOperand(0),
1674 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001675 }
1676};
1677
1678// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1679// iff C1&C2 == 0
1680struct AddMaskingAnd {
1681 Constant *C2;
1682 AddMaskingAnd(Constant *c) : C2(c) {}
1683 bool shouldApply(Value *LHS) const {
1684 ConstantInt *C1;
1685 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1686 ConstantExpr::getAnd(C1, C2)->isNullValue();
1687 }
1688 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001689 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690 }
1691};
1692
Dan Gohman089efff2008-05-13 00:00:25 +00001693}
1694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001695static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1696 InstCombiner *IC) {
1697 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1698 if (Constant *SOC = dyn_cast<Constant>(SO))
1699 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1700
Gabor Greifa645dd32008-05-16 19:29:10 +00001701 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1703 }
1704
1705 // Figure out if the constant is the left or the right argument.
1706 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1707 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1708
1709 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1710 if (ConstIsRHS)
1711 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1712 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1713 }
1714
1715 Value *Op0 = SO, *Op1 = ConstOperand;
1716 if (!ConstIsRHS)
1717 std::swap(Op0, Op1);
1718 Instruction *New;
1719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001720 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001721 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001722 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 SO->getName()+".cmp");
1724 else {
1725 assert(0 && "Unknown binary instruction type!");
1726 abort();
1727 }
1728 return IC->InsertNewInstBefore(New, I);
1729}
1730
1731// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1732// constant as the other operand, try to fold the binary operator into the
1733// select arguments. This also works for Cast instructions, which obviously do
1734// not have a second operand.
1735static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1736 InstCombiner *IC) {
1737 // Don't modify shared select instructions
1738 if (!SI->hasOneUse()) return 0;
1739 Value *TV = SI->getOperand(1);
1740 Value *FV = SI->getOperand(2);
1741
1742 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1743 // Bool selects with constant operands can be folded to logical ops.
1744 if (SI->getType() == Type::Int1Ty) return 0;
1745
1746 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1747 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1748
Gabor Greifd6da1d02008-04-06 20:25:17 +00001749 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1750 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001751 }
1752 return 0;
1753}
1754
1755
1756/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1757/// node as operand #0, see if we can fold the instruction into the PHI (which
1758/// is only possible if all operands to the PHI are constants).
1759Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1760 PHINode *PN = cast<PHINode>(I.getOperand(0));
1761 unsigned NumPHIValues = PN->getNumIncomingValues();
1762 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1763
1764 // Check to see if all of the operands of the PHI are constants. If there is
1765 // one non-constant value, remember the BB it is. If there is more than one
1766 // or if *it* is a PHI, bail out.
1767 BasicBlock *NonConstBB = 0;
1768 for (unsigned i = 0; i != NumPHIValues; ++i)
1769 if (!isa<Constant>(PN->getIncomingValue(i))) {
1770 if (NonConstBB) return 0; // More than one non-const value.
1771 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1772 NonConstBB = PN->getIncomingBlock(i);
1773
1774 // If the incoming non-constant value is in I's block, we have an infinite
1775 // loop.
1776 if (NonConstBB == I.getParent())
1777 return 0;
1778 }
1779
1780 // If there is exactly one non-constant value, we can insert a copy of the
1781 // operation in that block. However, if this is a critical edge, we would be
1782 // inserting the computation one some other paths (e.g. inside a loop). Only
1783 // do this if the pred block is unconditionally branching into the phi block.
1784 if (NonConstBB) {
1785 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1786 if (!BI || !BI->isUnconditional()) return 0;
1787 }
1788
1789 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001790 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1792 InsertNewInstBefore(NewPN, *PN);
1793 NewPN->takeName(PN);
1794
1795 // Next, add all of the operands to the PHI.
1796 if (I.getNumOperands() == 2) {
1797 Constant *C = cast<Constant>(I.getOperand(1));
1798 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001799 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1801 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1802 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1803 else
1804 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1805 } else {
1806 assert(PN->getIncomingBlock(i) == NonConstBB);
1807 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001808 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809 PN->getIncomingValue(i), C, "phitmp",
1810 NonConstBB->getTerminator());
1811 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001812 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813 CI->getPredicate(),
1814 PN->getIncomingValue(i), C, "phitmp",
1815 NonConstBB->getTerminator());
1816 else
1817 assert(0 && "Unknown binop!");
1818
1819 AddToWorkList(cast<Instruction>(InV));
1820 }
1821 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1822 }
1823 } else {
1824 CastInst *CI = cast<CastInst>(&I);
1825 const Type *RetTy = CI->getType();
1826 for (unsigned i = 0; i != NumPHIValues; ++i) {
1827 Value *InV;
1828 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1829 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1830 } else {
1831 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001832 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001833 I.getType(), "phitmp",
1834 NonConstBB->getTerminator());
1835 AddToWorkList(cast<Instruction>(InV));
1836 }
1837 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1838 }
1839 }
1840 return ReplaceInstUsesWith(I, NewPN);
1841}
1842
Chris Lattner55476162008-01-29 06:52:45 +00001843
Chris Lattner3554f972008-05-20 05:46:13 +00001844/// WillNotOverflowSignedAdd - Return true if we can prove that:
1845/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1846/// This basically requires proving that the add in the original type would not
1847/// overflow to change the sign bit or have a carry out.
1848bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1849 // There are different heuristics we can use for this. Here are some simple
1850 // ones.
1851
1852 // Add has the property that adding any two 2's complement numbers can only
1853 // have one carry bit which can change a sign. As such, if LHS and RHS each
1854 // have at least two sign bits, we know that the addition of the two values will
1855 // sign extend fine.
1856 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1857 return true;
1858
1859
1860 // If one of the operands only has one non-zero bit, and if the other operand
1861 // has a known-zero bit in a more significant place than it (not including the
1862 // sign bit) the ripple may go up to and fill the zero, but won't change the
1863 // sign. For example, (X & ~4) + 1.
1864
1865 // TODO: Implement.
1866
1867 return false;
1868}
1869
Chris Lattner55476162008-01-29 06:52:45 +00001870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001871Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1872 bool Changed = SimplifyCommutative(I);
1873 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1874
1875 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1876 // X + undef -> undef
1877 if (isa<UndefValue>(RHS))
1878 return ReplaceInstUsesWith(I, RHS);
1879
1880 // X + 0 --> X
1881 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1882 if (RHSC->isNullValue())
1883 return ReplaceInstUsesWith(I, LHS);
1884 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001885 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1886 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001887 return ReplaceInstUsesWith(I, LHS);
1888 }
1889
1890 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1891 // X + (signbit) --> X ^ signbit
1892 const APInt& Val = CI->getValue();
1893 uint32_t BitWidth = Val.getBitWidth();
1894 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00001895 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896
1897 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1898 // (X & 254)+1 -> (X&254)|1
1899 if (!isa<VectorType>(I.getType())) {
1900 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1901 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1902 KnownZero, KnownOne))
1903 return &I;
1904 }
1905 }
1906
1907 if (isa<PHINode>(LHS))
1908 if (Instruction *NV = FoldOpIntoPhi(I))
1909 return NV;
1910
1911 ConstantInt *XorRHS = 0;
1912 Value *XorLHS = 0;
1913 if (isa<ConstantInt>(RHSC) &&
1914 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1915 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1916 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1917
1918 uint32_t Size = TySizeBits / 2;
1919 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1920 APInt CFF80Val(-C0080Val);
1921 do {
1922 if (TySizeBits > Size) {
1923 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1924 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1925 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1926 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1927 // This is a sign extend if the top bits are known zero.
1928 if (!MaskedValueIsZero(XorLHS,
1929 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1930 Size = 0; // Not a sign ext, but can't be any others either.
1931 break;
1932 }
1933 }
1934 Size >>= 1;
1935 C0080Val = APIntOps::lshr(C0080Val, Size);
1936 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1937 } while (Size >= 1);
1938
1939 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00001940 // with funny bit widths then this switch statement should be removed. It
1941 // is just here to get the size of the "middle" type back up to something
1942 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943 const Type *MiddleType = 0;
1944 switch (Size) {
1945 default: break;
1946 case 32: MiddleType = Type::Int32Ty; break;
1947 case 16: MiddleType = Type::Int16Ty; break;
1948 case 8: MiddleType = Type::Int8Ty; break;
1949 }
1950 if (MiddleType) {
1951 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1952 InsertNewInstBefore(NewTrunc, I);
1953 return new SExtInst(NewTrunc, I.getType(), I.getName());
1954 }
1955 }
1956 }
1957
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001958 if (I.getType() == Type::Int1Ty)
1959 return BinaryOperator::CreateXor(LHS, RHS);
1960
Nick Lewycky4d474cd2008-05-23 04:39:38 +00001961 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00001962 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1964
1965 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1966 if (RHSI->getOpcode() == Instruction::Sub)
1967 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1968 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1969 }
1970 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1971 if (LHSI->getOpcode() == Instruction::Sub)
1972 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1973 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1974 }
1975 }
1976
1977 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00001978 // -A + -B --> -(A + B)
1979 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00001980 if (LHS->getType()->isIntOrIntVector()) {
1981 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00001982 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00001983 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00001984 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00001985 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00001986 }
1987
Gabor Greifa645dd32008-05-16 19:29:10 +00001988 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00001989 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001990
1991 // A + -B --> A - B
1992 if (!isa<Constant>(RHS))
1993 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00001994 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001995
1996
1997 ConstantInt *C2;
1998 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1999 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002000 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001
2002 // X*C1 + X*C2 --> X * (C1+C2)
2003 ConstantInt *C1;
2004 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002005 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002006 }
2007
2008 // X + X*C --> X * (C+1)
2009 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002010 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002011
2012 // X + ~X --> -1 since ~X = -X-1
2013 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2014 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2015
2016
2017 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2018 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2019 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2020 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002021
2022 // A+B --> A|B iff A and B have no bits set in common.
2023 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2024 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2025 APInt LHSKnownOne(IT->getBitWidth(), 0);
2026 APInt LHSKnownZero(IT->getBitWidth(), 0);
2027 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2028 if (LHSKnownZero != 0) {
2029 APInt RHSKnownOne(IT->getBitWidth(), 0);
2030 APInt RHSKnownZero(IT->getBitWidth(), 0);
2031 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2032
2033 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002034 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002035 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002036 }
2037 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002038
Nick Lewycky83598a72008-02-03 07:42:09 +00002039 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002040 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002041 Value *W, *X, *Y, *Z;
2042 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2043 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2044 if (W != Y) {
2045 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002046 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002047 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002048 std::swap(W, X);
2049 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002050 std::swap(Y, Z);
2051 std::swap(W, X);
2052 }
2053 }
2054
2055 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002056 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002057 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002058 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002059 }
2060 }
2061 }
2062
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2064 Value *X = 0;
2065 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002066 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002067
2068 // (X & FF00) + xx00 -> (X+xx00) & FF00
2069 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2070 Constant *Anded = And(CRHS, C2);
2071 if (Anded == CRHS) {
2072 // See if all bits from the first bit set in the Add RHS up are included
2073 // in the mask. First, get the rightmost bit.
2074 const APInt& AddRHSV = CRHS->getValue();
2075
2076 // Form a mask of all bits from the lowest bit added through the top.
2077 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2078
2079 // See if the and mask includes all of these bits.
2080 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2081
2082 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2083 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002084 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002086 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002087 }
2088 }
2089 }
2090
2091 // Try to fold constant add into select arguments.
2092 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2093 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2094 return R;
2095 }
2096
2097 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002098 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 {
2100 CastInst *CI = dyn_cast<CastInst>(LHS);
2101 Value *Other = RHS;
2102 if (!CI) {
2103 CI = dyn_cast<CastInst>(RHS);
2104 Other = LHS;
2105 }
2106 if (CI && CI->getType()->isSized() &&
2107 (CI->getType()->getPrimitiveSizeInBits() ==
2108 TD->getIntPtrType()->getPrimitiveSizeInBits())
2109 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002110 unsigned AS =
2111 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002112 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2113 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002114 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002115 return new PtrToIntInst(I2, CI->getType());
2116 }
2117 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002118
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002119 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002120 {
2121 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2122 Value *Other = RHS;
2123 if (!SI) {
2124 SI = dyn_cast<SelectInst>(RHS);
2125 Other = LHS;
2126 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002127 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002128 Value *TV = SI->getTrueValue();
2129 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002130 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002131
2132 // Can we fold the add into the argument of the select?
2133 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002134 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2135 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002136 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002137 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2138 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002139 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002140 }
2141 }
Chris Lattner55476162008-01-29 06:52:45 +00002142
2143 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2144 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2145 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2146 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002147
Chris Lattner3554f972008-05-20 05:46:13 +00002148 // Check for (add (sext x), y), see if we can merge this into an
2149 // integer add followed by a sext.
2150 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2151 // (add (sext x), cst) --> (sext (add x, cst'))
2152 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2153 Constant *CI =
2154 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2155 if (LHSConv->hasOneUse() &&
2156 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2157 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2158 // Insert the new, smaller add.
2159 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2160 CI, "addconv");
2161 InsertNewInstBefore(NewAdd, I);
2162 return new SExtInst(NewAdd, I.getType());
2163 }
2164 }
2165
2166 // (add (sext x), (sext y)) --> (sext (add int x, y))
2167 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2168 // Only do this if x/y have the same type, if at last one of them has a
2169 // single use (so we don't increase the number of sexts), and if the
2170 // integer add will not overflow.
2171 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2172 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2173 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2174 RHSConv->getOperand(0))) {
2175 // Insert the new integer add.
2176 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2177 RHSConv->getOperand(0),
2178 "addconv");
2179 InsertNewInstBefore(NewAdd, I);
2180 return new SExtInst(NewAdd, I.getType());
2181 }
2182 }
2183 }
2184
2185 // Check for (add double (sitofp x), y), see if we can merge this into an
2186 // integer add followed by a promotion.
2187 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2188 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2189 // ... if the constant fits in the integer value. This is useful for things
2190 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2191 // requires a constant pool load, and generally allows the add to be better
2192 // instcombined.
2193 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2194 Constant *CI =
2195 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2196 if (LHSConv->hasOneUse() &&
2197 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2198 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2199 // Insert the new integer add.
2200 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2201 CI, "addconv");
2202 InsertNewInstBefore(NewAdd, I);
2203 return new SIToFPInst(NewAdd, I.getType());
2204 }
2205 }
2206
2207 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2208 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2209 // Only do this if x/y have the same type, if at last one of them has a
2210 // single use (so we don't increase the number of int->fp conversions),
2211 // and if the integer add will not overflow.
2212 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2213 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2214 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2215 RHSConv->getOperand(0))) {
2216 // Insert the new integer add.
2217 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2218 RHSConv->getOperand(0),
2219 "addconv");
2220 InsertNewInstBefore(NewAdd, I);
2221 return new SIToFPInst(NewAdd, I.getType());
2222 }
2223 }
2224 }
2225
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002226 return Changed ? &I : 0;
2227}
2228
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002229Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2230 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2231
2232 if (Op0 == Op1) // sub X, X -> 0
2233 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2234
2235 // If this is a 'B = x-(-A)', change to B = x+A...
2236 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002237 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002238
2239 if (isa<UndefValue>(Op0))
2240 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2241 if (isa<UndefValue>(Op1))
2242 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2243
2244 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2245 // Replace (-1 - A) with (~A)...
2246 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002247 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002248
2249 // C - ~X == X + (1+C)
2250 Value *X = 0;
2251 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002252 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253
2254 // -(X >>u 31) -> (X >>s 31)
2255 // -(X >>s 31) -> (X >>u 31)
2256 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002257 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002258 if (SI->getOpcode() == Instruction::LShr) {
2259 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2260 // Check to see if we are shifting out everything but the sign bit.
2261 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2262 SI->getType()->getPrimitiveSizeInBits()-1) {
2263 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002264 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002265 SI->getOperand(0), CU, SI->getName());
2266 }
2267 }
2268 }
2269 else if (SI->getOpcode() == Instruction::AShr) {
2270 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2271 // Check to see if we are shifting out everything but the sign bit.
2272 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2273 SI->getType()->getPrimitiveSizeInBits()-1) {
2274 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002275 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002276 SI->getOperand(0), CU, SI->getName());
2277 }
2278 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002279 }
2280 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281 }
2282
2283 // Try to fold constant sub into select arguments.
2284 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2285 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2286 return R;
2287
2288 if (isa<PHINode>(Op0))
2289 if (Instruction *NV = FoldOpIntoPhi(I))
2290 return NV;
2291 }
2292
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002293 if (I.getType() == Type::Int1Ty)
2294 return BinaryOperator::CreateXor(Op0, Op1);
2295
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002296 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2297 if (Op1I->getOpcode() == Instruction::Add &&
2298 !Op0->getType()->isFPOrFPVector()) {
2299 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002300 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002301 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002302 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2304 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2305 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002306 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 Op1I->getOperand(0));
2308 }
2309 }
2310
2311 if (Op1I->hasOneUse()) {
2312 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2313 // is not used by anyone else...
2314 //
2315 if (Op1I->getOpcode() == Instruction::Sub &&
2316 !Op1I->getType()->isFPOrFPVector()) {
2317 // Swap the two operands of the subexpr...
2318 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2319 Op1I->setOperand(0, IIOp1);
2320 Op1I->setOperand(1, IIOp0);
2321
2322 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002323 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 }
2325
2326 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2327 //
2328 if (Op1I->getOpcode() == Instruction::And &&
2329 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2330 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2331
2332 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002333 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2334 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335 }
2336
2337 // 0 - (X sdiv C) -> (X sdiv -C)
2338 if (Op1I->getOpcode() == Instruction::SDiv)
2339 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2340 if (CSI->isZero())
2341 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002342 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002343 ConstantExpr::getNeg(DivRHS));
2344
2345 // X - X*C --> X * (1-C)
2346 ConstantInt *C2 = 0;
2347 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2348 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002349 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 }
Dan Gohmanda338742007-09-17 17:31:57 +00002351
2352 // X - ((X / Y) * Y) --> X % Y
2353 if (Op1I->getOpcode() == Instruction::Mul)
2354 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2355 if (Op0 == I->getOperand(0) &&
2356 Op1I->getOperand(1) == I->getOperand(1)) {
2357 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002358 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002359 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002360 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002361 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002362 }
2363 }
2364
2365 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002366 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002367 if (Op0I->getOpcode() == Instruction::Add) {
2368 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2369 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2370 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2371 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2372 } else if (Op0I->getOpcode() == Instruction::Sub) {
2373 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002374 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002375 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002376 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002377
2378 ConstantInt *C1;
2379 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2380 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002381 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002382
2383 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2384 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002385 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386 }
2387 return 0;
2388}
2389
2390/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2391/// comparison only checks the sign bit. If it only checks the sign bit, set
2392/// TrueIfSigned if the result of the comparison is true when the input value is
2393/// signed.
2394static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2395 bool &TrueIfSigned) {
2396 switch (pred) {
2397 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2398 TrueIfSigned = true;
2399 return RHS->isZero();
2400 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2401 TrueIfSigned = true;
2402 return RHS->isAllOnesValue();
2403 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2404 TrueIfSigned = false;
2405 return RHS->isAllOnesValue();
2406 case ICmpInst::ICMP_UGT:
2407 // True if LHS u> RHS and RHS == high-bit-mask - 1
2408 TrueIfSigned = true;
2409 return RHS->getValue() ==
2410 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2411 case ICmpInst::ICMP_UGE:
2412 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2413 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002414 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002415 default:
2416 return false;
2417 }
2418}
2419
2420Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2421 bool Changed = SimplifyCommutative(I);
2422 Value *Op0 = I.getOperand(0);
2423
2424 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2426
2427 // Simplify mul instructions with a constant RHS...
2428 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2429 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2430
2431 // ((X << C1)*C2) == (X * (C2 << C1))
2432 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2433 if (SI->getOpcode() == Instruction::Shl)
2434 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002435 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002436 ConstantExpr::getShl(CI, ShOp));
2437
2438 if (CI->isZero())
2439 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2440 if (CI->equalsInt(1)) // X * 1 == X
2441 return ReplaceInstUsesWith(I, Op0);
2442 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002443 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444
2445 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2446 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002447 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448 ConstantInt::get(Op0->getType(), Val.logBase2()));
2449 }
2450 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2451 if (Op1F->isNullValue())
2452 return ReplaceInstUsesWith(I, Op1);
2453
2454 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2455 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002456 // We need a better interface for long double here.
2457 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2458 if (Op1F->isExactlyValue(1.0))
2459 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460 }
2461
2462 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2463 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002464 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002466 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002467 Op1, "tmp");
2468 InsertNewInstBefore(Add, I);
2469 Value *C1C2 = ConstantExpr::getMul(Op1,
2470 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002472
2473 }
2474
2475 // Try to fold constant mul into select arguments.
2476 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2477 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2478 return R;
2479
2480 if (isa<PHINode>(Op0))
2481 if (Instruction *NV = FoldOpIntoPhi(I))
2482 return NV;
2483 }
2484
2485 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2486 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002487 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002489 if (I.getType() == Type::Int1Ty)
2490 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2491
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002492 // If one of the operands of the multiply is a cast from a boolean value, then
2493 // we know the bool is either zero or one, so this is a 'masking' multiply.
2494 // See if we can simplify things based on how the boolean was originally
2495 // formed.
2496 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002497 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002498 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2499 BoolCast = CI;
2500 if (!BoolCast)
2501 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2502 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2503 BoolCast = CI;
2504 if (BoolCast) {
2505 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2506 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2507 const Type *SCOpTy = SCIOp0->getType();
2508 bool TIS = false;
2509
2510 // If the icmp is true iff the sign bit of X is set, then convert this
2511 // multiply into a shift/and combination.
2512 if (isa<ConstantInt>(SCIOp1) &&
2513 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2514 TIS) {
2515 // Shift the X value right to turn it into "all signbits".
2516 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2517 SCOpTy->getPrimitiveSizeInBits()-1);
2518 Value *V =
2519 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002520 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002521 BoolCast->getOperand(0)->getName()+
2522 ".mask"), I);
2523
2524 // If the multiply type is not the same as the source type, sign extend
2525 // or truncate to the multiply type.
2526 if (I.getType() != V->getType()) {
2527 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2528 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2529 Instruction::CastOps opcode =
2530 (SrcBits == DstBits ? Instruction::BitCast :
2531 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2532 V = InsertCastBefore(opcode, V, I.getType(), I);
2533 }
2534
2535 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002537 }
2538 }
2539 }
2540
2541 return Changed ? &I : 0;
2542}
2543
2544/// This function implements the transforms on div instructions that work
2545/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2546/// used by the visitors to those instructions.
2547/// @brief Transforms common to all three div instructions
2548Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2549 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2550
Chris Lattner653ef3c2008-02-19 06:12:18 +00002551 // undef / X -> 0 for integer.
2552 // undef / X -> undef for FP (the undef could be a snan).
2553 if (isa<UndefValue>(Op0)) {
2554 if (Op0->getType()->isFPOrFPVector())
2555 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002557 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558
2559 // X / undef -> undef
2560 if (isa<UndefValue>(Op1))
2561 return ReplaceInstUsesWith(I, Op1);
2562
Chris Lattner5be238b2008-01-28 00:58:18 +00002563 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2564 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002565 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002566 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2567 // the same basic block, then we replace the select with Y, and the
2568 // condition of the select with false (if the cond value is in the same BB).
2569 // If the select has uses other than the div, this allows them to be
2570 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2571 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572 if (ST->isNullValue()) {
2573 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2574 if (CondI && CondI->getParent() == I.getParent())
2575 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2576 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2577 I.setOperand(1, SI->getOperand(2));
2578 else
2579 UpdateValueUsesWith(SI, SI->getOperand(2));
2580 return &I;
2581 }
2582
Chris Lattner5be238b2008-01-28 00:58:18 +00002583 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2584 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585 if (ST->isNullValue()) {
2586 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2587 if (CondI && CondI->getParent() == I.getParent())
2588 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2589 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2590 I.setOperand(1, SI->getOperand(1));
2591 else
2592 UpdateValueUsesWith(SI, SI->getOperand(1));
2593 return &I;
2594 }
2595 }
2596
2597 return 0;
2598}
2599
2600/// This function implements the transforms common to both integer division
2601/// instructions (udiv and sdiv). It is called by the visitors to those integer
2602/// division instructions.
2603/// @brief Common integer divide transforms
2604Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2606
Chris Lattnercefb36c2008-05-16 02:59:42 +00002607 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002608 if (Op0 == Op1) {
2609 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2610 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2611 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2612 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2613 }
2614
2615 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2616 return ReplaceInstUsesWith(I, CI);
2617 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002618
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002619 if (Instruction *Common = commonDivTransforms(I))
2620 return Common;
2621
2622 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2623 // div X, 1 == X
2624 if (RHS->equalsInt(1))
2625 return ReplaceInstUsesWith(I, Op0);
2626
2627 // (X / C1) / C2 -> X / (C1*C2)
2628 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2629 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2630 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002631 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2632 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2633 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002634 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002635 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002636 }
2637
2638 if (!RHS->isZero()) { // avoid X udiv 0
2639 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2640 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2641 return R;
2642 if (isa<PHINode>(Op0))
2643 if (Instruction *NV = FoldOpIntoPhi(I))
2644 return NV;
2645 }
2646 }
2647
2648 // 0 / X == 0, we don't need to preserve faults!
2649 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2650 if (LHS->equalsInt(0))
2651 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2652
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002653 // It can't be division by zero, hence it must be division by one.
2654 if (I.getType() == Type::Int1Ty)
2655 return ReplaceInstUsesWith(I, Op0);
2656
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002657 return 0;
2658}
2659
2660Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2661 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2662
2663 // Handle the integer div common cases
2664 if (Instruction *Common = commonIDivTransforms(I))
2665 return Common;
2666
2667 // X udiv C^2 -> X >> C
2668 // Check to see if this is an unsigned division with an exact power of 2,
2669 // if so, convert to a right shift.
2670 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2671 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002672 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2674 }
2675
2676 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2677 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2678 if (RHSI->getOpcode() == Instruction::Shl &&
2679 isa<ConstantInt>(RHSI->getOperand(0))) {
2680 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2681 if (C1.isPowerOf2()) {
2682 Value *N = RHSI->getOperand(1);
2683 const Type *NTy = N->getType();
2684 if (uint32_t C2 = C1.logBase2()) {
2685 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002686 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002687 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002688 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002689 }
2690 }
2691 }
2692
2693 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2694 // where C1&C2 are powers of two.
2695 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2696 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2697 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2698 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2699 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2700 // Compute the shift amounts
2701 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2702 // Construct the "on true" case of the select
2703 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002704 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002705 Op0, TC, SI->getName()+".t");
2706 TSI = InsertNewInstBefore(TSI, I);
2707
2708 // Construct the "on false" case of the select
2709 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002710 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002711 Op0, FC, SI->getName()+".f");
2712 FSI = InsertNewInstBefore(FSI, I);
2713
2714 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002715 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002716 }
2717 }
2718 return 0;
2719}
2720
2721Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2722 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2723
2724 // Handle the integer div common cases
2725 if (Instruction *Common = commonIDivTransforms(I))
2726 return Common;
2727
2728 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2729 // sdiv X, -1 == -X
2730 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002731 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732
2733 // -X/C -> X/-C
2734 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00002735 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002736 }
2737
2738 // If the sign bits of both operands are zero (i.e. we can prove they are
2739 // unsigned inputs), turn this into a udiv.
2740 if (I.getType()->isInteger()) {
2741 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2742 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002743 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002744 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 }
2746 }
2747
2748 return 0;
2749}
2750
2751Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2752 return commonDivTransforms(I);
2753}
2754
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755/// This function implements the transforms on rem instructions that work
2756/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2757/// is used by the visitors to those instructions.
2758/// @brief Transforms common to all three rem instructions
2759Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2760 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2761
Chris Lattner653ef3c2008-02-19 06:12:18 +00002762 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002763 if (Constant *LHS = dyn_cast<Constant>(Op0))
2764 if (LHS->isNullValue())
2765 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2766
Chris Lattner653ef3c2008-02-19 06:12:18 +00002767 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2768 if (I.getType()->isFPOrFPVector())
2769 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002771 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002772 if (isa<UndefValue>(Op1))
2773 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2774
2775 // Handle cases involving: rem X, (select Cond, Y, Z)
2776 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2777 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2778 // the same basic block, then we replace the select with Y, and the
2779 // condition of the select with false (if the cond value is in the same
2780 // BB). If the select has uses other than the div, this allows them to be
2781 // simplified also.
2782 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2783 if (ST->isNullValue()) {
2784 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2785 if (CondI && CondI->getParent() == I.getParent())
2786 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2787 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2788 I.setOperand(1, SI->getOperand(2));
2789 else
2790 UpdateValueUsesWith(SI, SI->getOperand(2));
2791 return &I;
2792 }
2793 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2794 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2795 if (ST->isNullValue()) {
2796 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2797 if (CondI && CondI->getParent() == I.getParent())
2798 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2799 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2800 I.setOperand(1, SI->getOperand(1));
2801 else
2802 UpdateValueUsesWith(SI, SI->getOperand(1));
2803 return &I;
2804 }
2805 }
2806
2807 return 0;
2808}
2809
2810/// This function implements the transforms common to both integer remainder
2811/// instructions (urem and srem). It is called by the visitors to those integer
2812/// remainder instructions.
2813/// @brief Common integer remainder transforms
2814Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2815 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2816
2817 if (Instruction *common = commonRemTransforms(I))
2818 return common;
2819
2820 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2821 // X % 0 == undef, we don't need to preserve faults!
2822 if (RHS->equalsInt(0))
2823 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2824
2825 if (RHS->equalsInt(1)) // X % 1 == 0
2826 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2827
2828 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2829 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2830 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2831 return R;
2832 } else if (isa<PHINode>(Op0I)) {
2833 if (Instruction *NV = FoldOpIntoPhi(I))
2834 return NV;
2835 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002836
2837 // See if we can fold away this rem instruction.
2838 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2839 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2840 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2841 KnownZero, KnownOne))
2842 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002843 }
2844 }
2845
2846 return 0;
2847}
2848
2849Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2851
2852 if (Instruction *common = commonIRemTransforms(I))
2853 return common;
2854
2855 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2856 // X urem C^2 -> X and C
2857 // Check to see if this is an unsigned remainder with an exact power of 2,
2858 // if so, convert to a bitwise and.
2859 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2860 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00002861 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 }
2863
2864 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2865 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2866 if (RHSI->getOpcode() == Instruction::Shl &&
2867 isa<ConstantInt>(RHSI->getOperand(0))) {
2868 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2869 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00002870 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002872 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873 }
2874 }
2875 }
2876
2877 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2878 // where C1&C2 are powers of two.
2879 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2880 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2881 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2882 // STO == 0 and SFO == 0 handled above.
2883 if ((STO->getValue().isPowerOf2()) &&
2884 (SFO->getValue().isPowerOf2())) {
2885 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002886 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002887 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002888 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002889 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890 }
2891 }
2892 }
2893
2894 return 0;
2895}
2896
2897Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2898 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2899
Dan Gohmandb3dd962007-11-05 23:16:33 +00002900 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002901 if (Instruction *common = commonIRemTransforms(I))
2902 return common;
2903
2904 if (Value *RHSNeg = dyn_castNegVal(Op1))
2905 if (!isa<ConstantInt>(RHSNeg) ||
2906 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2907 // X % -Y -> X % Y
2908 AddUsesToWorkList(I);
2909 I.setOperand(1, RHSNeg);
2910 return &I;
2911 }
2912
Dan Gohmandb3dd962007-11-05 23:16:33 +00002913 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002914 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00002915 if (I.getType()->isInteger()) {
2916 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2917 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2918 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002919 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00002920 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921 }
2922
2923 return 0;
2924}
2925
2926Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2927 return commonRemTransforms(I);
2928}
2929
2930// isMaxValueMinusOne - return true if this is Max-1
2931static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2932 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2933 if (!isSigned)
2934 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2935 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2936}
2937
2938// isMinValuePlusOne - return true if this is Min+1
2939static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2940 if (!isSigned)
2941 return C->getValue() == 1; // unsigned
2942
2943 // Calculate 1111111111000000000000
2944 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2945 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2946}
2947
2948// isOneBitSet - Return true if there is exactly one bit set in the specified
2949// constant.
2950static bool isOneBitSet(const ConstantInt *CI) {
2951 return CI->getValue().isPowerOf2();
2952}
2953
2954// isHighOnes - Return true if the constant is of the form 1+0+.
2955// This is the same as lowones(~X).
2956static bool isHighOnes(const ConstantInt *CI) {
2957 return (~CI->getValue() + 1).isPowerOf2();
2958}
2959
2960/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2961/// are carefully arranged to allow folding of expressions such as:
2962///
2963/// (A < B) | (A > B) --> (A != B)
2964///
2965/// Note that this is only valid if the first and second predicates have the
2966/// same sign. Is illegal to do: (A u< B) | (A s> B)
2967///
2968/// Three bits are used to represent the condition, as follows:
2969/// 0 A > B
2970/// 1 A == B
2971/// 2 A < B
2972///
2973/// <=> Value Definition
2974/// 000 0 Always false
2975/// 001 1 A > B
2976/// 010 2 A == B
2977/// 011 3 A >= B
2978/// 100 4 A < B
2979/// 101 5 A != B
2980/// 110 6 A <= B
2981/// 111 7 Always true
2982///
2983static unsigned getICmpCode(const ICmpInst *ICI) {
2984 switch (ICI->getPredicate()) {
2985 // False -> 0
2986 case ICmpInst::ICMP_UGT: return 1; // 001
2987 case ICmpInst::ICMP_SGT: return 1; // 001
2988 case ICmpInst::ICMP_EQ: return 2; // 010
2989 case ICmpInst::ICMP_UGE: return 3; // 011
2990 case ICmpInst::ICMP_SGE: return 3; // 011
2991 case ICmpInst::ICMP_ULT: return 4; // 100
2992 case ICmpInst::ICMP_SLT: return 4; // 100
2993 case ICmpInst::ICMP_NE: return 5; // 101
2994 case ICmpInst::ICMP_ULE: return 6; // 110
2995 case ICmpInst::ICMP_SLE: return 6; // 110
2996 // True -> 7
2997 default:
2998 assert(0 && "Invalid ICmp predicate!");
2999 return 0;
3000 }
3001}
3002
3003/// getICmpValue - This is the complement of getICmpCode, which turns an
3004/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003005/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003006/// of predicate to use in new icmp instructions.
3007static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3008 switch (code) {
3009 default: assert(0 && "Illegal ICmp code!");
3010 case 0: return ConstantInt::getFalse();
3011 case 1:
3012 if (sign)
3013 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3014 else
3015 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3016 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3017 case 3:
3018 if (sign)
3019 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3020 else
3021 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3022 case 4:
3023 if (sign)
3024 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3025 else
3026 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3027 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3028 case 6:
3029 if (sign)
3030 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3031 else
3032 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3033 case 7: return ConstantInt::getTrue();
3034 }
3035}
3036
3037static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3038 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3039 (ICmpInst::isSignedPredicate(p1) &&
3040 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3041 (ICmpInst::isSignedPredicate(p2) &&
3042 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3043}
3044
3045namespace {
3046// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3047struct FoldICmpLogical {
3048 InstCombiner &IC;
3049 Value *LHS, *RHS;
3050 ICmpInst::Predicate pred;
3051 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3052 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3053 pred(ICI->getPredicate()) {}
3054 bool shouldApply(Value *V) const {
3055 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3056 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003057 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3058 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003059 return false;
3060 }
3061 Instruction *apply(Instruction &Log) const {
3062 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3063 if (ICI->getOperand(0) != LHS) {
3064 assert(ICI->getOperand(1) == LHS);
3065 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3066 }
3067
3068 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3069 unsigned LHSCode = getICmpCode(ICI);
3070 unsigned RHSCode = getICmpCode(RHSICI);
3071 unsigned Code;
3072 switch (Log.getOpcode()) {
3073 case Instruction::And: Code = LHSCode & RHSCode; break;
3074 case Instruction::Or: Code = LHSCode | RHSCode; break;
3075 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3076 default: assert(0 && "Illegal logical opcode!"); return 0;
3077 }
3078
3079 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3080 ICmpInst::isSignedPredicate(ICI->getPredicate());
3081
3082 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3083 if (Instruction *I = dyn_cast<Instruction>(RV))
3084 return I;
3085 // Otherwise, it's a constant boolean value...
3086 return IC.ReplaceInstUsesWith(Log, RV);
3087 }
3088};
3089} // end anonymous namespace
3090
3091// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3092// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3093// guaranteed to be a binary operator.
3094Instruction *InstCombiner::OptAndOp(Instruction *Op,
3095 ConstantInt *OpRHS,
3096 ConstantInt *AndRHS,
3097 BinaryOperator &TheAnd) {
3098 Value *X = Op->getOperand(0);
3099 Constant *Together = 0;
3100 if (!Op->isShift())
3101 Together = And(AndRHS, OpRHS);
3102
3103 switch (Op->getOpcode()) {
3104 case Instruction::Xor:
3105 if (Op->hasOneUse()) {
3106 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003107 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108 InsertNewInstBefore(And, TheAnd);
3109 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003110 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003111 }
3112 break;
3113 case Instruction::Or:
3114 if (Together == AndRHS) // (X | C) & C --> C
3115 return ReplaceInstUsesWith(TheAnd, AndRHS);
3116
3117 if (Op->hasOneUse() && Together != OpRHS) {
3118 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003119 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120 InsertNewInstBefore(Or, TheAnd);
3121 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003122 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003123 }
3124 break;
3125 case Instruction::Add:
3126 if (Op->hasOneUse()) {
3127 // Adding a one to a single bit bit-field should be turned into an XOR
3128 // of the bit. First thing to check is to see if this AND is with a
3129 // single bit constant.
3130 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3131
3132 // If there is only one bit set...
3133 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3134 // Ok, at this point, we know that we are masking the result of the
3135 // ADD down to exactly one bit. If the constant we are adding has
3136 // no bits set below this bit, then we can eliminate the ADD.
3137 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3138
3139 // Check to see if any bits below the one bit set in AndRHSV are set.
3140 if ((AddRHS & (AndRHSV-1)) == 0) {
3141 // If not, the only thing that can effect the output of the AND is
3142 // the bit specified by AndRHSV. If that bit is set, the effect of
3143 // the XOR is to toggle the bit. If it is clear, then the ADD has
3144 // no effect.
3145 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3146 TheAnd.setOperand(0, X);
3147 return &TheAnd;
3148 } else {
3149 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003150 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151 InsertNewInstBefore(NewAnd, TheAnd);
3152 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003153 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 }
3155 }
3156 }
3157 }
3158 break;
3159
3160 case Instruction::Shl: {
3161 // We know that the AND will not produce any of the bits shifted in, so if
3162 // the anded constant includes them, clear them now!
3163 //
3164 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3165 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3166 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3167 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3168
3169 if (CI->getValue() == ShlMask) {
3170 // Masking out bits that the shift already masks
3171 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3172 } else if (CI != AndRHS) { // Reducing bits set in and.
3173 TheAnd.setOperand(1, CI);
3174 return &TheAnd;
3175 }
3176 break;
3177 }
3178 case Instruction::LShr:
3179 {
3180 // We know that the AND will not produce any of the bits shifted in, so if
3181 // the anded constant includes them, clear them now! This only applies to
3182 // unsigned shifts, because a signed shr may bring in set bits!
3183 //
3184 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3185 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3186 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3187 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3188
3189 if (CI->getValue() == ShrMask) {
3190 // Masking out bits that the shift already masks.
3191 return ReplaceInstUsesWith(TheAnd, Op);
3192 } else if (CI != AndRHS) {
3193 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3194 return &TheAnd;
3195 }
3196 break;
3197 }
3198 case Instruction::AShr:
3199 // Signed shr.
3200 // See if this is shifting in some sign extension, then masking it out
3201 // with an and.
3202 if (Op->hasOneUse()) {
3203 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3204 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3205 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3206 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3207 if (C == AndRHS) { // Masking out bits shifted in.
3208 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3209 // Make the argument unsigned.
3210 Value *ShVal = Op->getOperand(0);
3211 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003212 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003214 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 }
3216 }
3217 break;
3218 }
3219 return 0;
3220}
3221
3222
3223/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3224/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3225/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3226/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3227/// insert new instructions.
3228Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3229 bool isSigned, bool Inside,
3230 Instruction &IB) {
3231 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3232 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3233 "Lo is not <= Hi in range emission code!");
3234
3235 if (Inside) {
3236 if (Lo == Hi) // Trivially false.
3237 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3238
3239 // V >= Min && V < Hi --> V < Hi
3240 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3241 ICmpInst::Predicate pred = (isSigned ?
3242 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3243 return new ICmpInst(pred, V, Hi);
3244 }
3245
3246 // Emit V-Lo <u Hi-Lo
3247 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003248 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 InsertNewInstBefore(Add, IB);
3250 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3251 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3252 }
3253
3254 if (Lo == Hi) // Trivially true.
3255 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3256
3257 // V < Min || V >= Hi -> V > Hi-1
3258 Hi = SubOne(cast<ConstantInt>(Hi));
3259 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3260 ICmpInst::Predicate pred = (isSigned ?
3261 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3262 return new ICmpInst(pred, V, Hi);
3263 }
3264
3265 // Emit V-Lo >u Hi-1-Lo
3266 // Note that Hi has already had one subtracted from it, above.
3267 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003268 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003269 InsertNewInstBefore(Add, IB);
3270 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3271 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3272}
3273
3274// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3275// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3276// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3277// not, since all 1s are not contiguous.
3278static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3279 const APInt& V = Val->getValue();
3280 uint32_t BitWidth = Val->getType()->getBitWidth();
3281 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3282
3283 // look for the first zero bit after the run of ones
3284 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3285 // look for the first non-zero bit
3286 ME = V.getActiveBits();
3287 return true;
3288}
3289
3290/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3291/// where isSub determines whether the operator is a sub. If we can fold one of
3292/// the following xforms:
3293///
3294/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3295/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3296/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3297///
3298/// return (A +/- B).
3299///
3300Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3301 ConstantInt *Mask, bool isSub,
3302 Instruction &I) {
3303 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3304 if (!LHSI || LHSI->getNumOperands() != 2 ||
3305 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3306
3307 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3308
3309 switch (LHSI->getOpcode()) {
3310 default: return 0;
3311 case Instruction::And:
3312 if (And(N, Mask) == Mask) {
3313 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3314 if ((Mask->getValue().countLeadingZeros() +
3315 Mask->getValue().countPopulation()) ==
3316 Mask->getValue().getBitWidth())
3317 break;
3318
3319 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3320 // part, we don't need any explicit masks to take them out of A. If that
3321 // is all N is, ignore it.
3322 uint32_t MB = 0, ME = 0;
3323 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3324 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3325 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3326 if (MaskedValueIsZero(RHS, Mask))
3327 break;
3328 }
3329 }
3330 return 0;
3331 case Instruction::Or:
3332 case Instruction::Xor:
3333 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3334 if ((Mask->getValue().countLeadingZeros() +
3335 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3336 && And(N, Mask)->isZero())
3337 break;
3338 return 0;
3339 }
3340
3341 Instruction *New;
3342 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003343 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003345 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003346 return InsertNewInstBefore(New, I);
3347}
3348
3349Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3350 bool Changed = SimplifyCommutative(I);
3351 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3352
3353 if (isa<UndefValue>(Op1)) // X & undef -> 0
3354 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3355
3356 // and X, X = X
3357 if (Op0 == Op1)
3358 return ReplaceInstUsesWith(I, Op1);
3359
3360 // See if we can simplify any instructions used by the instruction whose sole
3361 // purpose is to compute bits we don't care about.
3362 if (!isa<VectorType>(I.getType())) {
3363 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3364 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3365 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3366 KnownZero, KnownOne))
3367 return &I;
3368 } else {
3369 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3370 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3371 return ReplaceInstUsesWith(I, I.getOperand(0));
3372 } else if (isa<ConstantAggregateZero>(Op1)) {
3373 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3374 }
3375 }
3376
3377 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3378 const APInt& AndRHSMask = AndRHS->getValue();
3379 APInt NotAndRHS(~AndRHSMask);
3380
3381 // Optimize a variety of ((val OP C1) & C2) combinations...
3382 if (isa<BinaryOperator>(Op0)) {
3383 Instruction *Op0I = cast<Instruction>(Op0);
3384 Value *Op0LHS = Op0I->getOperand(0);
3385 Value *Op0RHS = Op0I->getOperand(1);
3386 switch (Op0I->getOpcode()) {
3387 case Instruction::Xor:
3388 case Instruction::Or:
3389 // If the mask is only needed on one incoming arm, push it up.
3390 if (Op0I->hasOneUse()) {
3391 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3392 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003393 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003394 Op0RHS->getName()+".masked");
3395 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003396 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003397 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3398 }
3399 if (!isa<Constant>(Op0RHS) &&
3400 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3401 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003402 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003403 Op0LHS->getName()+".masked");
3404 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003405 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3407 }
3408 }
3409
3410 break;
3411 case Instruction::Add:
3412 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3413 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3414 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3415 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003416 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003418 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 break;
3420
3421 case Instruction::Sub:
3422 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3423 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3424 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3425 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003426 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003427 break;
3428 }
3429
3430 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3431 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3432 return Res;
3433 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3434 // If this is an integer truncation or change from signed-to-unsigned, and
3435 // if the source is an and/or with immediate, transform it. This
3436 // frequently occurs for bitfield accesses.
3437 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3438 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3439 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003440 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003441 if (CastOp->getOpcode() == Instruction::And) {
3442 // Change: and (cast (and X, C1) to T), C2
3443 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3444 // This will fold the two constants together, which may allow
3445 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003446 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 CastOp->getOperand(0), I.getType(),
3448 CastOp->getName()+".shrunk");
3449 NewCast = InsertNewInstBefore(NewCast, I);
3450 // trunc_or_bitcast(C1)&C2
3451 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3452 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003453 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003454 } else if (CastOp->getOpcode() == Instruction::Or) {
3455 // Change: and (cast (or X, C1) to T), C2
3456 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3457 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3458 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3459 return ReplaceInstUsesWith(I, AndRHS);
3460 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003461 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003462 }
3463 }
3464
3465 // Try to fold constant and into select arguments.
3466 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3467 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3468 return R;
3469 if (isa<PHINode>(Op0))
3470 if (Instruction *NV = FoldOpIntoPhi(I))
3471 return NV;
3472 }
3473
3474 Value *Op0NotVal = dyn_castNotVal(Op0);
3475 Value *Op1NotVal = dyn_castNotVal(Op1);
3476
3477 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3478 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3479
3480 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3481 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003482 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003483 I.getName()+".demorgan");
3484 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003485 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003486 }
3487
3488 {
3489 Value *A = 0, *B = 0, *C = 0, *D = 0;
3490 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3491 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3492 return ReplaceInstUsesWith(I, Op1);
3493
3494 // (A|B) & ~(A&B) -> A^B
3495 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3496 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003497 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003498 }
3499 }
3500
3501 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3502 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3503 return ReplaceInstUsesWith(I, Op0);
3504
3505 // ~(A&B) & (A|B) -> A^B
3506 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3507 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003508 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003509 }
3510 }
3511
3512 if (Op0->hasOneUse() &&
3513 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3514 if (A == Op1) { // (A^B)&A -> A&(A^B)
3515 I.swapOperands(); // Simplify below
3516 std::swap(Op0, Op1);
3517 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3518 cast<BinaryOperator>(Op0)->swapOperands();
3519 I.swapOperands(); // Simplify below
3520 std::swap(Op0, Op1);
3521 }
3522 }
3523 if (Op1->hasOneUse() &&
3524 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3525 if (B == Op0) { // B&(A^B) -> B&(B^A)
3526 cast<BinaryOperator>(Op1)->swapOperands();
3527 std::swap(A, B);
3528 }
3529 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003530 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003531 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003532 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003533 }
3534 }
3535 }
3536
3537 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3538 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3539 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3540 return R;
3541
3542 Value *LHSVal, *RHSVal;
3543 ConstantInt *LHSCst, *RHSCst;
3544 ICmpInst::Predicate LHSCC, RHSCC;
3545 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3546 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3547 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3548 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3549 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3550 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3551 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003552 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3553
3554 // Don't try to fold ICMP_SLT + ICMP_ULT.
3555 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3556 ICmpInst::isSignedPredicate(LHSCC) ==
3557 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003559 ICmpInst::Predicate GT;
3560 if (ICmpInst::isSignedPredicate(LHSCC) ||
3561 (ICmpInst::isEquality(LHSCC) &&
3562 ICmpInst::isSignedPredicate(RHSCC)))
3563 GT = ICmpInst::ICMP_SGT;
3564 else
3565 GT = ICmpInst::ICMP_UGT;
3566
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003567 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3568 ICmpInst *LHS = cast<ICmpInst>(Op0);
3569 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3570 std::swap(LHS, RHS);
3571 std::swap(LHSCst, RHSCst);
3572 std::swap(LHSCC, RHSCC);
3573 }
3574
3575 // At this point, we know we have have two icmp instructions
3576 // comparing a value against two constants and and'ing the result
3577 // together. Because of the above check, we know that we only have
3578 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3579 // (from the FoldICmpLogical check above), that the two constants
3580 // are not equal and that the larger constant is on the RHS
3581 assert(LHSCst != RHSCst && "Compares not folded above?");
3582
3583 switch (LHSCC) {
3584 default: assert(0 && "Unknown integer condition code!");
3585 case ICmpInst::ICMP_EQ:
3586 switch (RHSCC) {
3587 default: assert(0 && "Unknown integer condition code!");
3588 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3589 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3590 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3591 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3592 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3593 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3594 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3595 return ReplaceInstUsesWith(I, LHS);
3596 }
3597 case ICmpInst::ICMP_NE:
3598 switch (RHSCC) {
3599 default: assert(0 && "Unknown integer condition code!");
3600 case ICmpInst::ICMP_ULT:
3601 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3602 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3603 break; // (X != 13 & X u< 15) -> no change
3604 case ICmpInst::ICMP_SLT:
3605 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3606 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3607 break; // (X != 13 & X s< 15) -> no change
3608 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3609 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3610 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3611 return ReplaceInstUsesWith(I, RHS);
3612 case ICmpInst::ICMP_NE:
3613 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3614 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00003615 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003616 LHSVal->getName()+".off");
3617 InsertNewInstBefore(Add, I);
3618 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3619 ConstantInt::get(Add->getType(), 1));
3620 }
3621 break; // (X != 13 & X != 15) -> no change
3622 }
3623 break;
3624 case ICmpInst::ICMP_ULT:
3625 switch (RHSCC) {
3626 default: assert(0 && "Unknown integer condition code!");
3627 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3628 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3629 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3630 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3631 break;
3632 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3633 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3634 return ReplaceInstUsesWith(I, LHS);
3635 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3636 break;
3637 }
3638 break;
3639 case ICmpInst::ICMP_SLT:
3640 switch (RHSCC) {
3641 default: assert(0 && "Unknown integer condition code!");
3642 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3643 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3644 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3645 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3646 break;
3647 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3648 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3649 return ReplaceInstUsesWith(I, LHS);
3650 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3651 break;
3652 }
3653 break;
3654 case ICmpInst::ICMP_UGT:
3655 switch (RHSCC) {
3656 default: assert(0 && "Unknown integer condition code!");
3657 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3658 return ReplaceInstUsesWith(I, LHS);
3659 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3660 return ReplaceInstUsesWith(I, RHS);
3661 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3662 break;
3663 case ICmpInst::ICMP_NE:
3664 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3665 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3666 break; // (X u> 13 & X != 15) -> no change
3667 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3668 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3669 true, I);
3670 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3671 break;
3672 }
3673 break;
3674 case ICmpInst::ICMP_SGT:
3675 switch (RHSCC) {
3676 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003677 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003678 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3679 return ReplaceInstUsesWith(I, RHS);
3680 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3681 break;
3682 case ICmpInst::ICMP_NE:
3683 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3684 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3685 break; // (X s> 13 & X != 15) -> no change
3686 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3687 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3688 true, I);
3689 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3690 break;
3691 }
3692 break;
3693 }
3694 }
3695 }
3696
3697 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3698 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3699 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3700 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3701 const Type *SrcTy = Op0C->getOperand(0)->getType();
3702 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3703 // Only do this if the casts both really cause code to be generated.
3704 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3705 I.getType(), TD) &&
3706 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3707 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003708 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003709 Op1C->getOperand(0),
3710 I.getName());
3711 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003712 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 }
3714 }
3715
3716 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3717 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3718 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3719 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3720 SI0->getOperand(1) == SI1->getOperand(1) &&
3721 (SI0->hasOneUse() || SI1->hasOneUse())) {
3722 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00003723 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003724 SI1->getOperand(0),
3725 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003726 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003727 SI1->getOperand(1));
3728 }
3729 }
3730
Chris Lattner91882432007-10-24 05:38:08 +00003731 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3732 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3733 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3734 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3735 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3736 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3737 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3738 // If either of the constants are nans, then the whole thing returns
3739 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003740 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003741 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3742 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3743 RHS->getOperand(0));
3744 }
3745 }
3746 }
3747
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748 return Changed ? &I : 0;
3749}
3750
3751/// CollectBSwapParts - Look to see if the specified value defines a single byte
3752/// in the result. If it does, and if the specified byte hasn't been filled in
3753/// yet, fill it in and return false.
3754static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3755 Instruction *I = dyn_cast<Instruction>(V);
3756 if (I == 0) return true;
3757
3758 // If this is an or instruction, it is an inner node of the bswap.
3759 if (I->getOpcode() == Instruction::Or)
3760 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3761 CollectBSwapParts(I->getOperand(1), ByteValues);
3762
3763 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3764 // If this is a shift by a constant int, and it is "24", then its operand
3765 // defines a byte. We only handle unsigned types here.
3766 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3767 // Not shifting the entire input by N-1 bytes?
3768 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3769 8*(ByteValues.size()-1))
3770 return true;
3771
3772 unsigned DestNo;
3773 if (I->getOpcode() == Instruction::Shl) {
3774 // X << 24 defines the top byte with the lowest of the input bytes.
3775 DestNo = ByteValues.size()-1;
3776 } else {
3777 // X >>u 24 defines the low byte with the highest of the input bytes.
3778 DestNo = 0;
3779 }
3780
3781 // If the destination byte value is already defined, the values are or'd
3782 // together, which isn't a bswap (unless it's an or of the same bits).
3783 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3784 return true;
3785 ByteValues[DestNo] = I->getOperand(0);
3786 return false;
3787 }
3788
3789 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3790 // don't have this.
3791 Value *Shift = 0, *ShiftLHS = 0;
3792 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3793 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3794 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3795 return true;
3796 Instruction *SI = cast<Instruction>(Shift);
3797
3798 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3799 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3800 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3801 return true;
3802
3803 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3804 unsigned DestByte;
3805 if (AndAmt->getValue().getActiveBits() > 64)
3806 return true;
3807 uint64_t AndAmtVal = AndAmt->getZExtValue();
3808 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3809 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3810 break;
3811 // Unknown mask for bswap.
3812 if (DestByte == ByteValues.size()) return true;
3813
3814 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3815 unsigned SrcByte;
3816 if (SI->getOpcode() == Instruction::Shl)
3817 SrcByte = DestByte - ShiftBytes;
3818 else
3819 SrcByte = DestByte + ShiftBytes;
3820
3821 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3822 if (SrcByte != ByteValues.size()-DestByte-1)
3823 return true;
3824
3825 // If the destination byte value is already defined, the values are or'd
3826 // together, which isn't a bswap (unless it's an or of the same bits).
3827 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3828 return true;
3829 ByteValues[DestByte] = SI->getOperand(0);
3830 return false;
3831}
3832
3833/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3834/// If so, insert the new bswap intrinsic and return it.
3835Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3836 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3837 if (!ITy || ITy->getBitWidth() % 16)
3838 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3839
3840 /// ByteValues - For each byte of the result, we keep track of which value
3841 /// defines each byte.
3842 SmallVector<Value*, 8> ByteValues;
3843 ByteValues.resize(ITy->getBitWidth()/8);
3844
3845 // Try to find all the pieces corresponding to the bswap.
3846 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3847 CollectBSwapParts(I.getOperand(1), ByteValues))
3848 return 0;
3849
3850 // Check to see if all of the bytes come from the same value.
3851 Value *V = ByteValues[0];
3852 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3853
3854 // Check to make sure that all of the bytes come from the same value.
3855 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3856 if (ByteValues[i] != V)
3857 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003858 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003859 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003860 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003861 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003862}
3863
3864
3865Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3866 bool Changed = SimplifyCommutative(I);
3867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3868
3869 if (isa<UndefValue>(Op1)) // X | undef -> -1
3870 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3871
3872 // or X, X = X
3873 if (Op0 == Op1)
3874 return ReplaceInstUsesWith(I, Op0);
3875
3876 // See if we can simplify any instructions used by the instruction whose sole
3877 // purpose is to compute bits we don't care about.
3878 if (!isa<VectorType>(I.getType())) {
3879 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3880 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3881 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3882 KnownZero, KnownOne))
3883 return &I;
3884 } else if (isa<ConstantAggregateZero>(Op1)) {
3885 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3886 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3887 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3888 return ReplaceInstUsesWith(I, I.getOperand(1));
3889 }
3890
3891
3892
3893 // or X, -1 == -1
3894 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3895 ConstantInt *C1 = 0; Value *X = 0;
3896 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3897 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003898 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003899 InsertNewInstBefore(Or, I);
3900 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003902 ConstantInt::get(RHS->getValue() | C1->getValue()));
3903 }
3904
3905 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3906 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003907 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003908 InsertNewInstBefore(Or, I);
3909 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003910 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003911 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3912 }
3913
3914 // Try to fold constant and into select arguments.
3915 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3916 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3917 return R;
3918 if (isa<PHINode>(Op0))
3919 if (Instruction *NV = FoldOpIntoPhi(I))
3920 return NV;
3921 }
3922
3923 Value *A = 0, *B = 0;
3924 ConstantInt *C1 = 0, *C2 = 0;
3925
3926 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3927 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3928 return ReplaceInstUsesWith(I, Op1);
3929 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3930 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3931 return ReplaceInstUsesWith(I, Op0);
3932
3933 // (A | B) | C and A | (B | C) -> bswap if possible.
3934 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3935 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3936 match(Op1, m_Or(m_Value(), m_Value())) ||
3937 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3938 match(Op1, m_Shift(m_Value(), m_Value())))) {
3939 if (Instruction *BSwap = MatchBSwap(I))
3940 return BSwap;
3941 }
3942
3943 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3944 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3945 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003946 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003947 InsertNewInstBefore(NOr, I);
3948 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003949 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003950 }
3951
3952 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3953 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3954 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003955 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003956 InsertNewInstBefore(NOr, I);
3957 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00003958 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003959 }
3960
3961 // (A & C)|(B & D)
3962 Value *C = 0, *D = 0;
3963 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3964 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3965 Value *V1 = 0, *V2 = 0, *V3 = 0;
3966 C1 = dyn_cast<ConstantInt>(C);
3967 C2 = dyn_cast<ConstantInt>(D);
3968 if (C1 && C2) { // (A & C1)|(B & C2)
3969 // If we have: ((V + N) & C1) | (V & C2)
3970 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3971 // replace with V+N.
3972 if (C1->getValue() == ~C2->getValue()) {
3973 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3974 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3975 // Add commutes, try both ways.
3976 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3977 return ReplaceInstUsesWith(I, A);
3978 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3979 return ReplaceInstUsesWith(I, A);
3980 }
3981 // Or commutes, try both ways.
3982 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3983 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3984 // Add commutes, try both ways.
3985 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3986 return ReplaceInstUsesWith(I, B);
3987 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3988 return ReplaceInstUsesWith(I, B);
3989 }
3990 }
3991 V1 = 0; V2 = 0; V3 = 0;
3992 }
3993
3994 // Check to see if we have any common things being and'ed. If so, find the
3995 // terms for V1 & (V2|V3).
3996 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3997 if (A == B) // (A & C)|(A & D) == A & (C|D)
3998 V1 = A, V2 = C, V3 = D;
3999 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4000 V1 = A, V2 = B, V3 = C;
4001 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4002 V1 = C, V2 = A, V3 = D;
4003 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4004 V1 = C, V2 = A, V3 = B;
4005
4006 if (V1) {
4007 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004008 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4009 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004010 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004011 }
4012 }
4013
4014 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4015 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4016 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4017 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4018 SI0->getOperand(1) == SI1->getOperand(1) &&
4019 (SI0->hasOneUse() || SI1->hasOneUse())) {
4020 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004021 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004022 SI1->getOperand(0),
4023 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004024 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004025 SI1->getOperand(1));
4026 }
4027 }
4028
4029 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4030 if (A == Op1) // ~A | A == -1
4031 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4032 } else {
4033 A = 0;
4034 }
4035 // Note, A is still live here!
4036 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4037 if (Op0 == B)
4038 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4039
4040 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4041 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004042 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004043 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004044 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004045 }
4046 }
4047
4048 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4049 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4050 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4051 return R;
4052
4053 Value *LHSVal, *RHSVal;
4054 ConstantInt *LHSCst, *RHSCst;
4055 ICmpInst::Predicate LHSCC, RHSCC;
4056 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4057 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4058 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4059 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4060 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4061 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4062 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4063 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4064 // We can't fold (ugt x, C) | (sgt x, C2).
4065 PredicatesFoldable(LHSCC, RHSCC)) {
4066 // Ensure that the larger constant is on the RHS.
4067 ICmpInst *LHS = cast<ICmpInst>(Op0);
4068 bool NeedsSwap;
4069 if (ICmpInst::isSignedPredicate(LHSCC))
4070 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4071 else
4072 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4073
4074 if (NeedsSwap) {
4075 std::swap(LHS, RHS);
4076 std::swap(LHSCst, RHSCst);
4077 std::swap(LHSCC, RHSCC);
4078 }
4079
4080 // At this point, we know we have have two icmp instructions
4081 // comparing a value against two constants and or'ing the result
4082 // together. Because of the above check, we know that we only have
4083 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4084 // FoldICmpLogical check above), that the two constants are not
4085 // equal.
4086 assert(LHSCst != RHSCst && "Compares not folded above?");
4087
4088 switch (LHSCC) {
4089 default: assert(0 && "Unknown integer condition code!");
4090 case ICmpInst::ICMP_EQ:
4091 switch (RHSCC) {
4092 default: assert(0 && "Unknown integer condition code!");
4093 case ICmpInst::ICMP_EQ:
4094 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4095 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004096 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004097 LHSVal->getName()+".off");
4098 InsertNewInstBefore(Add, I);
4099 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4100 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4101 }
4102 break; // (X == 13 | X == 15) -> no change
4103 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4104 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4105 break;
4106 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4107 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4108 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4109 return ReplaceInstUsesWith(I, RHS);
4110 }
4111 break;
4112 case ICmpInst::ICMP_NE:
4113 switch (RHSCC) {
4114 default: assert(0 && "Unknown integer condition code!");
4115 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4116 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4117 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4118 return ReplaceInstUsesWith(I, LHS);
4119 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4120 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4121 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4122 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4123 }
4124 break;
4125 case ICmpInst::ICMP_ULT:
4126 switch (RHSCC) {
4127 default: assert(0 && "Unknown integer condition code!");
4128 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4129 break;
4130 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004131 // If RHSCst is [us]MAXINT, it is always false. Not handling
4132 // this can cause overflow.
4133 if (RHSCst->isMaxValue(false))
4134 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4136 false, I);
4137 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4138 break;
4139 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4140 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4141 return ReplaceInstUsesWith(I, RHS);
4142 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4143 break;
4144 }
4145 break;
4146 case ICmpInst::ICMP_SLT:
4147 switch (RHSCC) {
4148 default: assert(0 && "Unknown integer condition code!");
4149 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4150 break;
4151 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004152 // If RHSCst is [us]MAXINT, it is always false. Not handling
4153 // this can cause overflow.
4154 if (RHSCst->isMaxValue(true))
4155 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004156 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4157 false, I);
4158 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4159 break;
4160 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4161 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4162 return ReplaceInstUsesWith(I, RHS);
4163 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4164 break;
4165 }
4166 break;
4167 case ICmpInst::ICMP_UGT:
4168 switch (RHSCC) {
4169 default: assert(0 && "Unknown integer condition code!");
4170 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4171 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4172 return ReplaceInstUsesWith(I, LHS);
4173 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4174 break;
4175 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4176 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4177 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4178 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4179 break;
4180 }
4181 break;
4182 case ICmpInst::ICMP_SGT:
4183 switch (RHSCC) {
4184 default: assert(0 && "Unknown integer condition code!");
4185 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4186 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4187 return ReplaceInstUsesWith(I, LHS);
4188 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4189 break;
4190 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4191 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4192 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4193 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4194 break;
4195 }
4196 break;
4197 }
4198 }
4199 }
4200
4201 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004202 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4204 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004205 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4206 !isa<ICmpInst>(Op1C->getOperand(0))) {
4207 const Type *SrcTy = Op0C->getOperand(0)->getType();
4208 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4209 // Only do this if the casts both really cause code to be
4210 // generated.
4211 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4212 I.getType(), TD) &&
4213 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4214 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004215 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004216 Op1C->getOperand(0),
4217 I.getName());
4218 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004219 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004220 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004221 }
4222 }
Chris Lattner91882432007-10-24 05:38:08 +00004223 }
4224
4225
4226 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4227 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4228 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4229 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004230 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4231 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004232 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4233 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4234 // If either of the constants are nans, then the whole thing returns
4235 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004236 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004237 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4238
4239 // Otherwise, no need to compare the two constants, compare the
4240 // rest.
4241 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4242 RHS->getOperand(0));
4243 }
4244 }
4245 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004246
4247 return Changed ? &I : 0;
4248}
4249
Dan Gohman089efff2008-05-13 00:00:25 +00004250namespace {
4251
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004252// XorSelf - Implements: X ^ X --> 0
4253struct XorSelf {
4254 Value *RHS;
4255 XorSelf(Value *rhs) : RHS(rhs) {}
4256 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4257 Instruction *apply(BinaryOperator &Xor) const {
4258 return &Xor;
4259 }
4260};
4261
Dan Gohman089efff2008-05-13 00:00:25 +00004262}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004263
4264Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4265 bool Changed = SimplifyCommutative(I);
4266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4267
Evan Chenge5cd8032008-03-25 20:07:13 +00004268 if (isa<UndefValue>(Op1)) {
4269 if (isa<UndefValue>(Op0))
4270 // Handle undef ^ undef -> 0 special case. This is a common
4271 // idiom (misuse).
4272 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004273 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004274 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004275
4276 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4277 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004278 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004279 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4280 }
4281
4282 // See if we can simplify any instructions used by the instruction whose sole
4283 // purpose is to compute bits we don't care about.
4284 if (!isa<VectorType>(I.getType())) {
4285 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4286 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4287 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4288 KnownZero, KnownOne))
4289 return &I;
4290 } else if (isa<ConstantAggregateZero>(Op1)) {
4291 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4292 }
4293
4294 // Is this a ~ operation?
4295 if (Value *NotOp = dyn_castNotVal(&I)) {
4296 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4297 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4298 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4299 if (Op0I->getOpcode() == Instruction::And ||
4300 Op0I->getOpcode() == Instruction::Or) {
4301 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4302 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4303 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004304 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004305 Op0I->getOperand(1)->getName()+".not");
4306 InsertNewInstBefore(NotY, I);
4307 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004308 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004309 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004310 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004311 }
4312 }
4313 }
4314 }
4315
4316
4317 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004318 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4319 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4320 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004321 return new ICmpInst(ICI->getInversePredicate(),
4322 ICI->getOperand(0), ICI->getOperand(1));
4323
Nick Lewycky1405e922007-08-06 20:04:16 +00004324 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4325 return new FCmpInst(FCI->getInversePredicate(),
4326 FCI->getOperand(0), FCI->getOperand(1));
4327 }
4328
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004329 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4330 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4331 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4332 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4333 Instruction::CastOps Opcode = Op0C->getOpcode();
4334 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4335 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4336 Op0C->getDestTy())) {
4337 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4338 CI->getOpcode(), CI->getInversePredicate(),
4339 CI->getOperand(0), CI->getOperand(1)), I);
4340 NewCI->takeName(CI);
4341 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4342 }
4343 }
4344 }
4345 }
4346 }
4347
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004348 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4349 // ~(c-X) == X-c-1 == X+(-c-1)
4350 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4351 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4352 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4353 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4354 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004355 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004356 }
4357
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004358 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004359 if (Op0I->getOpcode() == Instruction::Add) {
4360 // ~(X-c) --> (-c-1)-X
4361 if (RHS->isAllOnesValue()) {
4362 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004363 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004364 ConstantExpr::getSub(NegOp0CI,
4365 ConstantInt::get(I.getType(), 1)),
4366 Op0I->getOperand(0));
4367 } else if (RHS->getValue().isSignBit()) {
4368 // (X + C) ^ signbit -> (X + C + signbit)
4369 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004370 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004371
4372 }
4373 } else if (Op0I->getOpcode() == Instruction::Or) {
4374 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4375 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4376 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4377 // Anything in both C1 and C2 is known to be zero, remove it from
4378 // NewRHS.
4379 Constant *CommonBits = And(Op0CI, RHS);
4380 NewRHS = ConstantExpr::getAnd(NewRHS,
4381 ConstantExpr::getNot(CommonBits));
4382 AddToWorkList(Op0I);
4383 I.setOperand(0, Op0I->getOperand(0));
4384 I.setOperand(1, NewRHS);
4385 return &I;
4386 }
4387 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004388 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004389 }
4390
4391 // Try to fold constant and into select arguments.
4392 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4393 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4394 return R;
4395 if (isa<PHINode>(Op0))
4396 if (Instruction *NV = FoldOpIntoPhi(I))
4397 return NV;
4398 }
4399
4400 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4401 if (X == Op1)
4402 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4403
4404 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4405 if (X == Op0)
4406 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4407
4408
4409 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4410 if (Op1I) {
4411 Value *A, *B;
4412 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4413 if (A == Op0) { // B^(B|A) == (A|B)^B
4414 Op1I->swapOperands();
4415 I.swapOperands();
4416 std::swap(Op0, Op1);
4417 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4418 I.swapOperands(); // Simplified below.
4419 std::swap(Op0, Op1);
4420 }
4421 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4422 if (Op0 == A) // A^(A^B) == B
4423 return ReplaceInstUsesWith(I, B);
4424 else if (Op0 == B) // A^(B^A) == B
4425 return ReplaceInstUsesWith(I, A);
4426 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4427 if (A == Op0) { // A^(A&B) -> A^(B&A)
4428 Op1I->swapOperands();
4429 std::swap(A, B);
4430 }
4431 if (B == Op0) { // A^(B&A) -> (B&A)^A
4432 I.swapOperands(); // Simplified below.
4433 std::swap(Op0, Op1);
4434 }
4435 }
4436 }
4437
4438 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4439 if (Op0I) {
4440 Value *A, *B;
4441 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4442 if (A == Op1) // (B|A)^B == (A|B)^B
4443 std::swap(A, B);
4444 if (B == Op1) { // (A|B)^B == A & ~B
4445 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004446 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4447 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004448 }
4449 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4450 if (Op1 == A) // (A^B)^A == B
4451 return ReplaceInstUsesWith(I, B);
4452 else if (Op1 == B) // (B^A)^A == B
4453 return ReplaceInstUsesWith(I, A);
4454 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4455 if (A == Op1) // (A&B)^A -> (B&A)^A
4456 std::swap(A, B);
4457 if (B == Op1 && // (B&A)^A == ~B & A
4458 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4459 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004460 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4461 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004462 }
4463 }
4464 }
4465
4466 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4467 if (Op0I && Op1I && Op0I->isShift() &&
4468 Op0I->getOpcode() == Op1I->getOpcode() &&
4469 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4470 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4471 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004472 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004473 Op1I->getOperand(0),
4474 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004475 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004476 Op1I->getOperand(1));
4477 }
4478
4479 if (Op0I && Op1I) {
4480 Value *A, *B, *C, *D;
4481 // (A & B)^(A | B) -> A ^ B
4482 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4483 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4484 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004485 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004486 }
4487 // (A | B)^(A & B) -> A ^ B
4488 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4489 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4490 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004491 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004492 }
4493
4494 // (A & B)^(C & D)
4495 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4496 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4497 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4498 // (X & Y)^(X & Y) -> (Y^Z) & X
4499 Value *X = 0, *Y = 0, *Z = 0;
4500 if (A == C)
4501 X = A, Y = B, Z = D;
4502 else if (A == D)
4503 X = A, Y = B, Z = C;
4504 else if (B == C)
4505 X = B, Y = A, Z = D;
4506 else if (B == D)
4507 X = B, Y = A, Z = C;
4508
4509 if (X) {
4510 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004511 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4512 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004513 }
4514 }
4515 }
4516
4517 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4518 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4519 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4520 return R;
4521
4522 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004523 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004524 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4525 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4526 const Type *SrcTy = Op0C->getOperand(0)->getType();
4527 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4528 // Only do this if the casts both really cause code to be generated.
4529 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4530 I.getType(), TD) &&
4531 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4532 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004533 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004534 Op1C->getOperand(0),
4535 I.getName());
4536 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004537 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004538 }
4539 }
Chris Lattner91882432007-10-24 05:38:08 +00004540 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004541
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004542 return Changed ? &I : 0;
4543}
4544
4545/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4546/// overflowed for this type.
4547static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4548 ConstantInt *In2, bool IsSigned = false) {
4549 Result = cast<ConstantInt>(Add(In1, In2));
4550
4551 if (IsSigned)
4552 if (In2->getValue().isNegative())
4553 return Result->getValue().sgt(In1->getValue());
4554 else
4555 return Result->getValue().slt(In1->getValue());
4556 else
4557 return Result->getValue().ult(In1->getValue());
4558}
4559
4560/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4561/// code necessary to compute the offset from the base pointer (without adding
4562/// in the base pointer). Return the result as a signed integer of intptr size.
4563static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4564 TargetData &TD = IC.getTargetData();
4565 gep_type_iterator GTI = gep_type_begin(GEP);
4566 const Type *IntPtrTy = TD.getIntPtrType();
4567 Value *Result = Constant::getNullValue(IntPtrTy);
4568
4569 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004570 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004571 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4572
Gabor Greif17396002008-06-12 21:37:33 +00004573 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4574 ++i, ++GTI) {
4575 Value *Op = *i;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004576 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004577 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4578 if (OpC->isZero()) continue;
4579
4580 // Handle a struct index, which adds its field offset to the pointer.
4581 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4582 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4583
4584 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4585 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4586 else
4587 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004588 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004589 ConstantInt::get(IntPtrTy, Size),
4590 GEP->getName()+".offs"), I);
4591 continue;
4592 }
4593
4594 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4595 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4596 Scale = ConstantExpr::getMul(OC, Scale);
4597 if (Constant *RC = dyn_cast<Constant>(Result))
4598 Result = ConstantExpr::getAdd(RC, Scale);
4599 else {
4600 // Emit an add instruction.
4601 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004602 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004603 GEP->getName()+".offs"), I);
4604 }
4605 continue;
4606 }
4607 // Convert to correct type.
4608 if (Op->getType() != IntPtrTy) {
4609 if (Constant *OpC = dyn_cast<Constant>(Op))
4610 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4611 else
4612 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4613 Op->getName()+".c"), I);
4614 }
4615 if (Size != 1) {
4616 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4617 if (Constant *OpC = dyn_cast<Constant>(Op))
4618 Op = ConstantExpr::getMul(OpC, Scale);
4619 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00004620 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004621 GEP->getName()+".idx"), I);
4622 }
4623
4624 // Emit an add instruction.
4625 if (isa<Constant>(Op) && isa<Constant>(Result))
4626 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4627 cast<Constant>(Result));
4628 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004629 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004630 GEP->getName()+".offs"), I);
4631 }
4632 return Result;
4633}
4634
Chris Lattnereba75862008-04-22 02:53:33 +00004635
4636/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4637/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4638/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4639/// complex, and scales are involved. The above expression would also be legal
4640/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4641/// later form is less amenable to optimization though, and we are allowed to
4642/// generate the first by knowing that pointer arithmetic doesn't overflow.
4643///
4644/// If we can't emit an optimized form for this expression, this returns null.
4645///
4646static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4647 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00004648 TargetData &TD = IC.getTargetData();
4649 gep_type_iterator GTI = gep_type_begin(GEP);
4650
4651 // Check to see if this gep only has a single variable index. If so, and if
4652 // any constant indices are a multiple of its scale, then we can compute this
4653 // in terms of the scale of the variable index. For example, if the GEP
4654 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4655 // because the expression will cross zero at the same point.
4656 unsigned i, e = GEP->getNumOperands();
4657 int64_t Offset = 0;
4658 for (i = 1; i != e; ++i, ++GTI) {
4659 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4660 // Compute the aggregate offset of constant indices.
4661 if (CI->isZero()) continue;
4662
4663 // Handle a struct index, which adds its field offset to the pointer.
4664 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4665 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4666 } else {
4667 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4668 Offset += Size*CI->getSExtValue();
4669 }
4670 } else {
4671 // Found our variable index.
4672 break;
4673 }
4674 }
4675
4676 // If there are no variable indices, we must have a constant offset, just
4677 // evaluate it the general way.
4678 if (i == e) return 0;
4679
4680 Value *VariableIdx = GEP->getOperand(i);
4681 // Determine the scale factor of the variable element. For example, this is
4682 // 4 if the variable index is into an array of i32.
4683 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4684
4685 // Verify that there are no other variable indices. If so, emit the hard way.
4686 for (++i, ++GTI; i != e; ++i, ++GTI) {
4687 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4688 if (!CI) return 0;
4689
4690 // Compute the aggregate offset of constant indices.
4691 if (CI->isZero()) continue;
4692
4693 // Handle a struct index, which adds its field offset to the pointer.
4694 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4695 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4696 } else {
4697 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4698 Offset += Size*CI->getSExtValue();
4699 }
4700 }
4701
4702 // Okay, we know we have a single variable index, which must be a
4703 // pointer/array/vector index. If there is no offset, life is simple, return
4704 // the index.
4705 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4706 if (Offset == 0) {
4707 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4708 // we don't need to bother extending: the extension won't affect where the
4709 // computation crosses zero.
4710 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4711 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4712 VariableIdx->getNameStart(), &I);
4713 return VariableIdx;
4714 }
4715
4716 // Otherwise, there is an index. The computation we will do will be modulo
4717 // the pointer size, so get it.
4718 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4719
4720 Offset &= PtrSizeMask;
4721 VariableScale &= PtrSizeMask;
4722
4723 // To do this transformation, any constant index must be a multiple of the
4724 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4725 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4726 // multiple of the variable scale.
4727 int64_t NewOffs = Offset / (int64_t)VariableScale;
4728 if (Offset != NewOffs*(int64_t)VariableScale)
4729 return 0;
4730
4731 // Okay, we can do this evaluation. Start by converting the index to intptr.
4732 const Type *IntPtrTy = TD.getIntPtrType();
4733 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00004734 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00004735 true /*SExt*/,
4736 VariableIdx->getNameStart(), &I);
4737 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00004738 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00004739}
4740
4741
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004742/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4743/// else. At this point we know that the GEP is on the LHS of the comparison.
4744Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4745 ICmpInst::Predicate Cond,
4746 Instruction &I) {
4747 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4748
Chris Lattnereba75862008-04-22 02:53:33 +00004749 // Look through bitcasts.
4750 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4751 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004752
4753 Value *PtrBase = GEPLHS->getOperand(0);
4754 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004755 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00004756 // This transformation (ignoring the base and scales) is valid because we
4757 // know pointers can't overflow. See if we can output an optimized form.
4758 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4759
4760 // If not, synthesize the offset the hard way.
4761 if (Offset == 0)
4762 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00004763 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4764 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004765 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4766 // If the base pointers are different, but the indices are the same, just
4767 // compare the base pointer.
4768 if (PtrBase != GEPRHS->getOperand(0)) {
4769 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4770 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4771 GEPRHS->getOperand(0)->getType();
4772 if (IndicesTheSame)
4773 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4774 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4775 IndicesTheSame = false;
4776 break;
4777 }
4778
4779 // If all indices are the same, just compare the base pointers.
4780 if (IndicesTheSame)
4781 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4782 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4783
4784 // Otherwise, the base pointers are different and the indices are
4785 // different, bail out.
4786 return 0;
4787 }
4788
4789 // If one of the GEPs has all zero indices, recurse.
4790 bool AllZeros = true;
4791 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4792 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4793 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4794 AllZeros = false;
4795 break;
4796 }
4797 if (AllZeros)
4798 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4799 ICmpInst::getSwappedPredicate(Cond), I);
4800
4801 // If the other GEP has all zero indices, recurse.
4802 AllZeros = true;
4803 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4804 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4805 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4806 AllZeros = false;
4807 break;
4808 }
4809 if (AllZeros)
4810 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4811
4812 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4813 // If the GEPs only differ by one index, compare it.
4814 unsigned NumDifferences = 0; // Keep track of # differences.
4815 unsigned DiffOperand = 0; // The operand that differs.
4816 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4817 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4818 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4819 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4820 // Irreconcilable differences.
4821 NumDifferences = 2;
4822 break;
4823 } else {
4824 if (NumDifferences++) break;
4825 DiffOperand = i;
4826 }
4827 }
4828
4829 if (NumDifferences == 0) // SAME GEP?
4830 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004831 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00004832 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00004833
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004834 else if (NumDifferences == 1) {
4835 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4836 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4837 // Make sure we do a signed comparison here.
4838 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4839 }
4840 }
4841
4842 // Only lower this if the icmp is the only user of the GEP or if we expect
4843 // the result to fold to a constant!
4844 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4845 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4846 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4847 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4848 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4849 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4850 }
4851 }
4852 return 0;
4853}
4854
Chris Lattnere6b62d92008-05-19 20:18:56 +00004855/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4856///
4857Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4858 Instruction *LHSI,
4859 Constant *RHSC) {
4860 if (!isa<ConstantFP>(RHSC)) return 0;
4861 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4862
4863 // Get the width of the mantissa. We don't want to hack on conversions that
4864 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00004865 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00004866 if (MantissaWidth == -1) return 0; // Unknown.
4867
4868 // Check to see that the input is converted from an integer type that is small
4869 // enough that preserves all bits. TODO: check here for "known" sign bits.
4870 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4871 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4872
4873 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4874 if (isa<UIToFPInst>(LHSI))
4875 ++InputSize;
4876
4877 // If the conversion would lose info, don't hack on this.
4878 if ((int)InputSize > MantissaWidth)
4879 return 0;
4880
4881 // Otherwise, we can potentially simplify the comparison. We know that it
4882 // will always come through as an integer value and we know the constant is
4883 // not a NAN (it would have been previously simplified).
4884 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4885
4886 ICmpInst::Predicate Pred;
4887 switch (I.getPredicate()) {
4888 default: assert(0 && "Unexpected predicate!");
4889 case FCmpInst::FCMP_UEQ:
4890 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4891 case FCmpInst::FCMP_UGT:
4892 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4893 case FCmpInst::FCMP_UGE:
4894 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4895 case FCmpInst::FCMP_ULT:
4896 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4897 case FCmpInst::FCMP_ULE:
4898 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4899 case FCmpInst::FCMP_UNE:
4900 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4901 case FCmpInst::FCMP_ORD:
4902 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4903 case FCmpInst::FCMP_UNO:
4904 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4905 }
4906
4907 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4908
4909 // Now we know that the APFloat is a normal number, zero or inf.
4910
Chris Lattnerf13ff492008-05-20 03:50:52 +00004911 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00004912 // comparing an i8 to 300.0.
4913 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4914
4915 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4916 // and large values.
4917 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4918 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4919 APFloat::rmNearestTiesToEven);
4920 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner82a80002008-05-24 04:06:28 +00004921 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4922 Pred == ICmpInst::ICMP_SLE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00004923 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4924 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4925 }
4926
4927 // See if the RHS value is < SignedMin.
4928 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4929 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4930 APFloat::rmNearestTiesToEven);
4931 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner82a80002008-05-24 04:06:28 +00004932 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4933 Pred == ICmpInst::ICMP_SGE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00004934 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4935 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4936 }
4937
4938 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4939 // it may still be fractional. See if it is fractional by casting the FP
4940 // value to the integer value and back, checking for equality. Don't do this
4941 // for zero, because -0.0 is not fractional.
4942 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4943 if (!RHS.isZero() &&
4944 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4945 // If we had a comparison against a fractional value, we have to adjust
4946 // the compare predicate and sometimes the value. RHSC is rounded towards
4947 // zero at this point.
4948 switch (Pred) {
4949 default: assert(0 && "Unexpected integer comparison!");
4950 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
4951 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4952 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
4953 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4954 case ICmpInst::ICMP_SLE:
4955 // (float)int <= 4.4 --> int <= 4
4956 // (float)int <= -4.4 --> int < -4
4957 if (RHS.isNegative())
4958 Pred = ICmpInst::ICMP_SLT;
4959 break;
4960 case ICmpInst::ICMP_SLT:
4961 // (float)int < -4.4 --> int < -4
4962 // (float)int < 4.4 --> int <= 4
4963 if (!RHS.isNegative())
4964 Pred = ICmpInst::ICMP_SLE;
4965 break;
4966 case ICmpInst::ICMP_SGT:
4967 // (float)int > 4.4 --> int > 4
4968 // (float)int > -4.4 --> int >= -4
4969 if (RHS.isNegative())
4970 Pred = ICmpInst::ICMP_SGE;
4971 break;
4972 case ICmpInst::ICMP_SGE:
4973 // (float)int >= -4.4 --> int >= -4
4974 // (float)int >= 4.4 --> int > 4
4975 if (!RHS.isNegative())
4976 Pred = ICmpInst::ICMP_SGT;
4977 break;
4978 }
4979 }
4980
4981 // Lower this FP comparison into an appropriate integer version of the
4982 // comparison.
4983 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4984}
4985
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004986Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4987 bool Changed = SimplifyCompare(I);
4988 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4989
4990 // Fold trivial predicates.
4991 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4992 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4993 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4994 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4995
4996 // Simplify 'fcmp pred X, X'
4997 if (Op0 == Op1) {
4998 switch (I.getPredicate()) {
4999 default: assert(0 && "Unknown predicate!");
5000 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5001 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5002 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5003 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5004 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5005 case FCmpInst::FCMP_OLT: // True if ordered and less than
5006 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5007 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5008
5009 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5010 case FCmpInst::FCMP_ULT: // True if unordered or less than
5011 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5012 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5013 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5014 I.setPredicate(FCmpInst::FCMP_UNO);
5015 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5016 return &I;
5017
5018 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5019 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5020 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5021 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5022 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5023 I.setPredicate(FCmpInst::FCMP_ORD);
5024 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5025 return &I;
5026 }
5027 }
5028
5029 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5030 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5031
5032 // Handle fcmp with constant RHS
5033 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005034 // If the constant is a nan, see if we can fold the comparison based on it.
5035 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5036 if (CFP->getValueAPF().isNaN()) {
5037 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5038 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005039 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5040 "Comparison must be either ordered or unordered!");
5041 // True if unordered.
5042 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005043 }
5044 }
5045
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005046 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5047 switch (LHSI->getOpcode()) {
5048 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005049 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5050 // block. If in the same block, we're encouraging jump threading. If
5051 // not, we are just pessimizing the code by making an i1 phi.
5052 if (LHSI->getParent() == I.getParent())
5053 if (Instruction *NV = FoldOpIntoPhi(I))
5054 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005055 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005056 case Instruction::SIToFP:
5057 case Instruction::UIToFP:
5058 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5059 return NV;
5060 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005061 case Instruction::Select:
5062 // If either operand of the select is a constant, we can fold the
5063 // comparison into the select arms, which will cause one to be
5064 // constant folded and the select turned into a bitwise or.
5065 Value *Op1 = 0, *Op2 = 0;
5066 if (LHSI->hasOneUse()) {
5067 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5068 // Fold the known value into the constant operand.
5069 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5070 // Insert a new FCmp of the other select operand.
5071 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5072 LHSI->getOperand(2), RHSC,
5073 I.getName()), I);
5074 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5075 // Fold the known value into the constant operand.
5076 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5077 // Insert a new FCmp of the other select operand.
5078 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5079 LHSI->getOperand(1), RHSC,
5080 I.getName()), I);
5081 }
5082 }
5083
5084 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005085 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005086 break;
5087 }
5088 }
5089
5090 return Changed ? &I : 0;
5091}
5092
5093Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5094 bool Changed = SimplifyCompare(I);
5095 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5096 const Type *Ty = Op0->getType();
5097
5098 // icmp X, X
5099 if (Op0 == Op1)
5100 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005101 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005102
5103 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5104 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005105
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005106 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5107 // addresses never equal each other! We already know that Op0 != Op1.
5108 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5109 isa<ConstantPointerNull>(Op0)) &&
5110 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5111 isa<ConstantPointerNull>(Op1)))
5112 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005113 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005114
5115 // icmp's with boolean values can always be turned into bitwise operations
5116 if (Ty == Type::Int1Ty) {
5117 switch (I.getPredicate()) {
5118 default: assert(0 && "Invalid icmp instruction!");
5119 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005120 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005121 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005122 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005123 }
5124 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005125 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005126
5127 case ICmpInst::ICMP_UGT:
5128 case ICmpInst::ICMP_SGT:
5129 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5130 // FALL THROUGH
5131 case ICmpInst::ICMP_ULT:
5132 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005133 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005134 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005135 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005136 }
5137 case ICmpInst::ICMP_UGE:
5138 case ICmpInst::ICMP_SGE:
5139 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5140 // FALL THROUGH
5141 case ICmpInst::ICMP_ULE:
5142 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005143 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005144 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005145 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005146 }
5147 }
5148 }
5149
5150 // See if we are doing a comparison between a constant and an instruction that
5151 // can be folded into the comparison.
5152 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005153 Value *A, *B;
5154
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005155 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5156 if (I.isEquality() && CI->isNullValue() &&
5157 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5158 // (icmp cond A B) if cond is equality
5159 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005160 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005161
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005162 switch (I.getPredicate()) {
5163 default: break;
5164 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5165 if (CI->isMinValue(false))
5166 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5167 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5168 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5169 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5170 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5171 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5172 if (CI->isMinValue(true))
5173 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5174 ConstantInt::getAllOnesValue(Op0->getType()));
5175
5176 break;
5177
5178 case ICmpInst::ICMP_SLT:
5179 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5180 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5181 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5182 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5183 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5184 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5185 break;
5186
5187 case ICmpInst::ICMP_UGT:
5188 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5189 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5190 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5191 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5192 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5193 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5194
5195 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5196 if (CI->isMaxValue(true))
5197 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5198 ConstantInt::getNullValue(Op0->getType()));
5199 break;
5200
5201 case ICmpInst::ICMP_SGT:
5202 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5203 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5204 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5205 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5206 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5207 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5208 break;
5209
5210 case ICmpInst::ICMP_ULE:
5211 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5212 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5213 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5214 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5215 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5216 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5217 break;
5218
5219 case ICmpInst::ICMP_SLE:
5220 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5221 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5222 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5223 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5224 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5225 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5226 break;
5227
5228 case ICmpInst::ICMP_UGE:
5229 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5230 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5231 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5232 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5233 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5234 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5235 break;
5236
5237 case ICmpInst::ICMP_SGE:
5238 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5239 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5240 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5241 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5242 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5243 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5244 break;
5245 }
5246
5247 // If we still have a icmp le or icmp ge instruction, turn it into the
5248 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5249 // already been handled above, this requires little checking.
5250 //
5251 switch (I.getPredicate()) {
5252 default: break;
5253 case ICmpInst::ICMP_ULE:
5254 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5255 case ICmpInst::ICMP_SLE:
5256 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5257 case ICmpInst::ICMP_UGE:
5258 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5259 case ICmpInst::ICMP_SGE:
5260 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5261 }
5262
5263 // See if we can fold the comparison based on bits known to be zero or one
5264 // in the input. If this comparison is a normal comparison, it demands all
5265 // bits, if it is a sign bit comparison, it only demands the sign bit.
5266
5267 bool UnusedBit;
5268 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5269
5270 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5271 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5272 if (SimplifyDemandedBits(Op0,
5273 isSignBit ? APInt::getSignBit(BitWidth)
5274 : APInt::getAllOnesValue(BitWidth),
5275 KnownZero, KnownOne, 0))
5276 return &I;
5277
5278 // Given the known and unknown bits, compute a range that the LHS could be
5279 // in.
5280 if ((KnownOne | KnownZero) != 0) {
5281 // Compute the Min, Max and RHS values based on the known bits. For the
5282 // EQ and NE we use unsigned values.
5283 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5284 const APInt& RHSVal = CI->getValue();
5285 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5286 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5287 Max);
5288 } else {
5289 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5290 Max);
5291 }
5292 switch (I.getPredicate()) { // LE/GE have been folded already.
5293 default: assert(0 && "Unknown icmp opcode!");
5294 case ICmpInst::ICMP_EQ:
5295 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5296 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5297 break;
5298 case ICmpInst::ICMP_NE:
5299 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5300 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5301 break;
5302 case ICmpInst::ICMP_ULT:
5303 if (Max.ult(RHSVal))
5304 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5305 if (Min.uge(RHSVal))
5306 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5307 break;
5308 case ICmpInst::ICMP_UGT:
5309 if (Min.ugt(RHSVal))
5310 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5311 if (Max.ule(RHSVal))
5312 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5313 break;
5314 case ICmpInst::ICMP_SLT:
5315 if (Max.slt(RHSVal))
5316 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5317 if (Min.sgt(RHSVal))
5318 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5319 break;
5320 case ICmpInst::ICMP_SGT:
5321 if (Min.sgt(RHSVal))
5322 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5323 if (Max.sle(RHSVal))
5324 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5325 break;
5326 }
5327 }
5328
5329 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5330 // instruction, see if that instruction also has constants so that the
5331 // instruction can be folded into the icmp
5332 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5333 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5334 return Res;
5335 }
5336
5337 // Handle icmp with constant (but not simple integer constant) RHS
5338 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5339 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5340 switch (LHSI->getOpcode()) {
5341 case Instruction::GetElementPtr:
5342 if (RHSC->isNullValue()) {
5343 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5344 bool isAllZeros = true;
5345 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5346 if (!isa<Constant>(LHSI->getOperand(i)) ||
5347 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5348 isAllZeros = false;
5349 break;
5350 }
5351 if (isAllZeros)
5352 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5353 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5354 }
5355 break;
5356
5357 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005358 // Only fold icmp into the PHI if the phi and fcmp are in the same
5359 // block. If in the same block, we're encouraging jump threading. If
5360 // not, we are just pessimizing the code by making an i1 phi.
5361 if (LHSI->getParent() == I.getParent())
5362 if (Instruction *NV = FoldOpIntoPhi(I))
5363 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005364 break;
5365 case Instruction::Select: {
5366 // If either operand of the select is a constant, we can fold the
5367 // comparison into the select arms, which will cause one to be
5368 // constant folded and the select turned into a bitwise or.
5369 Value *Op1 = 0, *Op2 = 0;
5370 if (LHSI->hasOneUse()) {
5371 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5372 // Fold the known value into the constant operand.
5373 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5374 // Insert a new ICmp of the other select operand.
5375 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5376 LHSI->getOperand(2), RHSC,
5377 I.getName()), I);
5378 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5379 // Fold the known value into the constant operand.
5380 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5381 // Insert a new ICmp of the other select operand.
5382 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5383 LHSI->getOperand(1), RHSC,
5384 I.getName()), I);
5385 }
5386 }
5387
5388 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005389 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005390 break;
5391 }
5392 case Instruction::Malloc:
5393 // If we have (malloc != null), and if the malloc has a single use, we
5394 // can assume it is successful and remove the malloc.
5395 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5396 AddToWorkList(LHSI);
5397 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005398 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005399 }
5400 break;
5401 }
5402 }
5403
5404 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5405 if (User *GEP = dyn_castGetElementPtr(Op0))
5406 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5407 return NI;
5408 if (User *GEP = dyn_castGetElementPtr(Op1))
5409 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5410 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5411 return NI;
5412
5413 // Test to see if the operands of the icmp are casted versions of other
5414 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5415 // now.
5416 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5417 if (isa<PointerType>(Op0->getType()) &&
5418 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5419 // We keep moving the cast from the left operand over to the right
5420 // operand, where it can often be eliminated completely.
5421 Op0 = CI->getOperand(0);
5422
5423 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5424 // so eliminate it as well.
5425 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5426 Op1 = CI2->getOperand(0);
5427
5428 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005429 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005430 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5431 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5432 } else {
5433 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005434 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005435 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005436 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005437 return new ICmpInst(I.getPredicate(), Op0, Op1);
5438 }
5439 }
5440
5441 if (isa<CastInst>(Op0)) {
5442 // Handle the special case of: icmp (cast bool to X), <cst>
5443 // This comes up when you have code like
5444 // int X = A < B;
5445 // if (X) ...
5446 // For generality, we handle any zero-extension of any operand comparison
5447 // with a constant or another cast from the same type.
5448 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5449 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5450 return R;
5451 }
5452
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005453 // ~x < ~y --> y < x
5454 { Value *A, *B;
5455 if (match(Op0, m_Not(m_Value(A))) &&
5456 match(Op1, m_Not(m_Value(B))))
5457 return new ICmpInst(I.getPredicate(), B, A);
5458 }
5459
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005460 if (I.isEquality()) {
5461 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005462
5463 // -x == -y --> x == y
5464 if (match(Op0, m_Neg(m_Value(A))) &&
5465 match(Op1, m_Neg(m_Value(B))))
5466 return new ICmpInst(I.getPredicate(), A, B);
5467
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005468 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5469 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5470 Value *OtherVal = A == Op1 ? B : A;
5471 return new ICmpInst(I.getPredicate(), OtherVal,
5472 Constant::getNullValue(A->getType()));
5473 }
5474
5475 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5476 // A^c1 == C^c2 --> A == C^(c1^c2)
5477 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5478 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5479 if (Op1->hasOneUse()) {
5480 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005481 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005482 return new ICmpInst(I.getPredicate(), A,
5483 InsertNewInstBefore(Xor, I));
5484 }
5485
5486 // A^B == A^D -> B == D
5487 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5488 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5489 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5490 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5491 }
5492 }
5493
5494 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5495 (A == Op0 || B == Op0)) {
5496 // A == (A^B) -> B == 0
5497 Value *OtherVal = A == Op0 ? B : A;
5498 return new ICmpInst(I.getPredicate(), OtherVal,
5499 Constant::getNullValue(A->getType()));
5500 }
5501 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5502 // (A-B) == A -> B == 0
5503 return new ICmpInst(I.getPredicate(), B,
5504 Constant::getNullValue(B->getType()));
5505 }
5506 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5507 // A == (A-B) -> B == 0
5508 return new ICmpInst(I.getPredicate(), B,
5509 Constant::getNullValue(B->getType()));
5510 }
5511
5512 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5513 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5514 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5515 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5516 Value *X = 0, *Y = 0, *Z = 0;
5517
5518 if (A == C) {
5519 X = B; Y = D; Z = A;
5520 } else if (A == D) {
5521 X = B; Y = C; Z = A;
5522 } else if (B == C) {
5523 X = A; Y = D; Z = B;
5524 } else if (B == D) {
5525 X = A; Y = C; Z = B;
5526 }
5527
5528 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005529 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5530 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005531 I.setOperand(0, Op1);
5532 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5533 return &I;
5534 }
5535 }
5536 }
5537 return Changed ? &I : 0;
5538}
5539
5540
5541/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5542/// and CmpRHS are both known to be integer constants.
5543Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5544 ConstantInt *DivRHS) {
5545 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5546 const APInt &CmpRHSV = CmpRHS->getValue();
5547
5548 // FIXME: If the operand types don't match the type of the divide
5549 // then don't attempt this transform. The code below doesn't have the
5550 // logic to deal with a signed divide and an unsigned compare (and
5551 // vice versa). This is because (x /s C1) <s C2 produces different
5552 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5553 // (x /u C1) <u C2. Simply casting the operands and result won't
5554 // work. :( The if statement below tests that condition and bails
5555 // if it finds it.
5556 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5557 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5558 return 0;
5559 if (DivRHS->isZero())
5560 return 0; // The ProdOV computation fails on divide by zero.
5561
5562 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5563 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5564 // C2 (CI). By solving for X we can turn this into a range check
5565 // instead of computing a divide.
5566 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5567
5568 // Determine if the product overflows by seeing if the product is
5569 // not equal to the divide. Make sure we do the same kind of divide
5570 // as in the LHS instruction that we're folding.
5571 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5572 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5573
5574 // Get the ICmp opcode
5575 ICmpInst::Predicate Pred = ICI.getPredicate();
5576
5577 // Figure out the interval that is being checked. For example, a comparison
5578 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5579 // Compute this interval based on the constants involved and the signedness of
5580 // the compare/divide. This computes a half-open interval, keeping track of
5581 // whether either value in the interval overflows. After analysis each
5582 // overflow variable is set to 0 if it's corresponding bound variable is valid
5583 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5584 int LoOverflow = 0, HiOverflow = 0;
5585 ConstantInt *LoBound = 0, *HiBound = 0;
5586
5587
5588 if (!DivIsSigned) { // udiv
5589 // e.g. X/5 op 3 --> [15, 20)
5590 LoBound = Prod;
5591 HiOverflow = LoOverflow = ProdOV;
5592 if (!HiOverflow)
5593 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005594 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005595 if (CmpRHSV == 0) { // (X / pos) op 0
5596 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5597 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5598 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005599 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005600 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5601 HiOverflow = LoOverflow = ProdOV;
5602 if (!HiOverflow)
5603 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5604 } else { // (X / pos) op neg
5605 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5606 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5607 LoOverflow = AddWithOverflow(LoBound, Prod,
5608 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5609 HiBound = AddOne(Prod);
5610 HiOverflow = ProdOV ? -1 : 0;
5611 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005612 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005613 if (CmpRHSV == 0) { // (X / neg) op 0
5614 // e.g. X/-5 op 0 --> [-4, 5)
5615 LoBound = AddOne(DivRHS);
5616 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5617 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5618 HiOverflow = 1; // [INTMIN+1, overflow)
5619 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5620 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005621 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005622 // e.g. X/-5 op 3 --> [-19, -14)
5623 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5624 if (!LoOverflow)
5625 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5626 HiBound = AddOne(Prod);
5627 } else { // (X / neg) op neg
5628 // e.g. X/-5 op -3 --> [15, 20)
5629 LoBound = Prod;
5630 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5631 HiBound = Subtract(Prod, DivRHS);
5632 }
5633
5634 // Dividing by a negative swaps the condition. LT <-> GT
5635 Pred = ICmpInst::getSwappedPredicate(Pred);
5636 }
5637
5638 Value *X = DivI->getOperand(0);
5639 switch (Pred) {
5640 default: assert(0 && "Unhandled icmp opcode!");
5641 case ICmpInst::ICMP_EQ:
5642 if (LoOverflow && HiOverflow)
5643 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5644 else if (HiOverflow)
5645 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5646 ICmpInst::ICMP_UGE, X, LoBound);
5647 else if (LoOverflow)
5648 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5649 ICmpInst::ICMP_ULT, X, HiBound);
5650 else
5651 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5652 case ICmpInst::ICMP_NE:
5653 if (LoOverflow && HiOverflow)
5654 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5655 else if (HiOverflow)
5656 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5657 ICmpInst::ICMP_ULT, X, LoBound);
5658 else if (LoOverflow)
5659 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5660 ICmpInst::ICMP_UGE, X, HiBound);
5661 else
5662 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5663 case ICmpInst::ICMP_ULT:
5664 case ICmpInst::ICMP_SLT:
5665 if (LoOverflow == +1) // Low bound is greater than input range.
5666 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5667 if (LoOverflow == -1) // Low bound is less than input range.
5668 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5669 return new ICmpInst(Pred, X, LoBound);
5670 case ICmpInst::ICMP_UGT:
5671 case ICmpInst::ICMP_SGT:
5672 if (HiOverflow == +1) // High bound greater than input range.
5673 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5674 else if (HiOverflow == -1) // High bound less than input range.
5675 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5676 if (Pred == ICmpInst::ICMP_UGT)
5677 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5678 else
5679 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5680 }
5681}
5682
5683
5684/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5685///
5686Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5687 Instruction *LHSI,
5688 ConstantInt *RHS) {
5689 const APInt &RHSV = RHS->getValue();
5690
5691 switch (LHSI->getOpcode()) {
5692 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5693 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5694 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5695 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005696 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5697 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005698 Value *CompareVal = LHSI->getOperand(0);
5699
5700 // If the sign bit of the XorCST is not set, there is no change to
5701 // the operation, just stop using the Xor.
5702 if (!XorCST->getValue().isNegative()) {
5703 ICI.setOperand(0, CompareVal);
5704 AddToWorkList(LHSI);
5705 return &ICI;
5706 }
5707
5708 // Was the old condition true if the operand is positive?
5709 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5710
5711 // If so, the new one isn't.
5712 isTrueIfPositive ^= true;
5713
5714 if (isTrueIfPositive)
5715 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5716 else
5717 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5718 }
5719 }
5720 break;
5721 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5722 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5723 LHSI->getOperand(0)->hasOneUse()) {
5724 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5725
5726 // If the LHS is an AND of a truncating cast, we can widen the
5727 // and/compare to be the input width without changing the value
5728 // produced, eliminating a cast.
5729 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5730 // We can do this transformation if either the AND constant does not
5731 // have its sign bit set or if it is an equality comparison.
5732 // Extending a relational comparison when we're checking the sign
5733 // bit would not work.
5734 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005735 (ICI.isEquality() ||
5736 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005737 uint32_t BitWidth =
5738 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5739 APInt NewCST = AndCST->getValue();
5740 NewCST.zext(BitWidth);
5741 APInt NewCI = RHSV;
5742 NewCI.zext(BitWidth);
5743 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005744 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005745 ConstantInt::get(NewCST),LHSI->getName());
5746 InsertNewInstBefore(NewAnd, ICI);
5747 return new ICmpInst(ICI.getPredicate(), NewAnd,
5748 ConstantInt::get(NewCI));
5749 }
5750 }
5751
5752 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5753 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5754 // happens a LOT in code produced by the C front-end, for bitfield
5755 // access.
5756 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5757 if (Shift && !Shift->isShift())
5758 Shift = 0;
5759
5760 ConstantInt *ShAmt;
5761 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5762 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5763 const Type *AndTy = AndCST->getType(); // Type of the and.
5764
5765 // We can fold this as long as we can't shift unknown bits
5766 // into the mask. This can only happen with signed shift
5767 // rights, as they sign-extend.
5768 if (ShAmt) {
5769 bool CanFold = Shift->isLogicalShift();
5770 if (!CanFold) {
5771 // To test for the bad case of the signed shr, see if any
5772 // of the bits shifted in could be tested after the mask.
5773 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5774 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5775
5776 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5777 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5778 AndCST->getValue()) == 0)
5779 CanFold = true;
5780 }
5781
5782 if (CanFold) {
5783 Constant *NewCst;
5784 if (Shift->getOpcode() == Instruction::Shl)
5785 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5786 else
5787 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5788
5789 // Check to see if we are shifting out any of the bits being
5790 // compared.
5791 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5792 // If we shifted bits out, the fold is not going to work out.
5793 // As a special case, check to see if this means that the
5794 // result is always true or false now.
5795 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5796 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5797 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5798 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5799 } else {
5800 ICI.setOperand(1, NewCst);
5801 Constant *NewAndCST;
5802 if (Shift->getOpcode() == Instruction::Shl)
5803 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5804 else
5805 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5806 LHSI->setOperand(1, NewAndCST);
5807 LHSI->setOperand(0, Shift->getOperand(0));
5808 AddToWorkList(Shift); // Shift is dead.
5809 AddUsesToWorkList(ICI);
5810 return &ICI;
5811 }
5812 }
5813 }
5814
5815 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5816 // preferable because it allows the C<<Y expression to be hoisted out
5817 // of a loop if Y is invariant and X is not.
5818 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5819 ICI.isEquality() && !Shift->isArithmeticShift() &&
5820 isa<Instruction>(Shift->getOperand(0))) {
5821 // Compute C << Y.
5822 Value *NS;
5823 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005824 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005825 Shift->getOperand(1), "tmp");
5826 } else {
5827 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00005828 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005829 Shift->getOperand(1), "tmp");
5830 }
5831 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5832
5833 // Compute X & (C << Y).
5834 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005835 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005836 InsertNewInstBefore(NewAnd, ICI);
5837
5838 ICI.setOperand(0, NewAnd);
5839 return &ICI;
5840 }
5841 }
5842 break;
5843
5844 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5845 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5846 if (!ShAmt) break;
5847
5848 uint32_t TypeBits = RHSV.getBitWidth();
5849
5850 // Check that the shift amount is in range. If not, don't perform
5851 // undefined shifts. When the shift is visited it will be
5852 // simplified.
5853 if (ShAmt->uge(TypeBits))
5854 break;
5855
5856 if (ICI.isEquality()) {
5857 // If we are comparing against bits always shifted out, the
5858 // comparison cannot succeed.
5859 Constant *Comp =
5860 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5861 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5862 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5863 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5864 return ReplaceInstUsesWith(ICI, Cst);
5865 }
5866
5867 if (LHSI->hasOneUse()) {
5868 // Otherwise strength reduce the shift into an and.
5869 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5870 Constant *Mask =
5871 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5872
5873 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005874 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005875 Mask, LHSI->getName()+".mask");
5876 Value *And = InsertNewInstBefore(AndI, ICI);
5877 return new ICmpInst(ICI.getPredicate(), And,
5878 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5879 }
5880 }
5881
5882 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5883 bool TrueIfSigned = false;
5884 if (LHSI->hasOneUse() &&
5885 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5886 // (X << 31) <s 0 --> (X&1) != 0
5887 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5888 (TypeBits-ShAmt->getZExtValue()-1));
5889 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005890 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005891 Mask, LHSI->getName()+".mask");
5892 Value *And = InsertNewInstBefore(AndI, ICI);
5893
5894 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5895 And, Constant::getNullValue(And->getType()));
5896 }
5897 break;
5898 }
5899
5900 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5901 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00005902 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005903 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00005904 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005905
Chris Lattner5ee84f82008-03-21 05:19:58 +00005906 // Check that the shift amount is in range. If not, don't perform
5907 // undefined shifts. When the shift is visited it will be
5908 // simplified.
5909 uint32_t TypeBits = RHSV.getBitWidth();
5910 if (ShAmt->uge(TypeBits))
5911 break;
5912
5913 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005914
Chris Lattner5ee84f82008-03-21 05:19:58 +00005915 // If we are comparing against bits always shifted out, the
5916 // comparison cannot succeed.
5917 APInt Comp = RHSV << ShAmtVal;
5918 if (LHSI->getOpcode() == Instruction::LShr)
5919 Comp = Comp.lshr(ShAmtVal);
5920 else
5921 Comp = Comp.ashr(ShAmtVal);
5922
5923 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5924 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5925 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5926 return ReplaceInstUsesWith(ICI, Cst);
5927 }
5928
5929 // Otherwise, check to see if the bits shifted out are known to be zero.
5930 // If so, we can compare against the unshifted value:
5931 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00005932 if (LHSI->hasOneUse() &&
5933 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00005934 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5935 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5936 ConstantExpr::getShl(RHS, ShAmt));
5937 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005938
Evan Chengfb9292a2008-04-23 00:38:06 +00005939 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00005940 // Otherwise strength reduce the shift into an and.
5941 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5942 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005943
Chris Lattner5ee84f82008-03-21 05:19:58 +00005944 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00005945 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00005946 Mask, LHSI->getName()+".mask");
5947 Value *And = InsertNewInstBefore(AndI, ICI);
5948 return new ICmpInst(ICI.getPredicate(), And,
5949 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005950 }
5951 break;
5952 }
5953
5954 case Instruction::SDiv:
5955 case Instruction::UDiv:
5956 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5957 // Fold this div into the comparison, producing a range check.
5958 // Determine, based on the divide type, what the range is being
5959 // checked. If there is an overflow on the low or high side, remember
5960 // it, otherwise compute the range [low, hi) bounding the new value.
5961 // See: InsertRangeTest above for the kinds of replacements possible.
5962 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5963 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5964 DivRHS))
5965 return R;
5966 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00005967
5968 case Instruction::Add:
5969 // Fold: icmp pred (add, X, C1), C2
5970
5971 if (!ICI.isEquality()) {
5972 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5973 if (!LHSC) break;
5974 const APInt &LHSV = LHSC->getValue();
5975
5976 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5977 .subtract(LHSV);
5978
5979 if (ICI.isSignedPredicate()) {
5980 if (CR.getLower().isSignBit()) {
5981 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5982 ConstantInt::get(CR.getUpper()));
5983 } else if (CR.getUpper().isSignBit()) {
5984 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5985 ConstantInt::get(CR.getLower()));
5986 }
5987 } else {
5988 if (CR.getLower().isMinValue()) {
5989 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5990 ConstantInt::get(CR.getUpper()));
5991 } else if (CR.getUpper().isMinValue()) {
5992 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5993 ConstantInt::get(CR.getLower()));
5994 }
5995 }
5996 }
5997 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005998 }
5999
6000 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6001 if (ICI.isEquality()) {
6002 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6003
6004 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6005 // the second operand is a constant, simplify a bit.
6006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6007 switch (BO->getOpcode()) {
6008 case Instruction::SRem:
6009 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6010 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6011 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6012 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6013 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006014 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006015 BO->getName());
6016 InsertNewInstBefore(NewRem, ICI);
6017 return new ICmpInst(ICI.getPredicate(), NewRem,
6018 Constant::getNullValue(BO->getType()));
6019 }
6020 }
6021 break;
6022 case Instruction::Add:
6023 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6024 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6025 if (BO->hasOneUse())
6026 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6027 Subtract(RHS, BOp1C));
6028 } else if (RHSV == 0) {
6029 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6030 // efficiently invertible, or if the add has just this one use.
6031 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6032
6033 if (Value *NegVal = dyn_castNegVal(BOp1))
6034 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6035 else if (Value *NegVal = dyn_castNegVal(BOp0))
6036 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6037 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006038 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006039 InsertNewInstBefore(Neg, ICI);
6040 Neg->takeName(BO);
6041 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6042 }
6043 }
6044 break;
6045 case Instruction::Xor:
6046 // For the xor case, we can xor two constants together, eliminating
6047 // the explicit xor.
6048 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6049 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6050 ConstantExpr::getXor(RHS, BOC));
6051
6052 // FALLTHROUGH
6053 case Instruction::Sub:
6054 // Replace (([sub|xor] A, B) != 0) with (A != B)
6055 if (RHSV == 0)
6056 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6057 BO->getOperand(1));
6058 break;
6059
6060 case Instruction::Or:
6061 // If bits are being or'd in that are not present in the constant we
6062 // are comparing against, then the comparison could never succeed!
6063 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6064 Constant *NotCI = ConstantExpr::getNot(RHS);
6065 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6066 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6067 isICMP_NE));
6068 }
6069 break;
6070
6071 case Instruction::And:
6072 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6073 // If bits are being compared against that are and'd out, then the
6074 // comparison can never succeed!
6075 if ((RHSV & ~BOC->getValue()) != 0)
6076 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6077 isICMP_NE));
6078
6079 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6080 if (RHS == BOC && RHSV.isPowerOf2())
6081 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6082 ICmpInst::ICMP_NE, LHSI,
6083 Constant::getNullValue(RHS->getType()));
6084
6085 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00006086 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006087 Value *X = BO->getOperand(0);
6088 Constant *Zero = Constant::getNullValue(X->getType());
6089 ICmpInst::Predicate pred = isICMP_NE ?
6090 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6091 return new ICmpInst(pred, X, Zero);
6092 }
6093
6094 // ((X & ~7) == 0) --> X < 8
6095 if (RHSV == 0 && isHighOnes(BOC)) {
6096 Value *X = BO->getOperand(0);
6097 Constant *NegX = ConstantExpr::getNeg(BOC);
6098 ICmpInst::Predicate pred = isICMP_NE ?
6099 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6100 return new ICmpInst(pred, X, NegX);
6101 }
6102 }
6103 default: break;
6104 }
6105 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6106 // Handle icmp {eq|ne} <intrinsic>, intcst.
6107 if (II->getIntrinsicID() == Intrinsic::bswap) {
6108 AddToWorkList(II);
6109 ICI.setOperand(0, II->getOperand(1));
6110 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6111 return &ICI;
6112 }
6113 }
6114 } else { // Not a ICMP_EQ/ICMP_NE
6115 // If the LHS is a cast from an integral value of the same size,
6116 // then since we know the RHS is a constant, try to simlify.
6117 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6118 Value *CastOp = Cast->getOperand(0);
6119 const Type *SrcTy = CastOp->getType();
6120 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6121 if (SrcTy->isInteger() &&
6122 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6123 // If this is an unsigned comparison, try to make the comparison use
6124 // smaller constant values.
6125 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6126 // X u< 128 => X s> -1
6127 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6128 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6129 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6130 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6131 // X u> 127 => X s< 0
6132 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6133 Constant::getNullValue(SrcTy));
6134 }
6135 }
6136 }
6137 }
6138 return 0;
6139}
6140
6141/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6142/// We only handle extending casts so far.
6143///
6144Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6145 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6146 Value *LHSCIOp = LHSCI->getOperand(0);
6147 const Type *SrcTy = LHSCIOp->getType();
6148 const Type *DestTy = LHSCI->getType();
6149 Value *RHSCIOp;
6150
6151 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6152 // integer type is the same size as the pointer type.
6153 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6154 getTargetData().getPointerSizeInBits() ==
6155 cast<IntegerType>(DestTy)->getBitWidth()) {
6156 Value *RHSOp = 0;
6157 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6158 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6159 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6160 RHSOp = RHSC->getOperand(0);
6161 // If the pointer types don't match, insert a bitcast.
6162 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006163 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006164 }
6165
6166 if (RHSOp)
6167 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6168 }
6169
6170 // The code below only handles extension cast instructions, so far.
6171 // Enforce this.
6172 if (LHSCI->getOpcode() != Instruction::ZExt &&
6173 LHSCI->getOpcode() != Instruction::SExt)
6174 return 0;
6175
6176 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6177 bool isSignedCmp = ICI.isSignedPredicate();
6178
6179 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6180 // Not an extension from the same type?
6181 RHSCIOp = CI->getOperand(0);
6182 if (RHSCIOp->getType() != LHSCIOp->getType())
6183 return 0;
6184
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006185 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006186 // and the other is a zext), then we can't handle this.
6187 if (CI->getOpcode() != LHSCI->getOpcode())
6188 return 0;
6189
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006190 // Deal with equality cases early.
6191 if (ICI.isEquality())
6192 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6193
6194 // A signed comparison of sign extended values simplifies into a
6195 // signed comparison.
6196 if (isSignedCmp && isSignedExt)
6197 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6198
6199 // The other three cases all fold into an unsigned comparison.
6200 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006201 }
6202
6203 // If we aren't dealing with a constant on the RHS, exit early
6204 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6205 if (!CI)
6206 return 0;
6207
6208 // Compute the constant that would happen if we truncated to SrcTy then
6209 // reextended to DestTy.
6210 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6211 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6212
6213 // If the re-extended constant didn't change...
6214 if (Res2 == CI) {
6215 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6216 // For example, we might have:
6217 // %A = sext short %X to uint
6218 // %B = icmp ugt uint %A, 1330
6219 // It is incorrect to transform this into
6220 // %B = icmp ugt short %X, 1330
6221 // because %A may have negative value.
6222 //
6223 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6224 // OR operation is EQ/NE.
6225 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6226 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6227 else
6228 return 0;
6229 }
6230
6231 // The re-extended constant changed so the constant cannot be represented
6232 // in the shorter type. Consequently, we cannot emit a simple comparison.
6233
6234 // First, handle some easy cases. We know the result cannot be equal at this
6235 // point so handle the ICI.isEquality() cases
6236 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6237 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6238 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6239 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6240
6241 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6242 // should have been folded away previously and not enter in here.
6243 Value *Result;
6244 if (isSignedCmp) {
6245 // We're performing a signed comparison.
6246 if (cast<ConstantInt>(CI)->getValue().isNegative())
6247 Result = ConstantInt::getFalse(); // X < (small) --> false
6248 else
6249 Result = ConstantInt::getTrue(); // X < (large) --> true
6250 } else {
6251 // We're performing an unsigned comparison.
6252 if (isSignedExt) {
6253 // We're performing an unsigned comp with a sign extended value.
6254 // This is true if the input is >= 0. [aka >s -1]
6255 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6256 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6257 NegOne, ICI.getName()), ICI);
6258 } else {
6259 // Unsigned extend & unsigned compare -> always true.
6260 Result = ConstantInt::getTrue();
6261 }
6262 }
6263
6264 // Finally, return the value computed.
6265 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6266 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6267 return ReplaceInstUsesWith(ICI, Result);
6268 } else {
6269 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6270 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6271 "ICmp should be folded!");
6272 if (Constant *CI = dyn_cast<Constant>(Result))
6273 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6274 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006275 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006276 }
6277}
6278
6279Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6280 return commonShiftTransforms(I);
6281}
6282
6283Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6284 return commonShiftTransforms(I);
6285}
6286
6287Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006288 if (Instruction *R = commonShiftTransforms(I))
6289 return R;
6290
6291 Value *Op0 = I.getOperand(0);
6292
6293 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6294 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6295 if (CSI->isAllOnesValue())
6296 return ReplaceInstUsesWith(I, CSI);
6297
6298 // See if we can turn a signed shr into an unsigned shr.
6299 if (MaskedValueIsZero(Op0,
6300 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006301 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006302
6303 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006304}
6305
6306Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6307 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6309
6310 // shl X, 0 == X and shr X, 0 == X
6311 // shl 0, X == 0 and shr 0, X == 0
6312 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6313 Op0 == Constant::getNullValue(Op0->getType()))
6314 return ReplaceInstUsesWith(I, Op0);
6315
6316 if (isa<UndefValue>(Op0)) {
6317 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6318 return ReplaceInstUsesWith(I, Op0);
6319 else // undef << X -> 0, undef >>u X -> 0
6320 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6321 }
6322 if (isa<UndefValue>(Op1)) {
6323 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6324 return ReplaceInstUsesWith(I, Op0);
6325 else // X << undef, X >>u undef -> 0
6326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6327 }
6328
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006329 // Try to fold constant and into select arguments.
6330 if (isa<Constant>(Op0))
6331 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6332 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6333 return R;
6334
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006335 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6336 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6337 return Res;
6338 return 0;
6339}
6340
6341Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6342 BinaryOperator &I) {
6343 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6344
6345 // See if we can simplify any instructions used by the instruction whose sole
6346 // purpose is to compute bits we don't care about.
6347 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6348 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6349 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6350 KnownZero, KnownOne))
6351 return &I;
6352
6353 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6354 // of a signed value.
6355 //
6356 if (Op1->uge(TypeBits)) {
6357 if (I.getOpcode() != Instruction::AShr)
6358 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6359 else {
6360 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6361 return &I;
6362 }
6363 }
6364
6365 // ((X*C1) << C2) == (X * (C1 << C2))
6366 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6367 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6368 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006369 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006370 ConstantExpr::getShl(BOOp, Op1));
6371
6372 // Try to fold constant and into select arguments.
6373 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6374 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6375 return R;
6376 if (isa<PHINode>(Op0))
6377 if (Instruction *NV = FoldOpIntoPhi(I))
6378 return NV;
6379
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006380 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6381 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6382 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6383 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6384 // place. Don't try to do this transformation in this case. Also, we
6385 // require that the input operand is a shift-by-constant so that we have
6386 // confidence that the shifts will get folded together. We could do this
6387 // xform in more cases, but it is unlikely to be profitable.
6388 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6389 isa<ConstantInt>(TrOp->getOperand(1))) {
6390 // Okay, we'll do this xform. Make the shift of shift.
6391 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006392 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006393 I.getName());
6394 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6395
6396 // For logical shifts, the truncation has the effect of making the high
6397 // part of the register be zeros. Emulate this by inserting an AND to
6398 // clear the top bits as needed. This 'and' will usually be zapped by
6399 // other xforms later if dead.
6400 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6401 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6402 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6403
6404 // The mask we constructed says what the trunc would do if occurring
6405 // between the shifts. We want to know the effect *after* the second
6406 // shift. We know that it is a logical shift by a constant, so adjust the
6407 // mask as appropriate.
6408 if (I.getOpcode() == Instruction::Shl)
6409 MaskV <<= Op1->getZExtValue();
6410 else {
6411 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6412 MaskV = MaskV.lshr(Op1->getZExtValue());
6413 }
6414
Gabor Greifa645dd32008-05-16 19:29:10 +00006415 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006416 TI->getName());
6417 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6418
6419 // Return the value truncated to the interesting size.
6420 return new TruncInst(And, I.getType());
6421 }
6422 }
6423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006424 if (Op0->hasOneUse()) {
6425 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6426 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6427 Value *V1, *V2;
6428 ConstantInt *CC;
6429 switch (Op0BO->getOpcode()) {
6430 default: break;
6431 case Instruction::Add:
6432 case Instruction::And:
6433 case Instruction::Or:
6434 case Instruction::Xor: {
6435 // These operators commute.
6436 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6437 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6438 match(Op0BO->getOperand(1),
6439 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006440 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006441 Op0BO->getOperand(0), Op1,
6442 Op0BO->getName());
6443 InsertNewInstBefore(YS, I); // (Y << C)
6444 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006445 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006446 Op0BO->getOperand(1)->getName());
6447 InsertNewInstBefore(X, I); // (X + (Y << C))
6448 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006449 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006450 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6451 }
6452
6453 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6454 Value *Op0BOOp1 = Op0BO->getOperand(1);
6455 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6456 match(Op0BOOp1,
6457 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6458 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6459 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006460 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006461 Op0BO->getOperand(0), Op1,
6462 Op0BO->getName());
6463 InsertNewInstBefore(YS, I); // (Y << C)
6464 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006465 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006466 V1->getName()+".mask");
6467 InsertNewInstBefore(XM, I); // X & (CC << C)
6468
Gabor Greifa645dd32008-05-16 19:29:10 +00006469 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006470 }
6471 }
6472
6473 // FALL THROUGH.
6474 case Instruction::Sub: {
6475 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6476 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6477 match(Op0BO->getOperand(0),
6478 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006479 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006480 Op0BO->getOperand(1), Op1,
6481 Op0BO->getName());
6482 InsertNewInstBefore(YS, I); // (Y << C)
6483 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006484 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006485 Op0BO->getOperand(0)->getName());
6486 InsertNewInstBefore(X, I); // (X + (Y << C))
6487 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006488 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006489 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6490 }
6491
6492 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6493 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6494 match(Op0BO->getOperand(0),
6495 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6496 m_ConstantInt(CC))) && V2 == Op1 &&
6497 cast<BinaryOperator>(Op0BO->getOperand(0))
6498 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006499 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006500 Op0BO->getOperand(1), Op1,
6501 Op0BO->getName());
6502 InsertNewInstBefore(YS, I); // (Y << C)
6503 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006504 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006505 V1->getName()+".mask");
6506 InsertNewInstBefore(XM, I); // X & (CC << C)
6507
Gabor Greifa645dd32008-05-16 19:29:10 +00006508 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006509 }
6510
6511 break;
6512 }
6513 }
6514
6515
6516 // If the operand is an bitwise operator with a constant RHS, and the
6517 // shift is the only use, we can pull it out of the shift.
6518 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6519 bool isValid = true; // Valid only for And, Or, Xor
6520 bool highBitSet = false; // Transform if high bit of constant set?
6521
6522 switch (Op0BO->getOpcode()) {
6523 default: isValid = false; break; // Do not perform transform!
6524 case Instruction::Add:
6525 isValid = isLeftShift;
6526 break;
6527 case Instruction::Or:
6528 case Instruction::Xor:
6529 highBitSet = false;
6530 break;
6531 case Instruction::And:
6532 highBitSet = true;
6533 break;
6534 }
6535
6536 // If this is a signed shift right, and the high bit is modified
6537 // by the logical operation, do not perform the transformation.
6538 // The highBitSet boolean indicates the value of the high bit of
6539 // the constant which would cause it to be modified for this
6540 // operation.
6541 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006542 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006543 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006544
6545 if (isValid) {
6546 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6547
6548 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006549 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006550 InsertNewInstBefore(NewShift, I);
6551 NewShift->takeName(Op0BO);
6552
Gabor Greifa645dd32008-05-16 19:29:10 +00006553 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006554 NewRHS);
6555 }
6556 }
6557 }
6558 }
6559
6560 // Find out if this is a shift of a shift by a constant.
6561 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6562 if (ShiftOp && !ShiftOp->isShift())
6563 ShiftOp = 0;
6564
6565 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6566 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6567 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6568 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6569 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6570 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6571 Value *X = ShiftOp->getOperand(0);
6572
6573 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6574 if (AmtSum > TypeBits)
6575 AmtSum = TypeBits;
6576
6577 const IntegerType *Ty = cast<IntegerType>(I.getType());
6578
6579 // Check for (X << c1) << c2 and (X >> c1) >> c2
6580 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006581 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006582 ConstantInt::get(Ty, AmtSum));
6583 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6584 I.getOpcode() == Instruction::AShr) {
6585 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006586 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006587 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6588 I.getOpcode() == Instruction::LShr) {
6589 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6590 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006591 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006592 InsertNewInstBefore(Shift, I);
6593
6594 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006595 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006596 }
6597
6598 // Okay, if we get here, one shift must be left, and the other shift must be
6599 // right. See if the amounts are equal.
6600 if (ShiftAmt1 == ShiftAmt2) {
6601 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6602 if (I.getOpcode() == Instruction::Shl) {
6603 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006604 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006605 }
6606 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6607 if (I.getOpcode() == Instruction::LShr) {
6608 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006609 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006610 }
6611 // We can simplify ((X << C) >>s C) into a trunc + sext.
6612 // NOTE: we could do this for any C, but that would make 'unusual' integer
6613 // types. For now, just stick to ones well-supported by the code
6614 // generators.
6615 const Type *SExtType = 0;
6616 switch (Ty->getBitWidth() - ShiftAmt1) {
6617 case 1 :
6618 case 8 :
6619 case 16 :
6620 case 32 :
6621 case 64 :
6622 case 128:
6623 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6624 break;
6625 default: break;
6626 }
6627 if (SExtType) {
6628 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6629 InsertNewInstBefore(NewTrunc, I);
6630 return new SExtInst(NewTrunc, Ty);
6631 }
6632 // Otherwise, we can't handle it yet.
6633 } else if (ShiftAmt1 < ShiftAmt2) {
6634 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6635
6636 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6637 if (I.getOpcode() == Instruction::Shl) {
6638 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6639 ShiftOp->getOpcode() == Instruction::AShr);
6640 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006641 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006642 InsertNewInstBefore(Shift, I);
6643
6644 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006645 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006646 }
6647
6648 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6649 if (I.getOpcode() == Instruction::LShr) {
6650 assert(ShiftOp->getOpcode() == Instruction::Shl);
6651 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006652 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006653 InsertNewInstBefore(Shift, I);
6654
6655 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006656 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006657 }
6658
6659 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6660 } else {
6661 assert(ShiftAmt2 < ShiftAmt1);
6662 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6663
6664 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6665 if (I.getOpcode() == Instruction::Shl) {
6666 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6667 ShiftOp->getOpcode() == Instruction::AShr);
6668 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006669 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006670 ConstantInt::get(Ty, ShiftDiff));
6671 InsertNewInstBefore(Shift, I);
6672
6673 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006674 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006675 }
6676
6677 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6678 if (I.getOpcode() == Instruction::LShr) {
6679 assert(ShiftOp->getOpcode() == Instruction::Shl);
6680 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006681 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006682 InsertNewInstBefore(Shift, I);
6683
6684 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006685 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006686 }
6687
6688 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6689 }
6690 }
6691 return 0;
6692}
6693
6694
6695/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6696/// expression. If so, decompose it, returning some value X, such that Val is
6697/// X*Scale+Offset.
6698///
6699static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6700 int &Offset) {
6701 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6702 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6703 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006704 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006705 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006706 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6707 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6708 if (I->getOpcode() == Instruction::Shl) {
6709 // This is a value scaled by '1 << the shift amt'.
6710 Scale = 1U << RHS->getZExtValue();
6711 Offset = 0;
6712 return I->getOperand(0);
6713 } else if (I->getOpcode() == Instruction::Mul) {
6714 // This value is scaled by 'RHS'.
6715 Scale = RHS->getZExtValue();
6716 Offset = 0;
6717 return I->getOperand(0);
6718 } else if (I->getOpcode() == Instruction::Add) {
6719 // We have X+C. Check to see if we really have (X*C2)+C1,
6720 // where C1 is divisible by C2.
6721 unsigned SubScale;
6722 Value *SubVal =
6723 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6724 Offset += RHS->getZExtValue();
6725 Scale = SubScale;
6726 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006727 }
6728 }
6729 }
6730
6731 // Otherwise, we can't look past this.
6732 Scale = 1;
6733 Offset = 0;
6734 return Val;
6735}
6736
6737
6738/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6739/// try to eliminate the cast by moving the type information into the alloc.
6740Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6741 AllocationInst &AI) {
6742 const PointerType *PTy = cast<PointerType>(CI.getType());
6743
6744 // Remove any uses of AI that are dead.
6745 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6746
6747 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6748 Instruction *User = cast<Instruction>(*UI++);
6749 if (isInstructionTriviallyDead(User)) {
6750 while (UI != E && *UI == User)
6751 ++UI; // If this instruction uses AI more than once, don't break UI.
6752
6753 ++NumDeadInst;
6754 DOUT << "IC: DCE: " << *User;
6755 EraseInstFromFunction(*User);
6756 }
6757 }
6758
6759 // Get the type really allocated and the type casted to.
6760 const Type *AllocElTy = AI.getAllocatedType();
6761 const Type *CastElTy = PTy->getElementType();
6762 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6763
6764 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6765 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6766 if (CastElTyAlign < AllocElTyAlign) return 0;
6767
6768 // If the allocation has multiple uses, only promote it if we are strictly
6769 // increasing the alignment of the resultant allocation. If we keep it the
6770 // same, we open the door to infinite loops of various kinds.
6771 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6772
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006773 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6774 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006775 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6776
6777 // See if we can satisfy the modulus by pulling a scale out of the array
6778 // size argument.
6779 unsigned ArraySizeScale;
6780 int ArrayOffset;
6781 Value *NumElements = // See if the array size is a decomposable linear expr.
6782 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6783
6784 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6785 // do the xform.
6786 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6787 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6788
6789 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6790 Value *Amt = 0;
6791 if (Scale == 1) {
6792 Amt = NumElements;
6793 } else {
6794 // If the allocation size is constant, form a constant mul expression
6795 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6796 if (isa<ConstantInt>(NumElements))
6797 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6798 // otherwise multiply the amount and the number of elements
6799 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006800 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006801 Amt = InsertNewInstBefore(Tmp, AI);
6802 }
6803 }
6804
6805 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6806 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00006807 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006808 Amt = InsertNewInstBefore(Tmp, AI);
6809 }
6810
6811 AllocationInst *New;
6812 if (isa<MallocInst>(AI))
6813 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6814 else
6815 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6816 InsertNewInstBefore(New, AI);
6817 New->takeName(&AI);
6818
6819 // If the allocation has multiple uses, insert a cast and change all things
6820 // that used it to use the new cast. This will also hack on CI, but it will
6821 // die soon.
6822 if (!AI.hasOneUse()) {
6823 AddUsesToWorkList(AI);
6824 // New is the allocation instruction, pointer typed. AI is the original
6825 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6826 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6827 InsertNewInstBefore(NewCast, AI);
6828 AI.replaceAllUsesWith(NewCast);
6829 }
6830 return ReplaceInstUsesWith(CI, New);
6831}
6832
6833/// CanEvaluateInDifferentType - Return true if we can take the specified value
6834/// and return it as type Ty without inserting any new casts and without
6835/// changing the computed value. This is used by code that tries to decide
6836/// whether promoting or shrinking integer operations to wider or smaller types
6837/// will allow us to eliminate a truncate or extend.
6838///
6839/// This is a truncation operation if Ty is smaller than V->getType(), or an
6840/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00006841bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6842 unsigned CastOpc,
6843 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006844 // We can always evaluate constants in another type.
6845 if (isa<ConstantInt>(V))
6846 return true;
6847
6848 Instruction *I = dyn_cast<Instruction>(V);
6849 if (!I) return false;
6850
6851 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6852
Chris Lattneref70bb82007-08-02 06:11:14 +00006853 // If this is an extension or truncate, we can often eliminate it.
6854 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6855 // If this is a cast from the destination type, we can trivially eliminate
6856 // it, and this will remove a cast overall.
6857 if (I->getOperand(0)->getType() == Ty) {
6858 // If the first operand is itself a cast, and is eliminable, do not count
6859 // this as an eliminable cast. We would prefer to eliminate those two
6860 // casts first.
6861 if (!isa<CastInst>(I->getOperand(0)))
6862 ++NumCastsRemoved;
6863 return true;
6864 }
6865 }
6866
6867 // We can't extend or shrink something that has multiple uses: doing so would
6868 // require duplicating the instruction in general, which isn't profitable.
6869 if (!I->hasOneUse()) return false;
6870
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006871 switch (I->getOpcode()) {
6872 case Instruction::Add:
6873 case Instruction::Sub:
6874 case Instruction::And:
6875 case Instruction::Or:
6876 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006877 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006878 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6879 NumCastsRemoved) &&
6880 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6881 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006882
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006883 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006884 // A multiply can be truncated by truncating its operands.
6885 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6886 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6887 NumCastsRemoved) &&
6888 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6889 NumCastsRemoved);
6890
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006891 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006892 // If we are truncating the result of this SHL, and if it's a shift of a
6893 // constant amount, we can always perform a SHL in a smaller type.
6894 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6895 uint32_t BitWidth = Ty->getBitWidth();
6896 if (BitWidth < OrigTy->getBitWidth() &&
6897 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006898 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6899 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006900 }
6901 break;
6902 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006903 // If this is a truncate of a logical shr, we can truncate it to a smaller
6904 // lshr iff we know that the bits we would otherwise be shifting in are
6905 // already zeros.
6906 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6907 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6908 uint32_t BitWidth = Ty->getBitWidth();
6909 if (BitWidth < OrigBitWidth &&
6910 MaskedValueIsZero(I->getOperand(0),
6911 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6912 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006913 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6914 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006915 }
6916 }
6917 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006918 case Instruction::ZExt:
6919 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006920 case Instruction::Trunc:
6921 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006922 // can safely replace it. Note that replacing it does not reduce the number
6923 // of casts in the input.
6924 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006925 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006926
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006927 break;
6928 default:
6929 // TODO: Can handle more cases here.
6930 break;
6931 }
6932
6933 return false;
6934}
6935
6936/// EvaluateInDifferentType - Given an expression that
6937/// CanEvaluateInDifferentType returns true for, actually insert the code to
6938/// evaluate the expression.
6939Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6940 bool isSigned) {
6941 if (Constant *C = dyn_cast<Constant>(V))
6942 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6943
6944 // Otherwise, it must be an instruction.
6945 Instruction *I = cast<Instruction>(V);
6946 Instruction *Res = 0;
6947 switch (I->getOpcode()) {
6948 case Instruction::Add:
6949 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006950 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006951 case Instruction::And:
6952 case Instruction::Or:
6953 case Instruction::Xor:
6954 case Instruction::AShr:
6955 case Instruction::LShr:
6956 case Instruction::Shl: {
6957 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6958 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00006959 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006960 LHS, RHS, I->getName());
6961 break;
6962 }
6963 case Instruction::Trunc:
6964 case Instruction::ZExt:
6965 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006966 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006967 // just return the source. There's no need to insert it because it is not
6968 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006969 if (I->getOperand(0)->getType() == Ty)
6970 return I->getOperand(0);
6971
Chris Lattneref70bb82007-08-02 06:11:14 +00006972 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00006973 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattneref70bb82007-08-02 06:11:14 +00006974 Ty, I->getName());
6975 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006976 default:
6977 // TODO: Can handle more cases here.
6978 assert(0 && "Unreachable!");
6979 break;
6980 }
6981
6982 return InsertNewInstBefore(Res, *I);
6983}
6984
6985/// @brief Implement the transforms common to all CastInst visitors.
6986Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6987 Value *Src = CI.getOperand(0);
6988
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006989 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6990 // eliminate it now.
6991 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6992 if (Instruction::CastOps opc =
6993 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6994 // The first cast (CSrc) is eliminable so we need to fix up or replace
6995 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00006996 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006997 }
6998 }
6999
7000 // If we are casting a select then fold the cast into the select
7001 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7002 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7003 return NV;
7004
7005 // If we are casting a PHI then fold the cast into the PHI
7006 if (isa<PHINode>(Src))
7007 if (Instruction *NV = FoldOpIntoPhi(CI))
7008 return NV;
7009
7010 return 0;
7011}
7012
7013/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7014Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7015 Value *Src = CI.getOperand(0);
7016
7017 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7018 // If casting the result of a getelementptr instruction with no offset, turn
7019 // this into a cast of the original pointer!
7020 if (GEP->hasAllZeroIndices()) {
7021 // Changing the cast operand is usually not a good idea but it is safe
7022 // here because the pointer operand is being replaced with another
7023 // pointer operand so the opcode doesn't need to change.
7024 AddToWorkList(GEP);
7025 CI.setOperand(0, GEP->getOperand(0));
7026 return &CI;
7027 }
7028
7029 // If the GEP has a single use, and the base pointer is a bitcast, and the
7030 // GEP computes a constant offset, see if we can convert these three
7031 // instructions into fewer. This typically happens with unions and other
7032 // non-type-safe code.
7033 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7034 if (GEP->hasAllConstantIndices()) {
7035 // We are guaranteed to get a constant from EmitGEPOffset.
7036 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7037 int64_t Offset = OffsetV->getSExtValue();
7038
7039 // Get the base pointer input of the bitcast, and the type it points to.
7040 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7041 const Type *GEPIdxTy =
7042 cast<PointerType>(OrigBase->getType())->getElementType();
7043 if (GEPIdxTy->isSized()) {
7044 SmallVector<Value*, 8> NewIndices;
7045
7046 // Start with the index over the outer type. Note that the type size
7047 // might be zero (even if the offset isn't zero) if the indexed type
7048 // is something like [0 x {int, int}]
7049 const Type *IntPtrTy = TD->getIntPtrType();
7050 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007051 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007052 FirstIdx = Offset/TySize;
7053 Offset %= TySize;
7054
7055 // Handle silly modulus not returning values values [0..TySize).
7056 if (Offset < 0) {
7057 --FirstIdx;
7058 Offset += TySize;
7059 assert(Offset >= 0);
7060 }
7061 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7062 }
7063
7064 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7065
7066 // Index into the types. If we fail, set OrigBase to null.
7067 while (Offset) {
7068 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7069 const StructLayout *SL = TD->getStructLayout(STy);
7070 if (Offset < (int64_t)SL->getSizeInBytes()) {
7071 unsigned Elt = SL->getElementContainingOffset(Offset);
7072 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7073
7074 Offset -= SL->getElementOffset(Elt);
7075 GEPIdxTy = STy->getElementType(Elt);
7076 } else {
7077 // Otherwise, we can't index into this, bail out.
7078 Offset = 0;
7079 OrigBase = 0;
7080 }
7081 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7082 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007083 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007084 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7085 Offset %= EltSize;
7086 } else {
7087 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7088 }
7089 GEPIdxTy = STy->getElementType();
7090 } else {
7091 // Otherwise, we can't index into this, bail out.
7092 Offset = 0;
7093 OrigBase = 0;
7094 }
7095 }
7096 if (OrigBase) {
7097 // If we were able to index down into an element, create the GEP
7098 // and bitcast the result. This eliminates one bitcast, potentially
7099 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007100 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7101 NewIndices.begin(),
7102 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007103 InsertNewInstBefore(NGEP, CI);
7104 NGEP->takeName(GEP);
7105
7106 if (isa<BitCastInst>(CI))
7107 return new BitCastInst(NGEP, CI.getType());
7108 assert(isa<PtrToIntInst>(CI));
7109 return new PtrToIntInst(NGEP, CI.getType());
7110 }
7111 }
7112 }
7113 }
7114 }
7115
7116 return commonCastTransforms(CI);
7117}
7118
7119
7120
7121/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7122/// integer types. This function implements the common transforms for all those
7123/// cases.
7124/// @brief Implement the transforms common to CastInst with integer operands
7125Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7126 if (Instruction *Result = commonCastTransforms(CI))
7127 return Result;
7128
7129 Value *Src = CI.getOperand(0);
7130 const Type *SrcTy = Src->getType();
7131 const Type *DestTy = CI.getType();
7132 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7133 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7134
7135 // See if we can simplify any instructions used by the LHS whose sole
7136 // purpose is to compute bits we don't care about.
7137 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7138 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7139 KnownZero, KnownOne))
7140 return &CI;
7141
7142 // If the source isn't an instruction or has more than one use then we
7143 // can't do anything more.
7144 Instruction *SrcI = dyn_cast<Instruction>(Src);
7145 if (!SrcI || !Src->hasOneUse())
7146 return 0;
7147
7148 // Attempt to propagate the cast into the instruction for int->int casts.
7149 int NumCastsRemoved = 0;
7150 if (!isa<BitCastInst>(CI) &&
7151 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007152 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007153 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007154 // eliminates the cast, so it is always a win. If this is a zero-extension,
7155 // we need to do an AND to maintain the clear top-part of the computation,
7156 // so we require that the input have eliminated at least one cast. If this
7157 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007158 // require that two casts have been eliminated.
7159 bool DoXForm;
7160 switch (CI.getOpcode()) {
7161 default:
7162 // All the others use floating point so we shouldn't actually
7163 // get here because of the check above.
7164 assert(0 && "Unknown cast type");
7165 case Instruction::Trunc:
7166 DoXForm = true;
7167 break;
7168 case Instruction::ZExt:
7169 DoXForm = NumCastsRemoved >= 1;
7170 break;
7171 case Instruction::SExt:
7172 DoXForm = NumCastsRemoved >= 2;
7173 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007174 }
7175
7176 if (DoXForm) {
7177 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7178 CI.getOpcode() == Instruction::SExt);
7179 assert(Res->getType() == DestTy);
7180 switch (CI.getOpcode()) {
7181 default: assert(0 && "Unknown cast type!");
7182 case Instruction::Trunc:
7183 case Instruction::BitCast:
7184 // Just replace this cast with the result.
7185 return ReplaceInstUsesWith(CI, Res);
7186 case Instruction::ZExt: {
7187 // We need to emit an AND to clear the high bits.
7188 assert(SrcBitSize < DestBitSize && "Not a zext?");
7189 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7190 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007191 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007192 }
7193 case Instruction::SExt:
7194 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007195 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007196 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7197 CI), DestTy);
7198 }
7199 }
7200 }
7201
7202 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7203 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7204
7205 switch (SrcI->getOpcode()) {
7206 case Instruction::Add:
7207 case Instruction::Mul:
7208 case Instruction::And:
7209 case Instruction::Or:
7210 case Instruction::Xor:
7211 // If we are discarding information, rewrite.
7212 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7213 // Don't insert two casts if they cannot be eliminated. We allow
7214 // two casts to be inserted if the sizes are the same. This could
7215 // only be converting signedness, which is a noop.
7216 if (DestBitSize == SrcBitSize ||
7217 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7218 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7219 Instruction::CastOps opcode = CI.getOpcode();
7220 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7221 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007222 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007223 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7224 }
7225 }
7226
7227 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7228 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7229 SrcI->getOpcode() == Instruction::Xor &&
7230 Op1 == ConstantInt::getTrue() &&
7231 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7232 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007233 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007234 }
7235 break;
7236 case Instruction::SDiv:
7237 case Instruction::UDiv:
7238 case Instruction::SRem:
7239 case Instruction::URem:
7240 // If we are just changing the sign, rewrite.
7241 if (DestBitSize == SrcBitSize) {
7242 // Don't insert two casts if they cannot be eliminated. We allow
7243 // two casts to be inserted if the sizes are the same. This could
7244 // only be converting signedness, which is a noop.
7245 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7246 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7247 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7248 Op0, DestTy, SrcI);
7249 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7250 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007251 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007252 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7253 }
7254 }
7255 break;
7256
7257 case Instruction::Shl:
7258 // Allow changing the sign of the source operand. Do not allow
7259 // changing the size of the shift, UNLESS the shift amount is a
7260 // constant. We must not change variable sized shifts to a smaller
7261 // size, because it is undefined to shift more bits out than exist
7262 // in the value.
7263 if (DestBitSize == SrcBitSize ||
7264 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7265 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7266 Instruction::BitCast : Instruction::Trunc);
7267 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7268 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007269 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007270 }
7271 break;
7272 case Instruction::AShr:
7273 // If this is a signed shr, and if all bits shifted in are about to be
7274 // truncated off, turn it into an unsigned shr to allow greater
7275 // simplifications.
7276 if (DestBitSize < SrcBitSize &&
7277 isa<ConstantInt>(Op1)) {
7278 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7279 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7280 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007281 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007282 }
7283 }
7284 break;
7285 }
7286 return 0;
7287}
7288
7289Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7290 if (Instruction *Result = commonIntCastTransforms(CI))
7291 return Result;
7292
7293 Value *Src = CI.getOperand(0);
7294 const Type *Ty = CI.getType();
7295 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7296 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7297
7298 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7299 switch (SrcI->getOpcode()) {
7300 default: break;
7301 case Instruction::LShr:
7302 // We can shrink lshr to something smaller if we know the bits shifted in
7303 // are already zeros.
7304 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7305 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7306
7307 // Get a mask for the bits shifting in.
7308 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7309 Value* SrcIOp0 = SrcI->getOperand(0);
7310 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7311 if (ShAmt >= DestBitWidth) // All zeros.
7312 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7313
7314 // Okay, we can shrink this. Truncate the input, then return a new
7315 // shift.
7316 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7317 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7318 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007319 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007320 }
7321 } else { // This is a variable shr.
7322
7323 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7324 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7325 // loop-invariant and CSE'd.
7326 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7327 Value *One = ConstantInt::get(SrcI->getType(), 1);
7328
7329 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007330 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007331 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007332 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007333 SrcI->getOperand(0),
7334 "tmp"), CI);
7335 Value *Zero = Constant::getNullValue(V->getType());
7336 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7337 }
7338 }
7339 break;
7340 }
7341 }
7342
7343 return 0;
7344}
7345
Evan Chenge3779cf2008-03-24 00:21:34 +00007346/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7347/// in order to eliminate the icmp.
7348Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7349 bool DoXform) {
7350 // If we are just checking for a icmp eq of a single bit and zext'ing it
7351 // to an integer, then shift the bit to the appropriate place and then
7352 // cast to integer to avoid the comparison.
7353 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7354 const APInt &Op1CV = Op1C->getValue();
7355
7356 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7357 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7358 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7359 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7360 if (!DoXform) return ICI;
7361
7362 Value *In = ICI->getOperand(0);
7363 Value *Sh = ConstantInt::get(In->getType(),
7364 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007365 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007366 In->getName()+".lobit"),
7367 CI);
7368 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007369 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007370 false/*ZExt*/, "tmp", &CI);
7371
7372 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7373 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007374 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007375 In->getName()+".not"),
7376 CI);
7377 }
7378
7379 return ReplaceInstUsesWith(CI, In);
7380 }
7381
7382
7383
7384 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7385 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7386 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7387 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7388 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7389 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7390 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7391 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7392 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7393 // This only works for EQ and NE
7394 ICI->isEquality()) {
7395 // If Op1C some other power of two, convert:
7396 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7397 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7398 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7399 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7400
7401 APInt KnownZeroMask(~KnownZero);
7402 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7403 if (!DoXform) return ICI;
7404
7405 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7406 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7407 // (X&4) == 2 --> false
7408 // (X&4) != 2 --> true
7409 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7410 Res = ConstantExpr::getZExt(Res, CI.getType());
7411 return ReplaceInstUsesWith(CI, Res);
7412 }
7413
7414 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7415 Value *In = ICI->getOperand(0);
7416 if (ShiftAmt) {
7417 // Perform a logical shr by shiftamt.
7418 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007419 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007420 ConstantInt::get(In->getType(), ShiftAmt),
7421 In->getName()+".lobit"), CI);
7422 }
7423
7424 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7425 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007426 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007427 InsertNewInstBefore(cast<Instruction>(In), CI);
7428 }
7429
7430 if (CI.getType() == In->getType())
7431 return ReplaceInstUsesWith(CI, In);
7432 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007433 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007434 }
7435 }
7436 }
7437
7438 return 0;
7439}
7440
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007441Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7442 // If one of the common conversion will work ..
7443 if (Instruction *Result = commonIntCastTransforms(CI))
7444 return Result;
7445
7446 Value *Src = CI.getOperand(0);
7447
7448 // If this is a cast of a cast
7449 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7450 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7451 // types and if the sizes are just right we can convert this into a logical
7452 // 'and' which will be much cheaper than the pair of casts.
7453 if (isa<TruncInst>(CSrc)) {
7454 // Get the sizes of the types involved
7455 Value *A = CSrc->getOperand(0);
7456 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7457 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7458 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7459 // If we're actually extending zero bits and the trunc is a no-op
7460 if (MidSize < DstSize && SrcSize == DstSize) {
7461 // Replace both of the casts with an And of the type mask.
7462 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7463 Constant *AndConst = ConstantInt::get(AndValue);
7464 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007465 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007466 // Unfortunately, if the type changed, we need to cast it back.
7467 if (And->getType() != CI.getType()) {
7468 And->setName(CSrc->getName()+".mask");
7469 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007470 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007471 }
7472 return And;
7473 }
7474 }
7475 }
7476
Evan Chenge3779cf2008-03-24 00:21:34 +00007477 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7478 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007479
Evan Chenge3779cf2008-03-24 00:21:34 +00007480 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7481 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7482 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7483 // of the (zext icmp) will be transformed.
7484 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7485 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7486 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7487 (transformZExtICmp(LHS, CI, false) ||
7488 transformZExtICmp(RHS, CI, false))) {
7489 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7490 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007491 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007492 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007493 }
7494
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007495 return 0;
7496}
7497
7498Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7499 if (Instruction *I = commonIntCastTransforms(CI))
7500 return I;
7501
7502 Value *Src = CI.getOperand(0);
7503
7504 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7505 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7506 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7507 // If we are just checking for a icmp eq of a single bit and zext'ing it
7508 // to an integer, then shift the bit to the appropriate place and then
7509 // cast to integer to avoid the comparison.
7510 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7511 const APInt &Op1CV = Op1C->getValue();
7512
7513 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7514 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7515 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7516 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7517 Value *In = ICI->getOperand(0);
7518 Value *Sh = ConstantInt::get(In->getType(),
7519 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007520 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007521 In->getName()+".lobit"),
7522 CI);
7523 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007524 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007525 true/*SExt*/, "tmp", &CI);
7526
7527 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007528 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007529 In->getName()+".not"), CI);
7530
7531 return ReplaceInstUsesWith(CI, In);
7532 }
7533 }
7534 }
Dan Gohmanf0f12022008-05-20 21:01:12 +00007535
7536 // See if the value being truncated is already sign extended. If so, just
7537 // eliminate the trunc/sext pair.
7538 if (getOpcode(Src) == Instruction::Trunc) {
7539 Value *Op = cast<User>(Src)->getOperand(0);
7540 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7541 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7542 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7543 unsigned NumSignBits = ComputeNumSignBits(Op);
7544
7545 if (OpBits == DestBits) {
7546 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7547 // bits, it is already ready.
7548 if (NumSignBits > DestBits-MidBits)
7549 return ReplaceInstUsesWith(CI, Op);
7550 } else if (OpBits < DestBits) {
7551 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7552 // bits, just sext from i32.
7553 if (NumSignBits > OpBits-MidBits)
7554 return new SExtInst(Op, CI.getType(), "tmp");
7555 } else {
7556 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7557 // bits, just truncate to i32.
7558 if (NumSignBits > OpBits-MidBits)
7559 return new TruncInst(Op, CI.getType(), "tmp");
7560 }
7561 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007562
7563 return 0;
7564}
7565
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007566/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7567/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007568static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007569 APFloat F = CFP->getValueAPF();
7570 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007571 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007572 return 0;
7573}
7574
7575/// LookThroughFPExtensions - If this is an fp extension instruction, look
7576/// through it until we get the source value.
7577static Value *LookThroughFPExtensions(Value *V) {
7578 if (Instruction *I = dyn_cast<Instruction>(V))
7579 if (I->getOpcode() == Instruction::FPExt)
7580 return LookThroughFPExtensions(I->getOperand(0));
7581
7582 // If this value is a constant, return the constant in the smallest FP type
7583 // that can accurately represent it. This allows us to turn
7584 // (float)((double)X+2.0) into x+2.0f.
7585 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7586 if (CFP->getType() == Type::PPC_FP128Ty)
7587 return V; // No constant folding of this.
7588 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007589 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007590 return V;
7591 if (CFP->getType() == Type::DoubleTy)
7592 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007593 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007594 return V;
7595 // Don't try to shrink to various long double types.
7596 }
7597
7598 return V;
7599}
7600
7601Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7602 if (Instruction *I = commonCastTransforms(CI))
7603 return I;
7604
7605 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7606 // smaller than the destination type, we can eliminate the truncate by doing
7607 // the add as the smaller type. This applies to add/sub/mul/div as well as
7608 // many builtins (sqrt, etc).
7609 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7610 if (OpI && OpI->hasOneUse()) {
7611 switch (OpI->getOpcode()) {
7612 default: break;
7613 case Instruction::Add:
7614 case Instruction::Sub:
7615 case Instruction::Mul:
7616 case Instruction::FDiv:
7617 case Instruction::FRem:
7618 const Type *SrcTy = OpI->getType();
7619 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7620 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7621 if (LHSTrunc->getType() != SrcTy &&
7622 RHSTrunc->getType() != SrcTy) {
7623 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7624 // If the source types were both smaller than the destination type of
7625 // the cast, do this xform.
7626 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7627 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7628 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7629 CI.getType(), CI);
7630 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7631 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007632 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007633 }
7634 }
7635 break;
7636 }
7637 }
7638 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007639}
7640
7641Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7642 return commonCastTransforms(CI);
7643}
7644
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007645Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7646 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7647 // mantissa to accurately represent all values of X. For example, do not
7648 // do this with i64->float->i64.
7649 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7650 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7651 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner9ce836b2008-05-19 21:17:23 +00007652 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007653 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7654
7655 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007656}
7657
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007658Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7659 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7660 // mantissa to accurately represent all values of X. For example, do not
7661 // do this with i64->float->i64.
7662 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7663 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7664 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner9ce836b2008-05-19 21:17:23 +00007665 SrcI->getType()->getFPMantissaWidth())
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007666 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7667
7668 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007669}
7670
7671Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7672 return commonCastTransforms(CI);
7673}
7674
7675Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7676 return commonCastTransforms(CI);
7677}
7678
7679Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7680 return commonPointerCastTransforms(CI);
7681}
7682
Chris Lattner7c1626482008-01-08 07:23:51 +00007683Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7684 if (Instruction *I = commonCastTransforms(CI))
7685 return I;
7686
7687 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7688 if (!DestPointee->isSized()) return 0;
7689
7690 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7691 ConstantInt *Cst;
7692 Value *X;
7693 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7694 m_ConstantInt(Cst)))) {
7695 // If the source and destination operands have the same type, see if this
7696 // is a single-index GEP.
7697 if (X->getType() == CI.getType()) {
7698 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007699 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007700
7701 // Convert the constant to intptr type.
7702 APInt Offset = Cst->getValue();
7703 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7704
7705 // If Offset is evenly divisible by Size, we can do this xform.
7706 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7707 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00007708 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00007709 }
7710 }
7711 // TODO: Could handle other cases, e.g. where add is indexing into field of
7712 // struct etc.
7713 } else if (CI.getOperand(0)->hasOneUse() &&
7714 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7715 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7716 // "inttoptr+GEP" instead of "add+intptr".
7717
7718 // Get the size of the pointee type.
7719 uint64_t Size = TD->getABITypeSize(DestPointee);
7720
7721 // Convert the constant to intptr type.
7722 APInt Offset = Cst->getValue();
7723 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7724
7725 // If Offset is evenly divisible by Size, we can do this xform.
7726 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7727 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7728
7729 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7730 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007731 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00007732 }
7733 }
7734 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007735}
7736
7737Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7738 // If the operands are integer typed then apply the integer transforms,
7739 // otherwise just apply the common ones.
7740 Value *Src = CI.getOperand(0);
7741 const Type *SrcTy = Src->getType();
7742 const Type *DestTy = CI.getType();
7743
7744 if (SrcTy->isInteger() && DestTy->isInteger()) {
7745 if (Instruction *Result = commonIntCastTransforms(CI))
7746 return Result;
7747 } else if (isa<PointerType>(SrcTy)) {
7748 if (Instruction *I = commonPointerCastTransforms(CI))
7749 return I;
7750 } else {
7751 if (Instruction *Result = commonCastTransforms(CI))
7752 return Result;
7753 }
7754
7755
7756 // Get rid of casts from one type to the same type. These are useless and can
7757 // be replaced by the operand.
7758 if (DestTy == Src->getType())
7759 return ReplaceInstUsesWith(CI, Src);
7760
7761 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7762 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7763 const Type *DstElTy = DstPTy->getElementType();
7764 const Type *SrcElTy = SrcPTy->getElementType();
7765
Nate Begemandf5b3612008-03-31 00:22:16 +00007766 // If the address spaces don't match, don't eliminate the bitcast, which is
7767 // required for changing types.
7768 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7769 return 0;
7770
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007771 // If we are casting a malloc or alloca to a pointer to a type of the same
7772 // size, rewrite the allocation instruction to allocate the "right" type.
7773 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7774 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7775 return V;
7776
7777 // If the source and destination are pointers, and this cast is equivalent
7778 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7779 // This can enhance SROA and other transforms that want type-safe pointers.
7780 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7781 unsigned NumZeros = 0;
7782 while (SrcElTy != DstElTy &&
7783 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7784 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7785 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7786 ++NumZeros;
7787 }
7788
7789 // If we found a path from the src to dest, create the getelementptr now.
7790 if (SrcElTy == DstElTy) {
7791 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007792 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7793 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007794 }
7795 }
7796
7797 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7798 if (SVI->hasOneUse()) {
7799 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7800 // a bitconvert to a vector with the same # elts.
7801 if (isa<VectorType>(DestTy) &&
7802 cast<VectorType>(DestTy)->getNumElements() ==
7803 SVI->getType()->getNumElements()) {
7804 CastInst *Tmp;
7805 // If either of the operands is a cast from CI.getType(), then
7806 // evaluating the shuffle in the casted destination's type will allow
7807 // us to eliminate at least one cast.
7808 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7809 Tmp->getOperand(0)->getType() == DestTy) ||
7810 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7811 Tmp->getOperand(0)->getType() == DestTy)) {
7812 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7813 SVI->getOperand(0), DestTy, &CI);
7814 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7815 SVI->getOperand(1), DestTy, &CI);
7816 // Return a new shuffle vector. Use the same element ID's, as we
7817 // know the vector types match #elts.
7818 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7819 }
7820 }
7821 }
7822 }
7823 return 0;
7824}
7825
7826/// GetSelectFoldableOperands - We want to turn code that looks like this:
7827/// %C = or %A, %B
7828/// %D = select %cond, %C, %A
7829/// into:
7830/// %C = select %cond, %B, 0
7831/// %D = or %A, %C
7832///
7833/// Assuming that the specified instruction is an operand to the select, return
7834/// a bitmask indicating which operands of this instruction are foldable if they
7835/// equal the other incoming value of the select.
7836///
7837static unsigned GetSelectFoldableOperands(Instruction *I) {
7838 switch (I->getOpcode()) {
7839 case Instruction::Add:
7840 case Instruction::Mul:
7841 case Instruction::And:
7842 case Instruction::Or:
7843 case Instruction::Xor:
7844 return 3; // Can fold through either operand.
7845 case Instruction::Sub: // Can only fold on the amount subtracted.
7846 case Instruction::Shl: // Can only fold on the shift amount.
7847 case Instruction::LShr:
7848 case Instruction::AShr:
7849 return 1;
7850 default:
7851 return 0; // Cannot fold
7852 }
7853}
7854
7855/// GetSelectFoldableConstant - For the same transformation as the previous
7856/// function, return the identity constant that goes into the select.
7857static Constant *GetSelectFoldableConstant(Instruction *I) {
7858 switch (I->getOpcode()) {
7859 default: assert(0 && "This cannot happen!"); abort();
7860 case Instruction::Add:
7861 case Instruction::Sub:
7862 case Instruction::Or:
7863 case Instruction::Xor:
7864 case Instruction::Shl:
7865 case Instruction::LShr:
7866 case Instruction::AShr:
7867 return Constant::getNullValue(I->getType());
7868 case Instruction::And:
7869 return Constant::getAllOnesValue(I->getType());
7870 case Instruction::Mul:
7871 return ConstantInt::get(I->getType(), 1);
7872 }
7873}
7874
7875/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7876/// have the same opcode and only one use each. Try to simplify this.
7877Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7878 Instruction *FI) {
7879 if (TI->getNumOperands() == 1) {
7880 // If this is a non-volatile load or a cast from the same type,
7881 // merge.
7882 if (TI->isCast()) {
7883 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7884 return 0;
7885 } else {
7886 return 0; // unknown unary op.
7887 }
7888
7889 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007890 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7891 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007892 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007893 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007894 TI->getType());
7895 }
7896
7897 // Only handle binary operators here.
7898 if (!isa<BinaryOperator>(TI))
7899 return 0;
7900
7901 // Figure out if the operations have any operands in common.
7902 Value *MatchOp, *OtherOpT, *OtherOpF;
7903 bool MatchIsOpZero;
7904 if (TI->getOperand(0) == FI->getOperand(0)) {
7905 MatchOp = TI->getOperand(0);
7906 OtherOpT = TI->getOperand(1);
7907 OtherOpF = FI->getOperand(1);
7908 MatchIsOpZero = true;
7909 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7910 MatchOp = TI->getOperand(1);
7911 OtherOpT = TI->getOperand(0);
7912 OtherOpF = FI->getOperand(0);
7913 MatchIsOpZero = false;
7914 } else if (!TI->isCommutative()) {
7915 return 0;
7916 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7917 MatchOp = TI->getOperand(0);
7918 OtherOpT = TI->getOperand(1);
7919 OtherOpF = FI->getOperand(0);
7920 MatchIsOpZero = true;
7921 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7922 MatchOp = TI->getOperand(1);
7923 OtherOpT = TI->getOperand(0);
7924 OtherOpF = FI->getOperand(1);
7925 MatchIsOpZero = true;
7926 } else {
7927 return 0;
7928 }
7929
7930 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007931 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7932 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007933 InsertNewInstBefore(NewSI, SI);
7934
7935 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7936 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00007937 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007938 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007939 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007940 }
7941 assert(0 && "Shouldn't get here");
7942 return 0;
7943}
7944
7945Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7946 Value *CondVal = SI.getCondition();
7947 Value *TrueVal = SI.getTrueValue();
7948 Value *FalseVal = SI.getFalseValue();
7949
7950 // select true, X, Y -> X
7951 // select false, X, Y -> Y
7952 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7953 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7954
7955 // select C, X, X -> X
7956 if (TrueVal == FalseVal)
7957 return ReplaceInstUsesWith(SI, TrueVal);
7958
7959 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7960 return ReplaceInstUsesWith(SI, FalseVal);
7961 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7962 return ReplaceInstUsesWith(SI, TrueVal);
7963 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7964 if (isa<Constant>(TrueVal))
7965 return ReplaceInstUsesWith(SI, TrueVal);
7966 else
7967 return ReplaceInstUsesWith(SI, FalseVal);
7968 }
7969
7970 if (SI.getType() == Type::Int1Ty) {
7971 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7972 if (C->getZExtValue()) {
7973 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00007974 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007975 } else {
7976 // Change: A = select B, false, C --> A = and !B, C
7977 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00007978 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007979 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007980 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007981 }
7982 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7983 if (C->getZExtValue() == false) {
7984 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00007985 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007986 } else {
7987 // Change: A = select B, C, true --> A = or !B, C
7988 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00007989 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007990 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007991 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992 }
7993 }
Chris Lattner53f85a72007-11-25 21:27:53 +00007994
7995 // select a, b, a -> a&b
7996 // select a, a, b -> a|b
7997 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00007998 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00007999 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008000 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008001 }
8002
8003 // Selecting between two integer constants?
8004 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8005 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8006 // select C, 1, 0 -> zext C to int
8007 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008008 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008009 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8010 // select C, 0, 1 -> zext !C to int
8011 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008012 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008013 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008014 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008015 }
8016
8017 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8018
8019 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8020
8021 // (x <s 0) ? -1 : 0 -> ashr x, 31
8022 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8023 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8024 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8025 // The comparison constant and the result are not neccessarily the
8026 // same width. Make an all-ones value by inserting a AShr.
8027 Value *X = IC->getOperand(0);
8028 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8029 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008030 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008031 ShAmt, "ones");
8032 InsertNewInstBefore(SRA, SI);
8033
8034 // Finally, convert to the type of the select RHS. We figure out
8035 // if this requires a SExt, Trunc or BitCast based on the sizes.
8036 Instruction::CastOps opc = Instruction::BitCast;
8037 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8038 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8039 if (SRASize < SISize)
8040 opc = Instruction::SExt;
8041 else if (SRASize > SISize)
8042 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008043 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008044 }
8045 }
8046
8047
8048 // If one of the constants is zero (we know they can't both be) and we
8049 // have an icmp instruction with zero, and we have an 'and' with the
8050 // non-constant value, eliminate this whole mess. This corresponds to
8051 // cases like this: ((X & 27) ? 27 : 0)
8052 if (TrueValC->isZero() || FalseValC->isZero())
8053 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8054 cast<Constant>(IC->getOperand(1))->isNullValue())
8055 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8056 if (ICA->getOpcode() == Instruction::And &&
8057 isa<ConstantInt>(ICA->getOperand(1)) &&
8058 (ICA->getOperand(1) == TrueValC ||
8059 ICA->getOperand(1) == FalseValC) &&
8060 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8061 // Okay, now we know that everything is set up, we just don't
8062 // know whether we have a icmp_ne or icmp_eq and whether the
8063 // true or false val is the zero.
8064 bool ShouldNotVal = !TrueValC->isZero();
8065 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8066 Value *V = ICA;
8067 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008068 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008069 Instruction::Xor, V, ICA->getOperand(1)), SI);
8070 return ReplaceInstUsesWith(SI, V);
8071 }
8072 }
8073 }
8074
8075 // See if we are selecting two values based on a comparison of the two values.
8076 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8077 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8078 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008079 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8080 // This is not safe in general for floating point:
8081 // consider X== -0, Y== +0.
8082 // It becomes safe if either operand is a nonzero constant.
8083 ConstantFP *CFPt, *CFPf;
8084 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8085 !CFPt->getValueAPF().isZero()) ||
8086 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8087 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008088 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008089 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008090 // Transform (X != Y) ? X : Y -> X
8091 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8092 return ReplaceInstUsesWith(SI, TrueVal);
8093 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8094
8095 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8096 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008097 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8098 // This is not safe in general for floating point:
8099 // consider X== -0, Y== +0.
8100 // It becomes safe if either operand is a nonzero constant.
8101 ConstantFP *CFPt, *CFPf;
8102 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8103 !CFPt->getValueAPF().isZero()) ||
8104 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8105 !CFPf->getValueAPF().isZero()))
8106 return ReplaceInstUsesWith(SI, FalseVal);
8107 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008108 // Transform (X != Y) ? Y : X -> Y
8109 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8110 return ReplaceInstUsesWith(SI, TrueVal);
8111 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8112 }
8113 }
8114
8115 // See if we are selecting two values based on a comparison of the two values.
8116 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8117 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8118 // Transform (X == Y) ? X : Y -> Y
8119 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8120 return ReplaceInstUsesWith(SI, FalseVal);
8121 // Transform (X != Y) ? X : Y -> X
8122 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8123 return ReplaceInstUsesWith(SI, TrueVal);
8124 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8125
8126 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8127 // Transform (X == Y) ? Y : X -> X
8128 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8129 return ReplaceInstUsesWith(SI, FalseVal);
8130 // Transform (X != Y) ? Y : X -> Y
8131 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8132 return ReplaceInstUsesWith(SI, TrueVal);
8133 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8134 }
8135 }
8136
8137 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8138 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8139 if (TI->hasOneUse() && FI->hasOneUse()) {
8140 Instruction *AddOp = 0, *SubOp = 0;
8141
8142 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8143 if (TI->getOpcode() == FI->getOpcode())
8144 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8145 return IV;
8146
8147 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8148 // even legal for FP.
8149 if (TI->getOpcode() == Instruction::Sub &&
8150 FI->getOpcode() == Instruction::Add) {
8151 AddOp = FI; SubOp = TI;
8152 } else if (FI->getOpcode() == Instruction::Sub &&
8153 TI->getOpcode() == Instruction::Add) {
8154 AddOp = TI; SubOp = FI;
8155 }
8156
8157 if (AddOp) {
8158 Value *OtherAddOp = 0;
8159 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8160 OtherAddOp = AddOp->getOperand(1);
8161 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8162 OtherAddOp = AddOp->getOperand(0);
8163 }
8164
8165 if (OtherAddOp) {
8166 // So at this point we know we have (Y -> OtherAddOp):
8167 // select C, (add X, Y), (sub X, Z)
8168 Value *NegVal; // Compute -Z
8169 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8170 NegVal = ConstantExpr::getNeg(C);
8171 } else {
8172 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008173 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008174 }
8175
8176 Value *NewTrueOp = OtherAddOp;
8177 Value *NewFalseOp = NegVal;
8178 if (AddOp != TI)
8179 std::swap(NewTrueOp, NewFalseOp);
8180 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008181 SelectInst::Create(CondVal, NewTrueOp,
8182 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008183
8184 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008185 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008186 }
8187 }
8188 }
8189
8190 // See if we can fold the select into one of our operands.
8191 if (SI.getType()->isInteger()) {
8192 // See the comment above GetSelectFoldableOperands for a description of the
8193 // transformation we are doing here.
8194 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8195 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8196 !isa<Constant>(FalseVal))
8197 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8198 unsigned OpToFold = 0;
8199 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8200 OpToFold = 1;
8201 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8202 OpToFold = 2;
8203 }
8204
8205 if (OpToFold) {
8206 Constant *C = GetSelectFoldableConstant(TVI);
8207 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008208 SelectInst::Create(SI.getCondition(),
8209 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008210 InsertNewInstBefore(NewSel, SI);
8211 NewSel->takeName(TVI);
8212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008213 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008214 else {
8215 assert(0 && "Unknown instruction!!");
8216 }
8217 }
8218 }
8219
8220 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8221 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8222 !isa<Constant>(TrueVal))
8223 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8224 unsigned OpToFold = 0;
8225 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8226 OpToFold = 1;
8227 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8228 OpToFold = 2;
8229 }
8230
8231 if (OpToFold) {
8232 Constant *C = GetSelectFoldableConstant(FVI);
8233 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008234 SelectInst::Create(SI.getCondition(), C,
8235 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008236 InsertNewInstBefore(NewSel, SI);
8237 NewSel->takeName(FVI);
8238 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008239 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008240 else
8241 assert(0 && "Unknown instruction!!");
8242 }
8243 }
8244 }
8245
8246 if (BinaryOperator::isNot(CondVal)) {
8247 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8248 SI.setOperand(1, FalseVal);
8249 SI.setOperand(2, TrueVal);
8250 return &SI;
8251 }
8252
8253 return 0;
8254}
8255
Dan Gohman2d648bb2008-04-10 18:43:06 +00008256/// EnforceKnownAlignment - If the specified pointer points to an object that
8257/// we control, modify the object's alignment to PrefAlign. This isn't
8258/// often possible though. If alignment is important, a more reliable approach
8259/// is to simply align all global variables and allocation instructions to
8260/// their preferred alignment from the beginning.
8261///
8262static unsigned EnforceKnownAlignment(Value *V,
8263 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008264
Dan Gohman2d648bb2008-04-10 18:43:06 +00008265 User *U = dyn_cast<User>(V);
8266 if (!U) return Align;
8267
8268 switch (getOpcode(U)) {
8269 default: break;
8270 case Instruction::BitCast:
8271 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8272 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008273 // If all indexes are zero, it is just the alignment of the base pointer.
8274 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00008275 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00008276 if (!isa<Constant>(*i) ||
8277 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008278 AllZeroOperands = false;
8279 break;
8280 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008281
8282 if (AllZeroOperands) {
8283 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008284 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008285 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008286 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008287 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008288 }
8289
8290 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8291 // If there is a large requested alignment and we can, bump up the alignment
8292 // of the global.
8293 if (!GV->isDeclaration()) {
8294 GV->setAlignment(PrefAlign);
8295 Align = PrefAlign;
8296 }
8297 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8298 // If there is a requested alignment and if this is an alloca, round up. We
8299 // don't do this for malloc, because some systems can't respect the request.
8300 if (isa<AllocaInst>(AI)) {
8301 AI->setAlignment(PrefAlign);
8302 Align = PrefAlign;
8303 }
8304 }
8305
8306 return Align;
8307}
8308
8309/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8310/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8311/// and it is more than the alignment of the ultimate object, see if we can
8312/// increase the alignment of the ultimate object, making this check succeed.
8313unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8314 unsigned PrefAlign) {
8315 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8316 sizeof(PrefAlign) * CHAR_BIT;
8317 APInt Mask = APInt::getAllOnesValue(BitWidth);
8318 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8319 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8320 unsigned TrailZ = KnownZero.countTrailingOnes();
8321 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8322
8323 if (PrefAlign > Align)
8324 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8325
8326 // We don't need to make any adjustment.
8327 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008328}
8329
Chris Lattner00ae5132008-01-13 23:50:23 +00008330Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008331 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8332 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008333 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8334 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8335
8336 if (CopyAlign < MinAlign) {
8337 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8338 return MI;
8339 }
8340
8341 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8342 // load/store.
8343 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8344 if (MemOpLength == 0) return 0;
8345
Chris Lattnerc669fb62008-01-14 00:28:35 +00008346 // Source and destination pointer types are always "i8*" for intrinsic. See
8347 // if the size is something we can handle with a single primitive load/store.
8348 // A single load+store correctly handles overlapping memory in the memmove
8349 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008350 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008351 if (Size == 0) return MI; // Delete this mem transfer.
8352
8353 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008354 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008355
Chris Lattnerc669fb62008-01-14 00:28:35 +00008356 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008357 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008358
8359 // Memcpy forces the use of i8* for the source and destination. That means
8360 // that if you're using memcpy to move one double around, you'll get a cast
8361 // from double* to i8*. We'd much rather use a double load+store rather than
8362 // an i64 load+store, here because this improves the odds that the source or
8363 // dest address will be promotable. See if we can find a better type than the
8364 // integer datatype.
8365 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8366 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8367 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8368 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8369 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008370 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00008371 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8372 if (STy->getNumElements() == 1)
8373 SrcETy = STy->getElementType(0);
8374 else
8375 break;
8376 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8377 if (ATy->getNumElements() == 1)
8378 SrcETy = ATy->getElementType();
8379 else
8380 break;
8381 } else
8382 break;
8383 }
8384
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008385 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00008386 NewPtrTy = PointerType::getUnqual(SrcETy);
8387 }
8388 }
8389
8390
Chris Lattner00ae5132008-01-13 23:50:23 +00008391 // If the memcpy/memmove provides better alignment info than we can
8392 // infer, use it.
8393 SrcAlign = std::max(SrcAlign, CopyAlign);
8394 DstAlign = std::max(DstAlign, CopyAlign);
8395
8396 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8397 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008398 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8399 InsertNewInstBefore(L, *MI);
8400 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8401
8402 // Set the size of the copy to 0, it will be deleted on the next iteration.
8403 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8404 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008405}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008406
Chris Lattner5af8a912008-04-30 06:39:11 +00008407Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8408 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8409 if (MI->getAlignment()->getZExtValue() < Alignment) {
8410 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8411 return MI;
8412 }
8413
8414 // Extract the length and alignment and fill if they are constant.
8415 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8416 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8417 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8418 return 0;
8419 uint64_t Len = LenC->getZExtValue();
8420 Alignment = MI->getAlignment()->getZExtValue();
8421
8422 // If the length is zero, this is a no-op
8423 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8424
8425 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8426 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8427 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8428
8429 Value *Dest = MI->getDest();
8430 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8431
8432 // Alignment 0 is identity for alignment 1 for memset, but not store.
8433 if (Alignment == 0) Alignment = 1;
8434
8435 // Extract the fill value and store.
8436 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8437 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8438 Alignment), *MI);
8439
8440 // Set the size of the copy to 0, it will be deleted on the next iteration.
8441 MI->setLength(Constant::getNullValue(LenC->getType()));
8442 return MI;
8443 }
8444
8445 return 0;
8446}
8447
8448
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008449/// visitCallInst - CallInst simplification. This mostly only handles folding
8450/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8451/// the heavy lifting.
8452///
8453Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8454 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8455 if (!II) return visitCallSite(&CI);
8456
8457 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8458 // visitCallSite.
8459 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8460 bool Changed = false;
8461
8462 // memmove/cpy/set of zero bytes is a noop.
8463 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8464 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8465
8466 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8467 if (CI->getZExtValue() == 1) {
8468 // Replace the instruction with just byte operations. We would
8469 // transform other cases to loads/stores, but we don't know if
8470 // alignment is sufficient.
8471 }
8472 }
8473
8474 // If we have a memmove and the source operation is a constant global,
8475 // then the source and dest pointers can't alias, so we can change this
8476 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008477 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008478 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8479 if (GVSrc->isConstant()) {
8480 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008481 Intrinsic::ID MemCpyID;
8482 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8483 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008484 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008485 MemCpyID = Intrinsic::memcpy_i64;
8486 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008487 Changed = true;
8488 }
Chris Lattner59b27d92008-05-28 05:30:41 +00008489
8490 // memmove(x,x,size) -> noop.
8491 if (MMI->getSource() == MMI->getDest())
8492 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008493 }
8494
8495 // If we can determine a pointer alignment that is bigger than currently
8496 // set, update the alignment.
8497 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008498 if (Instruction *I = SimplifyMemTransfer(MI))
8499 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008500 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8501 if (Instruction *I = SimplifyMemSet(MSI))
8502 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008503 }
8504
8505 if (Changed) return II;
8506 } else {
8507 switch (II->getIntrinsicID()) {
8508 default: break;
8509 case Intrinsic::ppc_altivec_lvx:
8510 case Intrinsic::ppc_altivec_lvxl:
8511 case Intrinsic::x86_sse_loadu_ps:
8512 case Intrinsic::x86_sse2_loadu_pd:
8513 case Intrinsic::x86_sse2_loadu_dq:
8514 // Turn PPC lvx -> load if the pointer is known aligned.
8515 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008516 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008517 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8518 PointerType::getUnqual(II->getType()),
8519 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008520 return new LoadInst(Ptr);
8521 }
8522 break;
8523 case Intrinsic::ppc_altivec_stvx:
8524 case Intrinsic::ppc_altivec_stvxl:
8525 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008526 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008527 const Type *OpPtrTy =
8528 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008529 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008530 return new StoreInst(II->getOperand(1), Ptr);
8531 }
8532 break;
8533 case Intrinsic::x86_sse_storeu_ps:
8534 case Intrinsic::x86_sse2_storeu_pd:
8535 case Intrinsic::x86_sse2_storeu_dq:
8536 case Intrinsic::x86_sse2_storel_dq:
8537 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008538 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008539 const Type *OpPtrTy =
8540 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008541 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008542 return new StoreInst(II->getOperand(2), Ptr);
8543 }
8544 break;
8545
8546 case Intrinsic::x86_sse_cvttss2si: {
8547 // These intrinsics only demands the 0th element of its input vector. If
8548 // we can simplify the input based on that, do so now.
8549 uint64_t UndefElts;
8550 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8551 UndefElts)) {
8552 II->setOperand(1, V);
8553 return II;
8554 }
8555 break;
8556 }
8557
8558 case Intrinsic::ppc_altivec_vperm:
8559 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8560 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8561 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8562
8563 // Check that all of the elements are integer constants or undefs.
8564 bool AllEltsOk = true;
8565 for (unsigned i = 0; i != 16; ++i) {
8566 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8567 !isa<UndefValue>(Mask->getOperand(i))) {
8568 AllEltsOk = false;
8569 break;
8570 }
8571 }
8572
8573 if (AllEltsOk) {
8574 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008575 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8576 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008577 Value *Result = UndefValue::get(Op0->getType());
8578
8579 // Only extract each element once.
8580 Value *ExtractedElts[32];
8581 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8582
8583 for (unsigned i = 0; i != 16; ++i) {
8584 if (isa<UndefValue>(Mask->getOperand(i)))
8585 continue;
8586 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8587 Idx &= 31; // Match the hardware behavior.
8588
8589 if (ExtractedElts[Idx] == 0) {
8590 Instruction *Elt =
8591 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8592 InsertNewInstBefore(Elt, CI);
8593 ExtractedElts[Idx] = Elt;
8594 }
8595
8596 // Insert this value into the result vector.
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008597 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8598 i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008599 InsertNewInstBefore(cast<Instruction>(Result), CI);
8600 }
Gabor Greifa645dd32008-05-16 19:29:10 +00008601 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008602 }
8603 }
8604 break;
8605
8606 case Intrinsic::stackrestore: {
8607 // If the save is right next to the restore, remove the restore. This can
8608 // happen when variable allocas are DCE'd.
8609 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8610 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8611 BasicBlock::iterator BI = SS;
8612 if (&*++BI == II)
8613 return EraseInstFromFunction(CI);
8614 }
8615 }
8616
Chris Lattner416d91c2008-02-18 06:12:38 +00008617 // Scan down this block to see if there is another stack restore in the
8618 // same block without an intervening call/alloca.
8619 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008620 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008621 bool CannotRemove = false;
8622 for (++BI; &*BI != TI; ++BI) {
8623 if (isa<AllocaInst>(BI)) {
8624 CannotRemove = true;
8625 break;
8626 }
8627 if (isa<CallInst>(BI)) {
8628 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008629 CannotRemove = true;
8630 break;
8631 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008632 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008633 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008634 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008635 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008636
8637 // If the stack restore is in a return/unwind block and if there are no
8638 // allocas or calls between the restore and the return, nuke the restore.
8639 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8640 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008641 break;
8642 }
8643 }
8644 }
8645
8646 return visitCallSite(II);
8647}
8648
8649// InvokeInst simplification
8650//
8651Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8652 return visitCallSite(&II);
8653}
8654
Dale Johannesen96021832008-04-25 21:16:07 +00008655/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8656/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008657static bool isSafeToEliminateVarargsCast(const CallSite CS,
8658 const CastInst * const CI,
8659 const TargetData * const TD,
8660 const int ix) {
8661 if (!CI->isLosslessCast())
8662 return false;
8663
8664 // The size of ByVal arguments is derived from the type, so we
8665 // can't change to a type with a different size. If the size were
8666 // passed explicitly we could avoid this check.
8667 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8668 return true;
8669
8670 const Type* SrcTy =
8671 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8672 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8673 if (!SrcTy->isSized() || !DstTy->isSized())
8674 return false;
8675 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8676 return false;
8677 return true;
8678}
8679
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008680// visitCallSite - Improvements for call and invoke instructions.
8681//
8682Instruction *InstCombiner::visitCallSite(CallSite CS) {
8683 bool Changed = false;
8684
8685 // If the callee is a constexpr cast of a function, attempt to move the cast
8686 // to the arguments of the call/invoke.
8687 if (transformConstExprCastCall(CS)) return 0;
8688
8689 Value *Callee = CS.getCalledValue();
8690
8691 if (Function *CalleeF = dyn_cast<Function>(Callee))
8692 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8693 Instruction *OldCall = CS.getInstruction();
8694 // If the call and callee calling conventions don't match, this call must
8695 // be unreachable, as the call is undefined.
8696 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008697 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8698 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008699 if (!OldCall->use_empty())
8700 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8701 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8702 return EraseInstFromFunction(*OldCall);
8703 return 0;
8704 }
8705
8706 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8707 // This instruction is not reachable, just remove it. We insert a store to
8708 // undef so that we know that this code is not reachable, despite the fact
8709 // that we can't modify the CFG here.
8710 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008711 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008712 CS.getInstruction());
8713
8714 if (!CS.getInstruction()->use_empty())
8715 CS.getInstruction()->
8716 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8717
8718 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8719 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008720 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8721 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008722 }
8723 return EraseInstFromFunction(*CS.getInstruction());
8724 }
8725
Duncan Sands74833f22007-09-17 10:26:40 +00008726 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8727 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8728 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8729 return transformCallThroughTrampoline(CS);
8730
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008731 const PointerType *PTy = cast<PointerType>(Callee->getType());
8732 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8733 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00008734 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008735 // See if we can optimize any arguments passed through the varargs area of
8736 // the call.
8737 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00008738 E = CS.arg_end(); I != E; ++I, ++ix) {
8739 CastInst *CI = dyn_cast<CastInst>(*I);
8740 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8741 *I = CI->getOperand(0);
8742 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008743 }
Dale Johannesen35615462008-04-23 18:34:37 +00008744 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008745 }
8746
Duncan Sands2937e352007-12-19 21:13:37 +00008747 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008748 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008749 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008750 Changed = true;
8751 }
8752
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008753 return Changed ? CS.getInstruction() : 0;
8754}
8755
8756// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8757// attempt to move the cast to the arguments of the call/invoke.
8758//
8759bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8760 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8761 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8762 if (CE->getOpcode() != Instruction::BitCast ||
8763 !isa<Function>(CE->getOperand(0)))
8764 return false;
8765 Function *Callee = cast<Function>(CE->getOperand(0));
8766 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00008767 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008768
8769 // Okay, this is a cast from a function to a different type. Unless doing so
8770 // would cause a type conversion of one of our arguments, change this call to
8771 // be a direct call with arguments casted to the appropriate types.
8772 //
8773 const FunctionType *FT = Callee->getFunctionType();
8774 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00008775 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008776
Duncan Sands7901ce12008-06-01 07:38:42 +00008777 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00008778 return false; // TODO: Handle multiple return values.
8779
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008780 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00008781 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00008782 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00008783 // Conversion is ok if changing from one pointer type to another or from
8784 // a pointer to an integer of the same size.
8785 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8786 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008787 return false; // Cannot transform this return value.
8788
Duncan Sands5c489582008-01-06 10:12:28 +00008789 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008790 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00008791 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008792 return false; // Cannot transform this return value.
8793
Chris Lattner1c8733e2008-03-12 17:45:29 +00008794 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8795 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands7901ce12008-06-01 07:38:42 +00008796 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008797 return false; // Attribute not compatible with transformed value.
8798 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008799
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008800 // If the callsite is an invoke instruction, and the return value is used by
8801 // a PHI node in a successor, we cannot change the return type of the call
8802 // because there is no place to put the cast instruction (without breaking
8803 // the critical edge). Bail out in this case.
8804 if (!Caller->use_empty())
8805 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8806 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8807 UI != E; ++UI)
8808 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8809 if (PN->getParent() == II->getNormalDest() ||
8810 PN->getParent() == II->getUnwindDest())
8811 return false;
8812 }
8813
8814 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8815 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8816
8817 CallSite::arg_iterator AI = CS.arg_begin();
8818 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8819 const Type *ParamTy = FT->getParamType(i);
8820 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008821
8822 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008823 return false; // Cannot transform this parameter value.
8824
Chris Lattner1c8733e2008-03-12 17:45:29 +00008825 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8826 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00008827
Duncan Sands7901ce12008-06-01 07:38:42 +00008828 // Converting from one pointer type to another or between a pointer and an
8829 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008830 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00008831 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8832 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008833 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008834 }
8835
8836 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8837 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00008838 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008839
Chris Lattner1c8733e2008-03-12 17:45:29 +00008840 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8841 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00008842 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008843 // won't be dropping them. Check that these extra arguments have attributes
8844 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008845 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8846 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00008847 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00008848 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00008849 if (PAttrs & ParamAttr::VarArgsIncompatible)
8850 return false;
8851 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008852
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008853 // Okay, we decided that this is a safe thing to do: go ahead and start
8854 // inserting cast instructions as necessary...
8855 std::vector<Value*> Args;
8856 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00008857 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00008858 attrVec.reserve(NumCommonArgs);
8859
8860 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008861 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00008862
8863 // If the return value is not being used, the type may not be compatible
8864 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands7901ce12008-06-01 07:38:42 +00008865 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00008866
8867 // Add the new return attributes.
8868 if (RAttrs)
8869 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008870
8871 AI = CS.arg_begin();
8872 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8873 const Type *ParamTy = FT->getParamType(i);
8874 if ((*AI)->getType() == ParamTy) {
8875 Args.push_back(*AI);
8876 } else {
8877 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8878 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008879 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008880 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8881 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008882
8883 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008884 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00008885 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008886 }
8887
8888 // If the function takes more arguments than the call was taking, add them
8889 // now...
8890 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8891 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8892
8893 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008894 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008895 if (!FT->isVarArg()) {
8896 cerr << "WARNING: While resolving call to function '"
8897 << Callee->getName() << "' arguments were dropped!\n";
8898 } else {
8899 // Add all of the arguments in their promoted form to the arg list...
8900 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8901 const Type *PTy = getPromotedType((*AI)->getType());
8902 if (PTy != (*AI)->getType()) {
8903 // Must promote to pass through va_arg area!
8904 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8905 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008906 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008907 InsertNewInstBefore(Cast, *Caller);
8908 Args.push_back(Cast);
8909 } else {
8910 Args.push_back(*AI);
8911 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008912
Duncan Sands4ced1f82008-01-13 08:02:44 +00008913 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008914 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00008915 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8916 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008917 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00008918 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008919
Duncan Sands7901ce12008-06-01 07:38:42 +00008920 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008921 Caller->setName(""); // Void type should not have a name.
8922
Chris Lattner1c8733e2008-03-12 17:45:29 +00008923 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00008924
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008925 Instruction *NC;
8926 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00008927 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008928 Args.begin(), Args.end(),
8929 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008930 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008931 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008932 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00008933 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8934 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008935 CallInst *CI = cast<CallInst>(Caller);
8936 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008937 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008938 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008939 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008940 }
8941
8942 // Insert a cast of the return type as necessary.
8943 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008944 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008945 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008946 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008947 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00008948 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008949
8950 // If this is an invoke instruction, we should insert it after the first
8951 // non-phi, instruction in the normal successor block.
8952 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00008953 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008954 InsertNewInstBefore(NC, *I);
8955 } else {
8956 // Otherwise, it's a call, just insert cast right after the call instr
8957 InsertNewInstBefore(NC, *Caller);
8958 }
8959 AddUsersToWorkList(*Caller);
8960 } else {
8961 NV = UndefValue::get(Caller->getType());
8962 }
8963 }
8964
8965 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8966 Caller->replaceAllUsesWith(NV);
8967 Caller->eraseFromParent();
8968 RemoveFromWorkList(Caller);
8969 return true;
8970}
8971
Duncan Sands74833f22007-09-17 10:26:40 +00008972// transformCallThroughTrampoline - Turn a call to a function created by the
8973// init_trampoline intrinsic into a direct call to the underlying function.
8974//
8975Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8976 Value *Callee = CS.getCalledValue();
8977 const PointerType *PTy = cast<PointerType>(Callee->getType());
8978 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00008979 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00008980
8981 // If the call already has the 'nest' attribute somewhere then give up -
8982 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00008983 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00008984 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00008985
8986 IntrinsicInst *Tramp =
8987 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8988
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00008989 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00008990 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8991 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8992
Chris Lattner1c8733e2008-03-12 17:45:29 +00008993 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8994 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00008995 unsigned NestIdx = 1;
8996 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00008997 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00008998
8999 // Look for a parameter marked with the 'nest' attribute.
9000 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9001 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009002 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009003 // Record the parameter type and any other attributes.
9004 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009005 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009006 break;
9007 }
9008
9009 if (NestTy) {
9010 Instruction *Caller = CS.getInstruction();
9011 std::vector<Value*> NewArgs;
9012 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9013
Chris Lattner1c8733e2008-03-12 17:45:29 +00009014 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9015 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009016
Duncan Sands74833f22007-09-17 10:26:40 +00009017 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009018 // mean appending it. Likewise for attributes.
9019
9020 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009021 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9022 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009023
Duncan Sands74833f22007-09-17 10:26:40 +00009024 {
9025 unsigned Idx = 1;
9026 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9027 do {
9028 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009029 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009030 Value *NestVal = Tramp->getOperand(3);
9031 if (NestVal->getType() != NestTy)
9032 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9033 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009034 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009035 }
9036
9037 if (I == E)
9038 break;
9039
Duncan Sands48b81112008-01-14 19:52:09 +00009040 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009041 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009042 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009043 NewAttrs.push_back
9044 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009045
9046 ++Idx, ++I;
9047 } while (1);
9048 }
9049
9050 // The trampoline may have been bitcast to a bogus type (FTy).
9051 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009052 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009053
Duncan Sands74833f22007-09-17 10:26:40 +00009054 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009055 NewTypes.reserve(FTy->getNumParams()+1);
9056
Duncan Sands74833f22007-09-17 10:26:40 +00009057 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009058 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009059 {
9060 unsigned Idx = 1;
9061 FunctionType::param_iterator I = FTy->param_begin(),
9062 E = FTy->param_end();
9063
9064 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009065 if (Idx == NestIdx)
9066 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009067 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009068
9069 if (I == E)
9070 break;
9071
Duncan Sands48b81112008-01-14 19:52:09 +00009072 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009073 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009074
9075 ++Idx, ++I;
9076 } while (1);
9077 }
9078
9079 // Replace the trampoline call with a direct call. Let the generic
9080 // code sort out any function type mismatches.
9081 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009082 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009083 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9084 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009085 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009086
9087 Instruction *NewCaller;
9088 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009089 NewCaller = InvokeInst::Create(NewCallee,
9090 II->getNormalDest(), II->getUnwindDest(),
9091 NewArgs.begin(), NewArgs.end(),
9092 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009093 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009094 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009095 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009096 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9097 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009098 if (cast<CallInst>(Caller)->isTailCall())
9099 cast<CallInst>(NewCaller)->setTailCall();
9100 cast<CallInst>(NewCaller)->
9101 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009102 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009103 }
9104 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9105 Caller->replaceAllUsesWith(NewCaller);
9106 Caller->eraseFromParent();
9107 RemoveFromWorkList(Caller);
9108 return 0;
9109 }
9110 }
9111
9112 // Replace the trampoline call with a direct call. Since there is no 'nest'
9113 // parameter, there is no need to adjust the argument list. Let the generic
9114 // code sort out any function type mismatches.
9115 Constant *NewCallee =
9116 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9117 CS.setCalledFunction(NewCallee);
9118 return CS.getInstruction();
9119}
9120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009121/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9122/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9123/// and a single binop.
9124Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9125 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9126 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9127 isa<CmpInst>(FirstInst));
9128 unsigned Opc = FirstInst->getOpcode();
9129 Value *LHSVal = FirstInst->getOperand(0);
9130 Value *RHSVal = FirstInst->getOperand(1);
9131
9132 const Type *LHSType = LHSVal->getType();
9133 const Type *RHSType = RHSVal->getType();
9134
9135 // Scan to see if all operands are the same opcode, all have one use, and all
9136 // kill their operands (i.e. the operands have one use).
9137 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9138 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9139 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9140 // Verify type of the LHS matches so we don't fold cmp's of different
9141 // types or GEP's with different index types.
9142 I->getOperand(0)->getType() != LHSType ||
9143 I->getOperand(1)->getType() != RHSType)
9144 return 0;
9145
9146 // If they are CmpInst instructions, check their predicates
9147 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9148 if (cast<CmpInst>(I)->getPredicate() !=
9149 cast<CmpInst>(FirstInst)->getPredicate())
9150 return 0;
9151
9152 // Keep track of which operand needs a phi node.
9153 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9154 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9155 }
9156
9157 // Otherwise, this is safe to transform, determine if it is profitable.
9158
9159 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9160 // Indexes are often folded into load/store instructions, so we don't want to
9161 // hide them behind a phi.
9162 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9163 return 0;
9164
9165 Value *InLHS = FirstInst->getOperand(0);
9166 Value *InRHS = FirstInst->getOperand(1);
9167 PHINode *NewLHS = 0, *NewRHS = 0;
9168 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009169 NewLHS = PHINode::Create(LHSType,
9170 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009171 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9172 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9173 InsertNewInstBefore(NewLHS, PN);
9174 LHSVal = NewLHS;
9175 }
9176
9177 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009178 NewRHS = PHINode::Create(RHSType,
9179 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009180 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9181 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9182 InsertNewInstBefore(NewRHS, PN);
9183 RHSVal = NewRHS;
9184 }
9185
9186 // Add all operands to the new PHIs.
9187 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9188 if (NewLHS) {
9189 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9190 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9191 }
9192 if (NewRHS) {
9193 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9194 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9195 }
9196 }
9197
9198 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009199 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009200 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009201 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009202 RHSVal);
9203 else {
9204 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009205 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009206 }
9207}
9208
9209/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9210/// of the block that defines it. This means that it must be obvious the value
9211/// of the load is not changed from the point of the load to the end of the
9212/// block it is in.
9213///
9214/// Finally, it is safe, but not profitable, to sink a load targetting a
9215/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9216/// to a register.
9217static bool isSafeToSinkLoad(LoadInst *L) {
9218 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9219
9220 for (++BBI; BBI != E; ++BBI)
9221 if (BBI->mayWriteToMemory())
9222 return false;
9223
9224 // Check for non-address taken alloca. If not address-taken already, it isn't
9225 // profitable to do this xform.
9226 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9227 bool isAddressTaken = false;
9228 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9229 UI != E; ++UI) {
9230 if (isa<LoadInst>(UI)) continue;
9231 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9232 // If storing TO the alloca, then the address isn't taken.
9233 if (SI->getOperand(1) == AI) continue;
9234 }
9235 isAddressTaken = true;
9236 break;
9237 }
9238
9239 if (!isAddressTaken)
9240 return false;
9241 }
9242
9243 return true;
9244}
9245
9246
9247// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9248// operator and they all are only used by the PHI, PHI together their
9249// inputs, and do the operation once, to the result of the PHI.
9250Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9251 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9252
9253 // Scan the instruction, looking for input operations that can be folded away.
9254 // If all input operands to the phi are the same instruction (e.g. a cast from
9255 // the same type or "+42") we can pull the operation through the PHI, reducing
9256 // code size and simplifying code.
9257 Constant *ConstantOp = 0;
9258 const Type *CastSrcTy = 0;
9259 bool isVolatile = false;
9260 if (isa<CastInst>(FirstInst)) {
9261 CastSrcTy = FirstInst->getOperand(0)->getType();
9262 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9263 // Can fold binop, compare or shift here if the RHS is a constant,
9264 // otherwise call FoldPHIArgBinOpIntoPHI.
9265 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9266 if (ConstantOp == 0)
9267 return FoldPHIArgBinOpIntoPHI(PN);
9268 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9269 isVolatile = LI->isVolatile();
9270 // We can't sink the load if the loaded value could be modified between the
9271 // load and the PHI.
9272 if (LI->getParent() != PN.getIncomingBlock(0) ||
9273 !isSafeToSinkLoad(LI))
9274 return 0;
9275 } else if (isa<GetElementPtrInst>(FirstInst)) {
9276 if (FirstInst->getNumOperands() == 2)
9277 return FoldPHIArgBinOpIntoPHI(PN);
9278 // Can't handle general GEPs yet.
9279 return 0;
9280 } else {
9281 return 0; // Cannot fold this operation.
9282 }
9283
9284 // Check to see if all arguments are the same operation.
9285 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9286 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9287 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9288 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9289 return 0;
9290 if (CastSrcTy) {
9291 if (I->getOperand(0)->getType() != CastSrcTy)
9292 return 0; // Cast operation must match.
9293 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9294 // We can't sink the load if the loaded value could be modified between
9295 // the load and the PHI.
9296 if (LI->isVolatile() != isVolatile ||
9297 LI->getParent() != PN.getIncomingBlock(i) ||
9298 !isSafeToSinkLoad(LI))
9299 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009300
9301 // If the PHI is volatile and its block has multiple successors, sinking
9302 // it would remove a load of the volatile value from the path through the
9303 // other successor.
9304 if (isVolatile &&
9305 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9306 return 0;
9307
9308
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009309 } else if (I->getOperand(1) != ConstantOp) {
9310 return 0;
9311 }
9312 }
9313
9314 // Okay, they are all the same operation. Create a new PHI node of the
9315 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009316 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9317 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009318 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9319
9320 Value *InVal = FirstInst->getOperand(0);
9321 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9322
9323 // Add all operands to the new PHI.
9324 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9325 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9326 if (NewInVal != InVal)
9327 InVal = 0;
9328 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9329 }
9330
9331 Value *PhiVal;
9332 if (InVal) {
9333 // The new PHI unions all of the same values together. This is really
9334 // common, so we handle it intelligently here for compile-time speed.
9335 PhiVal = InVal;
9336 delete NewPN;
9337 } else {
9338 InsertNewInstBefore(NewPN, PN);
9339 PhiVal = NewPN;
9340 }
9341
9342 // Insert and return the new operation.
9343 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009344 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009345 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009346 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009347 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009348 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009349 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009350 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9351
9352 // If this was a volatile load that we are merging, make sure to loop through
9353 // and mark all the input loads as non-volatile. If we don't do this, we will
9354 // insert a new volatile load and the old ones will not be deletable.
9355 if (isVolatile)
9356 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9357 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9358
9359 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009360}
9361
9362/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9363/// that is dead.
9364static bool DeadPHICycle(PHINode *PN,
9365 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9366 if (PN->use_empty()) return true;
9367 if (!PN->hasOneUse()) return false;
9368
9369 // Remember this node, and if we find the cycle, return.
9370 if (!PotentiallyDeadPHIs.insert(PN))
9371 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009372
9373 // Don't scan crazily complex things.
9374 if (PotentiallyDeadPHIs.size() == 16)
9375 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009376
9377 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9378 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9379
9380 return false;
9381}
9382
Chris Lattner27b695d2007-11-06 21:52:06 +00009383/// PHIsEqualValue - Return true if this phi node is always equal to
9384/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9385/// z = some value; x = phi (y, z); y = phi (x, z)
9386static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9387 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9388 // See if we already saw this PHI node.
9389 if (!ValueEqualPHIs.insert(PN))
9390 return true;
9391
9392 // Don't scan crazily complex things.
9393 if (ValueEqualPHIs.size() == 16)
9394 return false;
9395
9396 // Scan the operands to see if they are either phi nodes or are equal to
9397 // the value.
9398 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9399 Value *Op = PN->getIncomingValue(i);
9400 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9401 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9402 return false;
9403 } else if (Op != NonPhiInVal)
9404 return false;
9405 }
9406
9407 return true;
9408}
9409
9410
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009411// PHINode simplification
9412//
9413Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9414 // If LCSSA is around, don't mess with Phi nodes
9415 if (MustPreserveLCSSA) return 0;
9416
9417 if (Value *V = PN.hasConstantValue())
9418 return ReplaceInstUsesWith(PN, V);
9419
9420 // If all PHI operands are the same operation, pull them through the PHI,
9421 // reducing code size.
9422 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9423 PN.getIncomingValue(0)->hasOneUse())
9424 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9425 return Result;
9426
9427 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9428 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9429 // PHI)... break the cycle.
9430 if (PN.hasOneUse()) {
9431 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9432 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9433 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9434 PotentiallyDeadPHIs.insert(&PN);
9435 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9436 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9437 }
9438
9439 // If this phi has a single use, and if that use just computes a value for
9440 // the next iteration of a loop, delete the phi. This occurs with unused
9441 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9442 // common case here is good because the only other things that catch this
9443 // are induction variable analysis (sometimes) and ADCE, which is only run
9444 // late.
9445 if (PHIUser->hasOneUse() &&
9446 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9447 PHIUser->use_back() == &PN) {
9448 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9449 }
9450 }
9451
Chris Lattner27b695d2007-11-06 21:52:06 +00009452 // We sometimes end up with phi cycles that non-obviously end up being the
9453 // same value, for example:
9454 // z = some value; x = phi (y, z); y = phi (x, z)
9455 // where the phi nodes don't necessarily need to be in the same block. Do a
9456 // quick check to see if the PHI node only contains a single non-phi value, if
9457 // so, scan to see if the phi cycle is actually equal to that value.
9458 {
9459 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9460 // Scan for the first non-phi operand.
9461 while (InValNo != NumOperandVals &&
9462 isa<PHINode>(PN.getIncomingValue(InValNo)))
9463 ++InValNo;
9464
9465 if (InValNo != NumOperandVals) {
9466 Value *NonPhiInVal = PN.getOperand(InValNo);
9467
9468 // Scan the rest of the operands to see if there are any conflicts, if so
9469 // there is no need to recursively scan other phis.
9470 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9471 Value *OpVal = PN.getIncomingValue(InValNo);
9472 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9473 break;
9474 }
9475
9476 // If we scanned over all operands, then we have one unique value plus
9477 // phi values. Scan PHI nodes to see if they all merge in each other or
9478 // the value.
9479 if (InValNo == NumOperandVals) {
9480 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9481 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9482 return ReplaceInstUsesWith(PN, NonPhiInVal);
9483 }
9484 }
9485 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009486 return 0;
9487}
9488
9489static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9490 Instruction *InsertPoint,
9491 InstCombiner *IC) {
9492 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9493 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9494 // We must cast correctly to the pointer type. Ensure that we
9495 // sign extend the integer value if it is smaller as this is
9496 // used for address computation.
9497 Instruction::CastOps opcode =
9498 (VTySize < PtrSize ? Instruction::SExt :
9499 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9500 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9501}
9502
9503
9504Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9505 Value *PtrOp = GEP.getOperand(0);
9506 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9507 // If so, eliminate the noop.
9508 if (GEP.getNumOperands() == 1)
9509 return ReplaceInstUsesWith(GEP, PtrOp);
9510
9511 if (isa<UndefValue>(GEP.getOperand(0)))
9512 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9513
9514 bool HasZeroPointerIndex = false;
9515 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9516 HasZeroPointerIndex = C->isNullValue();
9517
9518 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9519 return ReplaceInstUsesWith(GEP, PtrOp);
9520
9521 // Eliminate unneeded casts for indices.
9522 bool MadeChange = false;
9523
9524 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009525 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9526 i != e; ++i, ++GTI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009527 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +00009528 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009529 if (CI->getOpcode() == Instruction::ZExt ||
9530 CI->getOpcode() == Instruction::SExt) {
9531 const Type *SrcTy = CI->getOperand(0)->getType();
9532 // We can eliminate a cast from i32 to i64 iff the target
9533 // is a 32-bit pointer target.
9534 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9535 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +00009536 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009537 }
9538 }
9539 }
9540 // If we are using a wider index than needed for this platform, shrink it
9541 // to what we need. If the incoming value needs a cast instruction,
9542 // insert it. This explicit cast can make subsequent optimizations more
9543 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +00009544 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009545 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009546 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +00009547 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009548 MadeChange = true;
9549 } else {
9550 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9551 GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009552 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009553 MadeChange = true;
9554 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009555 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009556 }
9557 }
9558 if (MadeChange) return &GEP;
9559
9560 // If this GEP instruction doesn't move the pointer, and if the input operand
9561 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9562 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009563 if (GEP.hasAllZeroIndices()) {
9564 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9565 // If the bitcast is of an allocation, and the allocation will be
9566 // converted to match the type of the cast, don't touch this.
9567 if (isa<AllocationInst>(BCI->getOperand(0))) {
9568 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009569 if (Instruction *I = visitBitCast(*BCI)) {
9570 if (I != BCI) {
9571 I->takeName(BCI);
9572 BCI->getParent()->getInstList().insert(BCI, I);
9573 ReplaceInstUsesWith(*BCI, I);
9574 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009575 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009576 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009577 }
9578 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9579 }
9580 }
9581
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009582 // Combine Indices - If the source pointer to this getelementptr instruction
9583 // is a getelementptr instruction, combine the indices of the two
9584 // getelementptr instructions into a single instruction.
9585 //
9586 SmallVector<Value*, 8> SrcGEPOperands;
9587 if (User *Src = dyn_castGetElementPtr(PtrOp))
9588 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9589
9590 if (!SrcGEPOperands.empty()) {
9591 // Note that if our source is a gep chain itself that we wait for that
9592 // chain to be resolved before we perform this transformation. This
9593 // avoids us creating a TON of code in some cases.
9594 //
9595 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9596 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9597 return 0; // Wait until our source is folded to completion.
9598
9599 SmallVector<Value*, 8> Indices;
9600
9601 // Find out whether the last index in the source GEP is a sequential idx.
9602 bool EndsWithSequential = false;
9603 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9604 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9605 EndsWithSequential = !isa<StructType>(*I);
9606
9607 // Can we combine the two pointer arithmetics offsets?
9608 if (EndsWithSequential) {
9609 // Replace: gep (gep %P, long B), long A, ...
9610 // With: T = long A+B; gep %P, T, ...
9611 //
9612 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9613 if (SO1 == Constant::getNullValue(SO1->getType())) {
9614 Sum = GO1;
9615 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9616 Sum = SO1;
9617 } else {
9618 // If they aren't the same type, convert both to an integer of the
9619 // target's pointer size.
9620 if (SO1->getType() != GO1->getType()) {
9621 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9622 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9623 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9624 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9625 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009626 unsigned PS = TD->getPointerSizeInBits();
9627 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009628 // Convert GO1 to SO1's type.
9629 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9630
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009631 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009632 // Convert SO1 to GO1's type.
9633 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9634 } else {
9635 const Type *PT = TD->getIntPtrType();
9636 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9637 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9638 }
9639 }
9640 }
9641 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9642 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9643 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00009644 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009645 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9646 }
9647 }
9648
9649 // Recycle the GEP we already have if possible.
9650 if (SrcGEPOperands.size() == 2) {
9651 GEP.setOperand(0, SrcGEPOperands[0]);
9652 GEP.setOperand(1, Sum);
9653 return &GEP;
9654 } else {
9655 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9656 SrcGEPOperands.end()-1);
9657 Indices.push_back(Sum);
9658 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9659 }
9660 } else if (isa<Constant>(*GEP.idx_begin()) &&
9661 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9662 SrcGEPOperands.size() != 1) {
9663 // Otherwise we can do the fold if the first index of the GEP is a zero
9664 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9665 SrcGEPOperands.end());
9666 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9667 }
9668
9669 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +00009670 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9671 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009672
9673 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9674 // GEP of global variable. If all of the indices for this GEP are
9675 // constants, we can promote this to a constexpr instead of an instruction.
9676
9677 // Scan for nonconstants...
9678 SmallVector<Constant*, 8> Indices;
9679 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9680 for (; I != E && isa<Constant>(*I); ++I)
9681 Indices.push_back(cast<Constant>(*I));
9682
9683 if (I == E) { // If they are all constants...
9684 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9685 &Indices[0],Indices.size());
9686
9687 // Replace all uses of the GEP with the new constexpr...
9688 return ReplaceInstUsesWith(GEP, CE);
9689 }
9690 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9691 if (!isa<PointerType>(X->getType())) {
9692 // Not interesting. Source pointer must be a cast from pointer.
9693 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009694 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9695 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009696 //
9697 // This occurs when the program declares an array extern like "int X[];"
9698 //
9699 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9700 const PointerType *XTy = cast<PointerType>(X->getType());
9701 if (const ArrayType *XATy =
9702 dyn_cast<ArrayType>(XTy->getElementType()))
9703 if (const ArrayType *CATy =
9704 dyn_cast<ArrayType>(CPTy->getElementType()))
9705 if (CATy->getElementType() == XATy->getElementType()) {
9706 // At this point, we know that the cast source type is a pointer
9707 // to an array of the same type as the destination pointer
9708 // array. Because the array type is never stepped over (there
9709 // is a leading zero) we can fold the cast into this GEP.
9710 GEP.setOperand(0, X);
9711 return &GEP;
9712 }
9713 } else if (GEP.getNumOperands() == 2) {
9714 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009715 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9716 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009717 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9718 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9719 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009720 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9721 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009722 Value *Idx[2];
9723 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9724 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009725 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +00009726 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009727 // V and GEP are both pointer types --> BitCast
9728 return new BitCastInst(V, GEP.getType());
9729 }
9730
9731 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009732 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009733 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009734 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009735
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009736 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009737 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009738 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009739
9740 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9741 // allow either a mul, shift, or constant here.
9742 Value *NewIdx = 0;
9743 ConstantInt *Scale = 0;
9744 if (ArrayEltSize == 1) {
9745 NewIdx = GEP.getOperand(1);
9746 Scale = ConstantInt::get(NewIdx->getType(), 1);
9747 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9748 NewIdx = ConstantInt::get(CI->getType(), 1);
9749 Scale = CI;
9750 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9751 if (Inst->getOpcode() == Instruction::Shl &&
9752 isa<ConstantInt>(Inst->getOperand(1))) {
9753 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9754 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9755 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9756 NewIdx = Inst->getOperand(0);
9757 } else if (Inst->getOpcode() == Instruction::Mul &&
9758 isa<ConstantInt>(Inst->getOperand(1))) {
9759 Scale = cast<ConstantInt>(Inst->getOperand(1));
9760 NewIdx = Inst->getOperand(0);
9761 }
9762 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009763
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009764 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009765 // out, perform the transformation. Note, we don't know whether Scale is
9766 // signed or not. We'll use unsigned version of division/modulo
9767 // operation after making sure Scale doesn't have the sign bit set.
9768 if (Scale && Scale->getSExtValue() >= 0LL &&
9769 Scale->getZExtValue() % ArrayEltSize == 0) {
9770 Scale = ConstantInt::get(Scale->getType(),
9771 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009772 if (Scale->getZExtValue() != 1) {
9773 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009774 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +00009775 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009776 NewIdx = InsertNewInstBefore(Sc, GEP);
9777 }
9778
9779 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009780 Value *Idx[2];
9781 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9782 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009783 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +00009784 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009785 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9786 // The NewGEP must be pointer typed, so must the old one -> BitCast
9787 return new BitCastInst(NewGEP, GEP.getType());
9788 }
9789 }
9790 }
9791 }
9792
9793 return 0;
9794}
9795
9796Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9797 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009798 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009799 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9800 const Type *NewTy =
9801 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9802 AllocationInst *New = 0;
9803
9804 // Create and insert the replacement instruction...
9805 if (isa<MallocInst>(AI))
9806 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9807 else {
9808 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9809 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9810 }
9811
9812 InsertNewInstBefore(New, AI);
9813
9814 // Scan to the end of the allocation instructions, to skip over a block of
9815 // allocas if possible...
9816 //
9817 BasicBlock::iterator It = New;
9818 while (isa<AllocationInst>(*It)) ++It;
9819
9820 // Now that I is pointing to the first non-allocation-inst in the block,
9821 // insert our getelementptr instruction...
9822 //
9823 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009824 Value *Idx[2];
9825 Idx[0] = NullIdx;
9826 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +00009827 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9828 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009829
9830 // Now make everything use the getelementptr instead of the original
9831 // allocation.
9832 return ReplaceInstUsesWith(AI, V);
9833 } else if (isa<UndefValue>(AI.getArraySize())) {
9834 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9835 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009836 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009837
9838 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9839 // Note that we only do this for alloca's, because malloc should allocate and
9840 // return a unique pointer, even for a zero byte allocation.
9841 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009842 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009843 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9844
9845 return 0;
9846}
9847
9848Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9849 Value *Op = FI.getOperand(0);
9850
9851 // free undef -> unreachable.
9852 if (isa<UndefValue>(Op)) {
9853 // Insert a new store to null because we cannot modify the CFG here.
9854 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009855 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009856 return EraseInstFromFunction(FI);
9857 }
9858
9859 // If we have 'free null' delete the instruction. This can happen in stl code
9860 // when lots of inlining happens.
9861 if (isa<ConstantPointerNull>(Op))
9862 return EraseInstFromFunction(FI);
9863
9864 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9865 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9866 FI.setOperand(0, CI->getOperand(0));
9867 return &FI;
9868 }
9869
9870 // Change free (gep X, 0,0,0,0) into free(X)
9871 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9872 if (GEPI->hasAllZeroIndices()) {
9873 AddToWorkList(GEPI);
9874 FI.setOperand(0, GEPI->getOperand(0));
9875 return &FI;
9876 }
9877 }
9878
9879 // Change free(malloc) into nothing, if the malloc has a single use.
9880 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9881 if (MI->hasOneUse()) {
9882 EraseInstFromFunction(FI);
9883 return EraseInstFromFunction(*MI);
9884 }
9885
9886 return 0;
9887}
9888
9889
9890/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009891static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +00009892 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009893 User *CI = cast<User>(LI.getOperand(0));
9894 Value *CastOp = CI->getOperand(0);
9895
Devang Patela0f8ea82007-10-18 19:52:32 +00009896 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9897 // Instead of loading constant c string, use corresponding integer value
9898 // directly if string length is small enough.
9899 const std::string &Str = CE->getOperand(0)->getStringValue();
9900 if (!Str.empty()) {
9901 unsigned len = Str.length();
9902 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9903 unsigned numBits = Ty->getPrimitiveSizeInBits();
9904 // Replace LI with immediate integer store.
9905 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00009906 APInt StrVal(numBits, 0);
9907 APInt SingleChar(numBits, 0);
9908 if (TD->isLittleEndian()) {
9909 for (signed i = len-1; i >= 0; i--) {
9910 SingleChar = (uint64_t) Str[i];
9911 StrVal = (StrVal << 8) | SingleChar;
9912 }
9913 } else {
9914 for (unsigned i = 0; i < len; i++) {
9915 SingleChar = (uint64_t) Str[i];
9916 StrVal = (StrVal << 8) | SingleChar;
9917 }
9918 // Append NULL at the end.
9919 SingleChar = 0;
9920 StrVal = (StrVal << 8) | SingleChar;
9921 }
9922 Value *NL = ConstantInt::get(StrVal);
9923 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +00009924 }
9925 }
9926 }
9927
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009928 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9929 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9930 const Type *SrcPTy = SrcTy->getElementType();
9931
9932 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9933 isa<VectorType>(DestPTy)) {
9934 // If the source is an array, the code below will not succeed. Check to
9935 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9936 // constants.
9937 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9938 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9939 if (ASrcTy->getNumElements() != 0) {
9940 Value *Idxs[2];
9941 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9942 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9943 SrcTy = cast<PointerType>(CastOp->getType());
9944 SrcPTy = SrcTy->getElementType();
9945 }
9946
9947 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9948 isa<VectorType>(SrcPTy)) &&
9949 // Do not allow turning this into a load of an integer, which is then
9950 // casted to a pointer, this pessimizes pointer analysis a lot.
9951 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9952 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9953 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9954
9955 // Okay, we are casting from one integer or pointer type to another of
9956 // the same size. Instead of casting the pointer before the load, cast
9957 // the result of the loaded value.
9958 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9959 CI->getName(),
9960 LI.isVolatile()),LI);
9961 // Now cast the result of the load.
9962 return new BitCastInst(NewLoad, LI.getType());
9963 }
9964 }
9965 }
9966 return 0;
9967}
9968
9969/// isSafeToLoadUnconditionally - Return true if we know that executing a load
9970/// from this value cannot trap. If it is not obviously safe to load from the
9971/// specified pointer, we do a quick local scan of the basic block containing
9972/// ScanFrom, to determine if the address is already accessed.
9973static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009974 // If it is an alloca it is always safe to load from.
9975 if (isa<AllocaInst>(V)) return true;
9976
Duncan Sandse40a94a2007-09-19 10:25:38 +00009977 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009978 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +00009979 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009980 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009981
9982 // Otherwise, be a little bit agressive by scanning the local block where we
9983 // want to check to see if the pointer is already being loaded or stored
9984 // from/to. If so, the previous load or store would have already trapped,
9985 // so there is no harm doing an extra load (also, CSE will later eliminate
9986 // the load entirely).
9987 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9988
9989 while (BBI != E) {
9990 --BBI;
9991
9992 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9993 if (LI->getOperand(0) == V) return true;
9994 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9995 if (SI->getOperand(1) == V) return true;
9996
9997 }
9998 return false;
9999}
10000
Chris Lattner0270a112007-08-11 18:48:48 +000010001/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10002/// until we find the underlying object a pointer is referring to or something
10003/// we don't understand. Note that the returned pointer may be offset from the
10004/// input, because we ignore GEP indices.
10005static Value *GetUnderlyingObject(Value *Ptr) {
10006 while (1) {
10007 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10008 if (CE->getOpcode() == Instruction::BitCast ||
10009 CE->getOpcode() == Instruction::GetElementPtr)
10010 Ptr = CE->getOperand(0);
10011 else
10012 return Ptr;
10013 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10014 Ptr = BCI->getOperand(0);
10015 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10016 Ptr = GEP->getOperand(0);
10017 } else {
10018 return Ptr;
10019 }
10020 }
10021}
10022
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010023Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10024 Value *Op = LI.getOperand(0);
10025
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010026 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010027 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10028 if (KnownAlign >
10029 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10030 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010031 LI.setAlignment(KnownAlign);
10032
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010033 // load (cast X) --> cast (load X) iff safe
10034 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010035 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010036 return Res;
10037
10038 // None of the following transforms are legal for volatile loads.
10039 if (LI.isVolatile()) return 0;
10040
10041 if (&LI.getParent()->front() != &LI) {
10042 BasicBlock::iterator BBI = &LI; --BBI;
10043 // If the instruction immediately before this is a store to the same
10044 // address, do a simple form of store->load forwarding.
10045 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10046 if (SI->getOperand(1) == LI.getOperand(0))
10047 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10048 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10049 if (LIB->getOperand(0) == LI.getOperand(0))
10050 return ReplaceInstUsesWith(LI, LIB);
10051 }
10052
Christopher Lamb2c175392007-12-29 07:56:53 +000010053 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10054 const Value *GEPI0 = GEPI->getOperand(0);
10055 // TODO: Consider a target hook for valid address spaces for this xform.
10056 if (isa<ConstantPointerNull>(GEPI0) &&
10057 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010058 // Insert a new store to null instruction before the load to indicate
10059 // that this code is not reachable. We do this instead of inserting
10060 // an unreachable instruction directly because we cannot modify the
10061 // CFG.
10062 new StoreInst(UndefValue::get(LI.getType()),
10063 Constant::getNullValue(Op->getType()), &LI);
10064 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10065 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010066 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010067
10068 if (Constant *C = dyn_cast<Constant>(Op)) {
10069 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010070 // TODO: Consider a target hook for valid address spaces for this xform.
10071 if (isa<UndefValue>(C) || (C->isNullValue() &&
10072 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010073 // Insert a new store to null instruction before the load to indicate that
10074 // this code is not reachable. We do this instead of inserting an
10075 // unreachable instruction directly because we cannot modify the CFG.
10076 new StoreInst(UndefValue::get(LI.getType()),
10077 Constant::getNullValue(Op->getType()), &LI);
10078 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10079 }
10080
10081 // Instcombine load (constant global) into the value loaded.
10082 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10083 if (GV->isConstant() && !GV->isDeclaration())
10084 return ReplaceInstUsesWith(LI, GV->getInitializer());
10085
10086 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010087 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010088 if (CE->getOpcode() == Instruction::GetElementPtr) {
10089 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10090 if (GV->isConstant() && !GV->isDeclaration())
10091 if (Constant *V =
10092 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10093 return ReplaceInstUsesWith(LI, V);
10094 if (CE->getOperand(0)->isNullValue()) {
10095 // Insert a new store to null instruction before the load to indicate
10096 // that this code is not reachable. We do this instead of inserting
10097 // an unreachable instruction directly because we cannot modify the
10098 // CFG.
10099 new StoreInst(UndefValue::get(LI.getType()),
10100 Constant::getNullValue(Op->getType()), &LI);
10101 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10102 }
10103
10104 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010105 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010106 return Res;
10107 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010108 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010109 }
Chris Lattner0270a112007-08-11 18:48:48 +000010110
10111 // If this load comes from anywhere in a constant global, and if the global
10112 // is all undef or zero, we know what it loads.
10113 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10114 if (GV->isConstant() && GV->hasInitializer()) {
10115 if (GV->getInitializer()->isNullValue())
10116 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10117 else if (isa<UndefValue>(GV->getInitializer()))
10118 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10119 }
10120 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010121
10122 if (Op->hasOneUse()) {
10123 // Change select and PHI nodes to select values instead of addresses: this
10124 // helps alias analysis out a lot, allows many others simplifications, and
10125 // exposes redundancy in the code.
10126 //
10127 // Note that we cannot do the transformation unless we know that the
10128 // introduced loads cannot trap! Something like this is valid as long as
10129 // the condition is always false: load (select bool %C, int* null, int* %G),
10130 // but it would not be valid if we transformed it to load from null
10131 // unconditionally.
10132 //
10133 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10134 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10135 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10136 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10137 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10138 SI->getOperand(1)->getName()+".val"), LI);
10139 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10140 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010141 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010142 }
10143
10144 // load (select (cond, null, P)) -> load P
10145 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10146 if (C->isNullValue()) {
10147 LI.setOperand(0, SI->getOperand(2));
10148 return &LI;
10149 }
10150
10151 // load (select (cond, P, null)) -> load P
10152 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10153 if (C->isNullValue()) {
10154 LI.setOperand(0, SI->getOperand(1));
10155 return &LI;
10156 }
10157 }
10158 }
10159 return 0;
10160}
10161
10162/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10163/// when possible.
10164static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10165 User *CI = cast<User>(SI.getOperand(1));
10166 Value *CastOp = CI->getOperand(0);
10167
10168 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10169 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10170 const Type *SrcPTy = SrcTy->getElementType();
10171
10172 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10173 // If the source is an array, the code below will not succeed. Check to
10174 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10175 // constants.
10176 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10177 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10178 if (ASrcTy->getNumElements() != 0) {
10179 Value* Idxs[2];
10180 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10181 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10182 SrcTy = cast<PointerType>(CastOp->getType());
10183 SrcPTy = SrcTy->getElementType();
10184 }
10185
10186 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10187 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10188 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10189
10190 // Okay, we are casting from one integer or pointer type to another of
10191 // the same size. Instead of casting the pointer before
10192 // the store, cast the value to be stored.
10193 Value *NewCast;
10194 Value *SIOp0 = SI.getOperand(0);
10195 Instruction::CastOps opcode = Instruction::BitCast;
10196 const Type* CastSrcTy = SIOp0->getType();
10197 const Type* CastDstTy = SrcPTy;
10198 if (isa<PointerType>(CastDstTy)) {
10199 if (CastSrcTy->isInteger())
10200 opcode = Instruction::IntToPtr;
10201 } else if (isa<IntegerType>(CastDstTy)) {
10202 if (isa<PointerType>(SIOp0->getType()))
10203 opcode = Instruction::PtrToInt;
10204 }
10205 if (Constant *C = dyn_cast<Constant>(SIOp0))
10206 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10207 else
10208 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010209 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010210 SI);
10211 return new StoreInst(NewCast, CastOp);
10212 }
10213 }
10214 }
10215 return 0;
10216}
10217
10218Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10219 Value *Val = SI.getOperand(0);
10220 Value *Ptr = SI.getOperand(1);
10221
10222 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10223 EraseInstFromFunction(SI);
10224 ++NumCombined;
10225 return 0;
10226 }
10227
10228 // If the RHS is an alloca with a single use, zapify the store, making the
10229 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010230 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010231 if (isa<AllocaInst>(Ptr)) {
10232 EraseInstFromFunction(SI);
10233 ++NumCombined;
10234 return 0;
10235 }
10236
10237 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10238 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10239 GEP->getOperand(0)->hasOneUse()) {
10240 EraseInstFromFunction(SI);
10241 ++NumCombined;
10242 return 0;
10243 }
10244 }
10245
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010246 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010247 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10248 if (KnownAlign >
10249 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10250 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010251 SI.setAlignment(KnownAlign);
10252
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010253 // Do really simple DSE, to catch cases where there are several consequtive
10254 // stores to the same location, separated by a few arithmetic operations. This
10255 // situation often occurs with bitfield accesses.
10256 BasicBlock::iterator BBI = &SI;
10257 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10258 --ScanInsts) {
10259 --BBI;
10260
10261 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10262 // Prev store isn't volatile, and stores to the same location?
10263 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10264 ++NumDeadStore;
10265 ++BBI;
10266 EraseInstFromFunction(*PrevSI);
10267 continue;
10268 }
10269 break;
10270 }
10271
10272 // If this is a load, we have to stop. However, if the loaded value is from
10273 // the pointer we're loading and is producing the pointer we're storing,
10274 // then *this* store is dead (X = load P; store X -> P).
10275 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010276 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010277 EraseInstFromFunction(SI);
10278 ++NumCombined;
10279 return 0;
10280 }
10281 // Otherwise, this is a load from some other location. Stores before it
10282 // may not be dead.
10283 break;
10284 }
10285
10286 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010287 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010288 break;
10289 }
10290
10291
10292 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10293
10294 // store X, null -> turns into 'unreachable' in SimplifyCFG
10295 if (isa<ConstantPointerNull>(Ptr)) {
10296 if (!isa<UndefValue>(Val)) {
10297 SI.setOperand(0, UndefValue::get(Val->getType()));
10298 if (Instruction *U = dyn_cast<Instruction>(Val))
10299 AddToWorkList(U); // Dropped a use.
10300 ++NumCombined;
10301 }
10302 return 0; // Do not modify these!
10303 }
10304
10305 // store undef, Ptr -> noop
10306 if (isa<UndefValue>(Val)) {
10307 EraseInstFromFunction(SI);
10308 ++NumCombined;
10309 return 0;
10310 }
10311
10312 // If the pointer destination is a cast, see if we can fold the cast into the
10313 // source instead.
10314 if (isa<CastInst>(Ptr))
10315 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10316 return Res;
10317 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10318 if (CE->isCast())
10319 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10320 return Res;
10321
10322
10323 // If this store is the last instruction in the basic block, and if the block
10324 // ends with an unconditional branch, try to move it to the successor block.
10325 BBI = &SI; ++BBI;
10326 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10327 if (BI->isUnconditional())
10328 if (SimplifyStoreAtEndOfBlock(SI))
10329 return 0; // xform done!
10330
10331 return 0;
10332}
10333
10334/// SimplifyStoreAtEndOfBlock - Turn things like:
10335/// if () { *P = v1; } else { *P = v2 }
10336/// into a phi node with a store in the successor.
10337///
10338/// Simplify things like:
10339/// *P = v1; if () { *P = v2; }
10340/// into a phi node with a store in the successor.
10341///
10342bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10343 BasicBlock *StoreBB = SI.getParent();
10344
10345 // Check to see if the successor block has exactly two incoming edges. If
10346 // so, see if the other predecessor contains a store to the same location.
10347 // if so, insert a PHI node (if needed) and move the stores down.
10348 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10349
10350 // Determine whether Dest has exactly two predecessors and, if so, compute
10351 // the other predecessor.
10352 pred_iterator PI = pred_begin(DestBB);
10353 BasicBlock *OtherBB = 0;
10354 if (*PI != StoreBB)
10355 OtherBB = *PI;
10356 ++PI;
10357 if (PI == pred_end(DestBB))
10358 return false;
10359
10360 if (*PI != StoreBB) {
10361 if (OtherBB)
10362 return false;
10363 OtherBB = *PI;
10364 }
10365 if (++PI != pred_end(DestBB))
10366 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000010367
10368 // Bail out if all the relevant blocks aren't distinct (this can happen,
10369 // for example, if SI is in an infinite loop)
10370 if (StoreBB == DestBB || OtherBB == DestBB)
10371 return false;
10372
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010373 // Verify that the other block ends in a branch and is not otherwise empty.
10374 BasicBlock::iterator BBI = OtherBB->getTerminator();
10375 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10376 if (!OtherBr || BBI == OtherBB->begin())
10377 return false;
10378
10379 // If the other block ends in an unconditional branch, check for the 'if then
10380 // else' case. there is an instruction before the branch.
10381 StoreInst *OtherStore = 0;
10382 if (OtherBr->isUnconditional()) {
10383 // If this isn't a store, or isn't a store to the same location, bail out.
10384 --BBI;
10385 OtherStore = dyn_cast<StoreInst>(BBI);
10386 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10387 return false;
10388 } else {
10389 // Otherwise, the other block ended with a conditional branch. If one of the
10390 // destinations is StoreBB, then we have the if/then case.
10391 if (OtherBr->getSuccessor(0) != StoreBB &&
10392 OtherBr->getSuccessor(1) != StoreBB)
10393 return false;
10394
10395 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10396 // if/then triangle. See if there is a store to the same ptr as SI that
10397 // lives in OtherBB.
10398 for (;; --BBI) {
10399 // Check to see if we find the matching store.
10400 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10401 if (OtherStore->getOperand(1) != SI.getOperand(1))
10402 return false;
10403 break;
10404 }
Eli Friedman3a311d52008-06-13 22:02:12 +000010405 // If we find something that may be using or overwriting the stored
10406 // value, or if we run out of instructions, we can't do the xform.
10407 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010408 BBI == OtherBB->begin())
10409 return false;
10410 }
10411
10412 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000010413 // make sure nothing reads or overwrites the stored value in
10414 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010415 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10416 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000010417 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010418 return false;
10419 }
10420 }
10421
10422 // Insert a PHI node now if we need it.
10423 Value *MergedVal = OtherStore->getOperand(0);
10424 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010425 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010426 PN->reserveOperandSpace(2);
10427 PN->addIncoming(SI.getOperand(0), SI.getParent());
10428 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10429 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10430 }
10431
10432 // Advance to a place where it is safe to insert the new store and
10433 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000010434 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010435 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10436 OtherStore->isVolatile()), *BBI);
10437
10438 // Nuke the old stores.
10439 EraseInstFromFunction(SI);
10440 EraseInstFromFunction(*OtherStore);
10441 ++NumCombined;
10442 return true;
10443}
10444
10445
10446Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10447 // Change br (not X), label True, label False to: br X, label False, True
10448 Value *X = 0;
10449 BasicBlock *TrueDest;
10450 BasicBlock *FalseDest;
10451 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10452 !isa<Constant>(X)) {
10453 // Swap Destinations and condition...
10454 BI.setCondition(X);
10455 BI.setSuccessor(0, FalseDest);
10456 BI.setSuccessor(1, TrueDest);
10457 return &BI;
10458 }
10459
10460 // Cannonicalize fcmp_one -> fcmp_oeq
10461 FCmpInst::Predicate FPred; Value *Y;
10462 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10463 TrueDest, FalseDest)))
10464 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10465 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10466 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10467 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10468 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10469 NewSCC->takeName(I);
10470 // Swap Destinations and condition...
10471 BI.setCondition(NewSCC);
10472 BI.setSuccessor(0, FalseDest);
10473 BI.setSuccessor(1, TrueDest);
10474 RemoveFromWorkList(I);
10475 I->eraseFromParent();
10476 AddToWorkList(NewSCC);
10477 return &BI;
10478 }
10479
10480 // Cannonicalize icmp_ne -> icmp_eq
10481 ICmpInst::Predicate IPred;
10482 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10483 TrueDest, FalseDest)))
10484 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10485 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10486 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10487 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10488 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10489 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10490 NewSCC->takeName(I);
10491 // Swap Destinations and condition...
10492 BI.setCondition(NewSCC);
10493 BI.setSuccessor(0, FalseDest);
10494 BI.setSuccessor(1, TrueDest);
10495 RemoveFromWorkList(I);
10496 I->eraseFromParent();;
10497 AddToWorkList(NewSCC);
10498 return &BI;
10499 }
10500
10501 return 0;
10502}
10503
10504Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10505 Value *Cond = SI.getCondition();
10506 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10507 if (I->getOpcode() == Instruction::Add)
10508 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10509 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10510 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10511 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10512 AddRHS));
10513 SI.setOperand(0, I->getOperand(0));
10514 AddToWorkList(I);
10515 return &SI;
10516 }
10517 }
10518 return 0;
10519}
10520
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010521Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10522 // See if we are trying to extract a known value. If so, use that instead.
Matthijs Kooijman3d328112008-06-16 12:57:37 +000010523 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10524 EV.idx_end(), EV))
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010525 return ReplaceInstUsesWith(EV, Elt);
10526
10527 // No changes
10528 return 0;
10529}
10530
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010531/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10532/// is to leave as a vector operation.
10533static bool CheapToScalarize(Value *V, bool isConstant) {
10534 if (isa<ConstantAggregateZero>(V))
10535 return true;
10536 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10537 if (isConstant) return true;
10538 // If all elts are the same, we can extract.
10539 Constant *Op0 = C->getOperand(0);
10540 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10541 if (C->getOperand(i) != Op0)
10542 return false;
10543 return true;
10544 }
10545 Instruction *I = dyn_cast<Instruction>(V);
10546 if (!I) return false;
10547
10548 // Insert element gets simplified to the inserted element or is deleted if
10549 // this is constant idx extract element and its a constant idx insertelt.
10550 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10551 isa<ConstantInt>(I->getOperand(2)))
10552 return true;
10553 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10554 return true;
10555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10556 if (BO->hasOneUse() &&
10557 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10558 CheapToScalarize(BO->getOperand(1), isConstant)))
10559 return true;
10560 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10561 if (CI->hasOneUse() &&
10562 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10563 CheapToScalarize(CI->getOperand(1), isConstant)))
10564 return true;
10565
10566 return false;
10567}
10568
10569/// Read and decode a shufflevector mask.
10570///
10571/// It turns undef elements into values that are larger than the number of
10572/// elements in the input.
10573static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10574 unsigned NElts = SVI->getType()->getNumElements();
10575 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10576 return std::vector<unsigned>(NElts, 0);
10577 if (isa<UndefValue>(SVI->getOperand(2)))
10578 return std::vector<unsigned>(NElts, 2*NElts);
10579
10580 std::vector<unsigned> Result;
10581 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000010582 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10583 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010584 Result.push_back(NElts*2); // undef -> 8
10585 else
Gabor Greif17396002008-06-12 21:37:33 +000010586 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010587 return Result;
10588}
10589
10590/// FindScalarElement - Given a vector and an element number, see if the scalar
10591/// value is already around as a register, for example if it were inserted then
10592/// extracted from the vector.
10593static Value *FindScalarElement(Value *V, unsigned EltNo) {
10594 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10595 const VectorType *PTy = cast<VectorType>(V->getType());
10596 unsigned Width = PTy->getNumElements();
10597 if (EltNo >= Width) // Out of range access.
10598 return UndefValue::get(PTy->getElementType());
10599
10600 if (isa<UndefValue>(V))
10601 return UndefValue::get(PTy->getElementType());
10602 else if (isa<ConstantAggregateZero>(V))
10603 return Constant::getNullValue(PTy->getElementType());
10604 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10605 return CP->getOperand(EltNo);
10606 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10607 // If this is an insert to a variable element, we don't know what it is.
10608 if (!isa<ConstantInt>(III->getOperand(2)))
10609 return 0;
10610 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10611
10612 // If this is an insert to the element we are looking for, return the
10613 // inserted value.
10614 if (EltNo == IIElt)
10615 return III->getOperand(1);
10616
10617 // Otherwise, the insertelement doesn't modify the value, recurse on its
10618 // vector input.
10619 return FindScalarElement(III->getOperand(0), EltNo);
10620 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10621 unsigned InEl = getShuffleMask(SVI)[EltNo];
10622 if (InEl < Width)
10623 return FindScalarElement(SVI->getOperand(0), InEl);
10624 else if (InEl < Width*2)
10625 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10626 else
10627 return UndefValue::get(PTy->getElementType());
10628 }
10629
10630 // Otherwise, we don't know.
10631 return 0;
10632}
10633
10634Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010635 // If vector val is undef, replace extract with scalar undef.
10636 if (isa<UndefValue>(EI.getOperand(0)))
10637 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10638
10639 // If vector val is constant 0, replace extract with scalar 0.
10640 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10641 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10642
10643 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000010644 // If vector val is constant with all elements the same, replace EI with
10645 // that element. When the elements are not identical, we cannot replace yet
10646 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010647 Constant *op0 = C->getOperand(0);
10648 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10649 if (C->getOperand(i) != op0) {
10650 op0 = 0;
10651 break;
10652 }
10653 if (op0)
10654 return ReplaceInstUsesWith(EI, op0);
10655 }
10656
10657 // If extracting a specified index from the vector, see if we can recursively
10658 // find a previously computed scalar that was inserted into the vector.
10659 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10660 unsigned IndexVal = IdxC->getZExtValue();
10661 unsigned VectorWidth =
10662 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10663
10664 // If this is extracting an invalid index, turn this into undef, to avoid
10665 // crashing the code below.
10666 if (IndexVal >= VectorWidth)
10667 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10668
10669 // This instruction only demands the single element from the input vector.
10670 // If the input vector has a single use, simplify it based on this use
10671 // property.
10672 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10673 uint64_t UndefElts;
10674 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10675 1 << IndexVal,
10676 UndefElts)) {
10677 EI.setOperand(0, V);
10678 return &EI;
10679 }
10680 }
10681
10682 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10683 return ReplaceInstUsesWith(EI, Elt);
10684
10685 // If the this extractelement is directly using a bitcast from a vector of
10686 // the same number of elements, see if we can find the source element from
10687 // it. In this case, we will end up needing to bitcast the scalars.
10688 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10689 if (const VectorType *VT =
10690 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10691 if (VT->getNumElements() == VectorWidth)
10692 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10693 return new BitCastInst(Elt, EI.getType());
10694 }
10695 }
10696
10697 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10698 if (I->hasOneUse()) {
10699 // Push extractelement into predecessor operation if legal and
10700 // profitable to do so
10701 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10702 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10703 if (CheapToScalarize(BO, isConstantElt)) {
10704 ExtractElementInst *newEI0 =
10705 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10706 EI.getName()+".lhs");
10707 ExtractElementInst *newEI1 =
10708 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10709 EI.getName()+".rhs");
10710 InsertNewInstBefore(newEI0, EI);
10711 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000010712 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010713 }
10714 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010715 unsigned AS =
10716 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010717 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10718 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010719 GetElementPtrInst *GEP =
10720 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010721 InsertNewInstBefore(GEP, EI);
10722 return new LoadInst(GEP);
10723 }
10724 }
10725 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10726 // Extracting the inserted element?
10727 if (IE->getOperand(2) == EI.getOperand(1))
10728 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10729 // If the inserted and extracted elements are constants, they must not
10730 // be the same value, extract from the pre-inserted value instead.
10731 if (isa<Constant>(IE->getOperand(2)) &&
10732 isa<Constant>(EI.getOperand(1))) {
10733 AddUsesToWorkList(EI);
10734 EI.setOperand(0, IE->getOperand(0));
10735 return &EI;
10736 }
10737 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10738 // If this is extracting an element from a shufflevector, figure out where
10739 // it came from and extract from the appropriate input element instead.
10740 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10741 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10742 Value *Src;
10743 if (SrcIdx < SVI->getType()->getNumElements())
10744 Src = SVI->getOperand(0);
10745 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10746 SrcIdx -= SVI->getType()->getNumElements();
10747 Src = SVI->getOperand(1);
10748 } else {
10749 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10750 }
10751 return new ExtractElementInst(Src, SrcIdx);
10752 }
10753 }
10754 }
10755 return 0;
10756}
10757
10758/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10759/// elements from either LHS or RHS, return the shuffle mask and true.
10760/// Otherwise, return false.
10761static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10762 std::vector<Constant*> &Mask) {
10763 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10764 "Invalid CollectSingleShuffleElements");
10765 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10766
10767 if (isa<UndefValue>(V)) {
10768 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10769 return true;
10770 } else if (V == LHS) {
10771 for (unsigned i = 0; i != NumElts; ++i)
10772 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10773 return true;
10774 } else if (V == RHS) {
10775 for (unsigned i = 0; i != NumElts; ++i)
10776 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10777 return true;
10778 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10779 // If this is an insert of an extract from some other vector, include it.
10780 Value *VecOp = IEI->getOperand(0);
10781 Value *ScalarOp = IEI->getOperand(1);
10782 Value *IdxOp = IEI->getOperand(2);
10783
10784 if (!isa<ConstantInt>(IdxOp))
10785 return false;
10786 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10787
10788 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10789 // Okay, we can handle this if the vector we are insertinting into is
10790 // transitively ok.
10791 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10792 // If so, update the mask to reflect the inserted undef.
10793 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10794 return true;
10795 }
10796 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10797 if (isa<ConstantInt>(EI->getOperand(1)) &&
10798 EI->getOperand(0)->getType() == V->getType()) {
10799 unsigned ExtractedIdx =
10800 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10801
10802 // This must be extracting from either LHS or RHS.
10803 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10804 // Okay, we can handle this if the vector we are insertinting into is
10805 // transitively ok.
10806 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10807 // If so, update the mask to reflect the inserted value.
10808 if (EI->getOperand(0) == LHS) {
10809 Mask[InsertedIdx & (NumElts-1)] =
10810 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10811 } else {
10812 assert(EI->getOperand(0) == RHS);
10813 Mask[InsertedIdx & (NumElts-1)] =
10814 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10815
10816 }
10817 return true;
10818 }
10819 }
10820 }
10821 }
10822 }
10823 // TODO: Handle shufflevector here!
10824
10825 return false;
10826}
10827
10828/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10829/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10830/// that computes V and the LHS value of the shuffle.
10831static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10832 Value *&RHS) {
10833 assert(isa<VectorType>(V->getType()) &&
10834 (RHS == 0 || V->getType() == RHS->getType()) &&
10835 "Invalid shuffle!");
10836 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10837
10838 if (isa<UndefValue>(V)) {
10839 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10840 return V;
10841 } else if (isa<ConstantAggregateZero>(V)) {
10842 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10843 return V;
10844 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10845 // If this is an insert of an extract from some other vector, include it.
10846 Value *VecOp = IEI->getOperand(0);
10847 Value *ScalarOp = IEI->getOperand(1);
10848 Value *IdxOp = IEI->getOperand(2);
10849
10850 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10851 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10852 EI->getOperand(0)->getType() == V->getType()) {
10853 unsigned ExtractedIdx =
10854 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10855 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10856
10857 // Either the extracted from or inserted into vector must be RHSVec,
10858 // otherwise we'd end up with a shuffle of three inputs.
10859 if (EI->getOperand(0) == RHS || RHS == 0) {
10860 RHS = EI->getOperand(0);
10861 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10862 Mask[InsertedIdx & (NumElts-1)] =
10863 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10864 return V;
10865 }
10866
10867 if (VecOp == RHS) {
10868 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10869 // Everything but the extracted element is replaced with the RHS.
10870 for (unsigned i = 0; i != NumElts; ++i) {
10871 if (i != InsertedIdx)
10872 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10873 }
10874 return V;
10875 }
10876
10877 // If this insertelement is a chain that comes from exactly these two
10878 // vectors, return the vector and the effective shuffle.
10879 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10880 return EI->getOperand(0);
10881
10882 }
10883 }
10884 }
10885 // TODO: Handle shufflevector here!
10886
10887 // Otherwise, can't do anything fancy. Return an identity vector.
10888 for (unsigned i = 0; i != NumElts; ++i)
10889 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10890 return V;
10891}
10892
10893Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10894 Value *VecOp = IE.getOperand(0);
10895 Value *ScalarOp = IE.getOperand(1);
10896 Value *IdxOp = IE.getOperand(2);
10897
10898 // Inserting an undef or into an undefined place, remove this.
10899 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10900 ReplaceInstUsesWith(IE, VecOp);
10901
10902 // If the inserted element was extracted from some other vector, and if the
10903 // indexes are constant, try to turn this into a shufflevector operation.
10904 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10905 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10906 EI->getOperand(0)->getType() == IE.getType()) {
10907 unsigned NumVectorElts = IE.getType()->getNumElements();
10908 unsigned ExtractedIdx =
10909 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10910 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10911
10912 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10913 return ReplaceInstUsesWith(IE, VecOp);
10914
10915 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10916 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10917
10918 // If we are extracting a value from a vector, then inserting it right
10919 // back into the same place, just use the input vector.
10920 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10921 return ReplaceInstUsesWith(IE, VecOp);
10922
10923 // We could theoretically do this for ANY input. However, doing so could
10924 // turn chains of insertelement instructions into a chain of shufflevector
10925 // instructions, and right now we do not merge shufflevectors. As such,
10926 // only do this in a situation where it is clear that there is benefit.
10927 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10928 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10929 // the values of VecOp, except then one read from EIOp0.
10930 // Build a new shuffle mask.
10931 std::vector<Constant*> Mask;
10932 if (isa<UndefValue>(VecOp))
10933 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10934 else {
10935 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10936 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10937 NumVectorElts));
10938 }
10939 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10940 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10941 ConstantVector::get(Mask));
10942 }
10943
10944 // If this insertelement isn't used by some other insertelement, turn it
10945 // (and any insertelements it points to), into one big shuffle.
10946 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10947 std::vector<Constant*> Mask;
10948 Value *RHS = 0;
10949 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10950 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10951 // We now have a shuffle of LHS, RHS, Mask.
10952 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10953 }
10954 }
10955 }
10956
10957 return 0;
10958}
10959
10960
10961Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10962 Value *LHS = SVI.getOperand(0);
10963 Value *RHS = SVI.getOperand(1);
10964 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10965
10966 bool MadeChange = false;
10967
10968 // Undefined shuffle mask -> undefined value.
10969 if (isa<UndefValue>(SVI.getOperand(2)))
10970 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10971
10972 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10973 // the undef, change them to undefs.
10974 if (isa<UndefValue>(SVI.getOperand(1))) {
10975 // Scan to see if there are any references to the RHS. If so, replace them
10976 // with undef element refs and set MadeChange to true.
10977 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10978 if (Mask[i] >= e && Mask[i] != 2*e) {
10979 Mask[i] = 2*e;
10980 MadeChange = true;
10981 }
10982 }
10983
10984 if (MadeChange) {
10985 // Remap any references to RHS to use LHS.
10986 std::vector<Constant*> Elts;
10987 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10988 if (Mask[i] == 2*e)
10989 Elts.push_back(UndefValue::get(Type::Int32Ty));
10990 else
10991 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10992 }
10993 SVI.setOperand(2, ConstantVector::get(Elts));
10994 }
10995 }
10996
10997 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10998 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10999 if (LHS == RHS || isa<UndefValue>(LHS)) {
11000 if (isa<UndefValue>(LHS) && LHS == RHS) {
11001 // shuffle(undef,undef,mask) -> undef.
11002 return ReplaceInstUsesWith(SVI, LHS);
11003 }
11004
11005 // Remap any references to RHS to use LHS.
11006 std::vector<Constant*> Elts;
11007 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11008 if (Mask[i] >= 2*e)
11009 Elts.push_back(UndefValue::get(Type::Int32Ty));
11010 else {
11011 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11012 (Mask[i] < e && isa<UndefValue>(LHS)))
11013 Mask[i] = 2*e; // Turn into undef.
11014 else
11015 Mask[i] &= (e-1); // Force to LHS.
11016 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11017 }
11018 }
11019 SVI.setOperand(0, SVI.getOperand(1));
11020 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11021 SVI.setOperand(2, ConstantVector::get(Elts));
11022 LHS = SVI.getOperand(0);
11023 RHS = SVI.getOperand(1);
11024 MadeChange = true;
11025 }
11026
11027 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11028 bool isLHSID = true, isRHSID = true;
11029
11030 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11031 if (Mask[i] >= e*2) continue; // Ignore undef values.
11032 // Is this an identity shuffle of the LHS value?
11033 isLHSID &= (Mask[i] == i);
11034
11035 // Is this an identity shuffle of the RHS value?
11036 isRHSID &= (Mask[i]-e == i);
11037 }
11038
11039 // Eliminate identity shuffles.
11040 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11041 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11042
11043 // If the LHS is a shufflevector itself, see if we can combine it with this
11044 // one without producing an unusual shuffle. Here we are really conservative:
11045 // we are absolutely afraid of producing a shuffle mask not in the input
11046 // program, because the code gen may not be smart enough to turn a merged
11047 // shuffle into two specific shuffles: it may produce worse code. As such,
11048 // we only merge two shuffles if the result is one of the two input shuffle
11049 // masks. In this case, merging the shuffles just removes one instruction,
11050 // which we know is safe. This is good for things like turning:
11051 // (splat(splat)) -> splat.
11052 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11053 if (isa<UndefValue>(RHS)) {
11054 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11055
11056 std::vector<unsigned> NewMask;
11057 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11058 if (Mask[i] >= 2*e)
11059 NewMask.push_back(2*e);
11060 else
11061 NewMask.push_back(LHSMask[Mask[i]]);
11062
11063 // If the result mask is equal to the src shuffle or this shuffle mask, do
11064 // the replacement.
11065 if (NewMask == LHSMask || NewMask == Mask) {
11066 std::vector<Constant*> Elts;
11067 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11068 if (NewMask[i] >= e*2) {
11069 Elts.push_back(UndefValue::get(Type::Int32Ty));
11070 } else {
11071 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11072 }
11073 }
11074 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11075 LHSSVI->getOperand(1),
11076 ConstantVector::get(Elts));
11077 }
11078 }
11079 }
11080
11081 return MadeChange ? &SVI : 0;
11082}
11083
11084
11085
11086
11087/// TryToSinkInstruction - Try to move the specified instruction from its
11088/// current block into the beginning of DestBlock, which can only happen if it's
11089/// safe to move the instruction past all of the instructions between it and the
11090/// end of its block.
11091static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11092 assert(I->hasOneUse() && "Invariants didn't hold!");
11093
11094 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011095 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11096 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011097
11098 // Do not sink alloca instructions out of the entry block.
11099 if (isa<AllocaInst>(I) && I->getParent() ==
11100 &DestBlock->getParent()->getEntryBlock())
11101 return false;
11102
11103 // We can only sink load instructions if there is nothing between the load and
11104 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011105 if (I->mayReadFromMemory()) {
11106 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011107 Scan != E; ++Scan)
11108 if (Scan->mayWriteToMemory())
11109 return false;
11110 }
11111
Dan Gohman514277c2008-05-23 21:05:58 +000011112 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011113
11114 I->moveBefore(InsertPos);
11115 ++NumSunkInst;
11116 return true;
11117}
11118
11119
11120/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11121/// all reachable code to the worklist.
11122///
11123/// This has a couple of tricks to make the code faster and more powerful. In
11124/// particular, we constant fold and DCE instructions as we go, to avoid adding
11125/// them to the worklist (this significantly speeds up instcombine on code where
11126/// many instructions are dead or constant). Additionally, if we find a branch
11127/// whose condition is a known constant, we only visit the reachable successors.
11128///
11129static void AddReachableCodeToWorklist(BasicBlock *BB,
11130 SmallPtrSet<BasicBlock*, 64> &Visited,
11131 InstCombiner &IC,
11132 const TargetData *TD) {
11133 std::vector<BasicBlock*> Worklist;
11134 Worklist.push_back(BB);
11135
11136 while (!Worklist.empty()) {
11137 BB = Worklist.back();
11138 Worklist.pop_back();
11139
11140 // We have now visited this block! If we've already been here, ignore it.
11141 if (!Visited.insert(BB)) continue;
11142
11143 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11144 Instruction *Inst = BBI++;
11145
11146 // DCE instruction if trivially dead.
11147 if (isInstructionTriviallyDead(Inst)) {
11148 ++NumDeadInst;
11149 DOUT << "IC: DCE: " << *Inst;
11150 Inst->eraseFromParent();
11151 continue;
11152 }
11153
11154 // ConstantProp instruction if trivially constant.
11155 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11156 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11157 Inst->replaceAllUsesWith(C);
11158 ++NumConstProp;
11159 Inst->eraseFromParent();
11160 continue;
11161 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011162
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011163 IC.AddToWorkList(Inst);
11164 }
11165
11166 // Recursively visit successors. If this is a branch or switch on a
11167 // constant, only visit the reachable successor.
11168 TerminatorInst *TI = BB->getTerminator();
11169 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11170 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11171 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011172 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011173 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011174 continue;
11175 }
11176 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11177 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11178 // See if this is an explicit destination.
11179 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11180 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011181 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011182 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011183 continue;
11184 }
11185
11186 // Otherwise it is the default destination.
11187 Worklist.push_back(SI->getSuccessor(0));
11188 continue;
11189 }
11190 }
11191
11192 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11193 Worklist.push_back(TI->getSuccessor(i));
11194 }
11195}
11196
11197bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11198 bool Changed = false;
11199 TD = &getAnalysis<TargetData>();
11200
11201 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11202 << F.getNameStr() << "\n");
11203
11204 {
11205 // Do a depth-first traversal of the function, populate the worklist with
11206 // the reachable instructions. Ignore blocks that are not reachable. Keep
11207 // track of which blocks we visit.
11208 SmallPtrSet<BasicBlock*, 64> Visited;
11209 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11210
11211 // Do a quick scan over the function. If we find any blocks that are
11212 // unreachable, remove any instructions inside of them. This prevents
11213 // the instcombine code from having to deal with some bad special cases.
11214 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11215 if (!Visited.count(BB)) {
11216 Instruction *Term = BB->getTerminator();
11217 while (Term != BB->begin()) { // Remove instrs bottom-up
11218 BasicBlock::iterator I = Term; --I;
11219
11220 DOUT << "IC: DCE: " << *I;
11221 ++NumDeadInst;
11222
11223 if (!I->use_empty())
11224 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11225 I->eraseFromParent();
11226 }
11227 }
11228 }
11229
11230 while (!Worklist.empty()) {
11231 Instruction *I = RemoveOneFromWorkList();
11232 if (I == 0) continue; // skip null values.
11233
11234 // Check to see if we can DCE the instruction.
11235 if (isInstructionTriviallyDead(I)) {
11236 // Add operands to the worklist.
11237 if (I->getNumOperands() < 4)
11238 AddUsesToWorkList(*I);
11239 ++NumDeadInst;
11240
11241 DOUT << "IC: DCE: " << *I;
11242
11243 I->eraseFromParent();
11244 RemoveFromWorkList(I);
11245 continue;
11246 }
11247
11248 // Instruction isn't dead, see if we can constant propagate it.
11249 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11250 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11251
11252 // Add operands to the worklist.
11253 AddUsesToWorkList(*I);
11254 ReplaceInstUsesWith(*I, C);
11255
11256 ++NumConstProp;
11257 I->eraseFromParent();
11258 RemoveFromWorkList(I);
11259 continue;
11260 }
11261
Nick Lewyckyadb67922008-05-25 20:56:15 +000011262 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11263 // See if we can constant fold its operands.
11264 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11265 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11266 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11267 i->set(NewC);
11268 }
11269 }
11270 }
11271
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011272 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011273 // FIXME: Remove GetResultInst test when first class support for aggregates
11274 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011275 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011276 BasicBlock *BB = I->getParent();
11277 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11278 if (UserParent != BB) {
11279 bool UserIsSuccessor = false;
11280 // See if the user is one of our successors.
11281 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11282 if (*SI == UserParent) {
11283 UserIsSuccessor = true;
11284 break;
11285 }
11286
11287 // If the user is one of our immediate successors, and if that successor
11288 // only has us as a predecessors (we'd have to split the critical edge
11289 // otherwise), we can keep going.
11290 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11291 next(pred_begin(UserParent)) == pred_end(UserParent))
11292 // Okay, the CFG is simple enough, try to sink this instruction.
11293 Changed |= TryToSinkInstruction(I, UserParent);
11294 }
11295 }
11296
11297 // Now that we have an instruction, try combining it to simplify it...
11298#ifndef NDEBUG
11299 std::string OrigI;
11300#endif
11301 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11302 if (Instruction *Result = visit(*I)) {
11303 ++NumCombined;
11304 // Should we replace the old instruction with a new one?
11305 if (Result != I) {
11306 DOUT << "IC: Old = " << *I
11307 << " New = " << *Result;
11308
11309 // Everything uses the new instruction now.
11310 I->replaceAllUsesWith(Result);
11311
11312 // Push the new instruction and any users onto the worklist.
11313 AddToWorkList(Result);
11314 AddUsersToWorkList(*Result);
11315
11316 // Move the name to the new instruction first.
11317 Result->takeName(I);
11318
11319 // Insert the new instruction into the basic block...
11320 BasicBlock *InstParent = I->getParent();
11321 BasicBlock::iterator InsertPos = I;
11322
11323 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11324 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11325 ++InsertPos;
11326
11327 InstParent->getInstList().insert(InsertPos, Result);
11328
11329 // Make sure that we reprocess all operands now that we reduced their
11330 // use counts.
11331 AddUsesToWorkList(*I);
11332
11333 // Instructions can end up on the worklist more than once. Make sure
11334 // we do not process an instruction that has been deleted.
11335 RemoveFromWorkList(I);
11336
11337 // Erase the old instruction.
11338 InstParent->getInstList().erase(I);
11339 } else {
11340#ifndef NDEBUG
11341 DOUT << "IC: Mod = " << OrigI
11342 << " New = " << *I;
11343#endif
11344
11345 // If the instruction was modified, it's possible that it is now dead.
11346 // if so, remove it.
11347 if (isInstructionTriviallyDead(I)) {
11348 // Make sure we process all operands now that we are reducing their
11349 // use counts.
11350 AddUsesToWorkList(*I);
11351
11352 // Instructions may end up in the worklist more than once. Erase all
11353 // occurrences of this instruction.
11354 RemoveFromWorkList(I);
11355 I->eraseFromParent();
11356 } else {
11357 AddToWorkList(I);
11358 AddUsersToWorkList(*I);
11359 }
11360 }
11361 Changed = true;
11362 }
11363 }
11364
11365 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011366
11367 // Do an explicit clear, this shrinks the map if needed.
11368 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011369 return Changed;
11370}
11371
11372
11373bool InstCombiner::runOnFunction(Function &F) {
11374 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11375
11376 bool EverMadeChange = false;
11377
11378 // Iterate while there is work to do.
11379 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011380 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011381 EverMadeChange = true;
11382 return EverMadeChange;
11383}
11384
11385FunctionPass *llvm::createInstructionCombiningPass() {
11386 return new InstCombiner();
11387}
11388