blob: f02a7108fd6d7d5db7ca3c6c4dd2ff8fcd6f4f8d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
38#include "llvm/IntrinsicInst.h"
39#include "llvm/Pass.h"
40#include "llvm/DerivedTypes.h"
41#include "llvm/GlobalVariable.h"
42#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000061#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include <sstream>
63using namespace llvm;
64using namespace llvm::PatternMatch;
65
66STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72namespace {
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
79 TargetData *TD;
80 bool MustPreserveLCSSA;
81 public:
82 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
109
110
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 UI != UE; ++UI)
118 AddToWorkList(cast<Instruction>(*UI));
119 }
120
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 AddToWorkList(Op);
128 }
129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif17396002008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
Gabor Greif17396002008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
145
146 return R;
147 }
148
149 public:
150 virtual bool runOnFunction(Function &F);
151
152 bool DoOneIteration(Function &F, unsigned ItNum);
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
158 }
159
160 TargetData &getTargetData() const { return *TD; }
161
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
168 //
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
183 Instruction *visitAnd(BinaryOperator &I);
184 Instruction *visitOr (BinaryOperator &I);
185 Instruction *visitXor(BinaryOperator &I);
186 Instruction *visitShl(BinaryOperator &I);
187 Instruction *visitAShr(BinaryOperator &I);
188 Instruction *visitLShr(BinaryOperator &I);
189 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000190 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196 Instruction *LHS,
197 ConstantInt *RHS);
198 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199 ConstantInt *DivRHS);
200
201 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
203 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
204 BinaryOperator &I);
205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonIntCastTransforms(CastInst &CI);
207 Instruction *commonPointerCastTransforms(CastInst &CI);
208 Instruction *visitTrunc(TruncInst &CI);
209 Instruction *visitZExt(ZExtInst &CI);
210 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000211 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000213 Instruction *visitFPToUI(FPToUIInst &FI);
214 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 Instruction *visitUIToFP(CastInst &CI);
216 Instruction *visitSIToFP(CastInst &CI);
217 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000218 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitBitCast(BitCastInst &CI);
220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221 Instruction *FI);
222 Instruction *visitSelectInst(SelectInst &CI);
223 Instruction *visitCallInst(CallInst &CI);
224 Instruction *visitInvokeInst(InvokeInst &II);
225 Instruction *visitPHINode(PHINode &PN);
226 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
227 Instruction *visitAllocationInst(AllocationInst &AI);
228 Instruction *visitFreeInst(FreeInst &FI);
229 Instruction *visitLoadInst(LoadInst &LI);
230 Instruction *visitStoreInst(StoreInst &SI);
231 Instruction *visitBranchInst(BranchInst &BI);
232 Instruction *visitSwitchInst(SwitchInst &SI);
233 Instruction *visitInsertElementInst(InsertElementInst &IE);
234 Instruction *visitExtractElementInst(ExtractElementInst &EI);
235 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000236 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237
238 // visitInstruction - Specify what to return for unhandled instructions...
239 Instruction *visitInstruction(Instruction &I) { return 0; }
240
241 private:
242 Instruction *visitCallSite(CallSite CS);
243 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000244 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000245 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
246 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000247 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248
249 public:
250 // InsertNewInstBefore - insert an instruction New before instruction Old
251 // in the program. Add the new instruction to the worklist.
252 //
253 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
254 assert(New && New->getParent() == 0 &&
255 "New instruction already inserted into a basic block!");
256 BasicBlock *BB = Old.getParent();
257 BB->getInstList().insert(&Old, New); // Insert inst
258 AddToWorkList(New);
259 return New;
260 }
261
262 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
263 /// This also adds the cast to the worklist. Finally, this returns the
264 /// cast.
265 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
266 Instruction &Pos) {
267 if (V->getType() == Ty) return V;
268
269 if (Constant *CV = dyn_cast<Constant>(V))
270 return ConstantExpr::getCast(opc, CV, Ty);
271
Gabor Greifa645dd32008-05-16 19:29:10 +0000272 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 AddToWorkList(C);
274 return C;
275 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000276
277 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
278 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
279 }
280
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281
282 // ReplaceInstUsesWith - This method is to be used when an instruction is
283 // found to be dead, replacable with another preexisting expression. Here
284 // we add all uses of I to the worklist, replace all uses of I with the new
285 // value, then return I, so that the inst combiner will know that I was
286 // modified.
287 //
288 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
289 AddUsersToWorkList(I); // Add all modified instrs to worklist
290 if (&I != V) {
291 I.replaceAllUsesWith(V);
292 return &I;
293 } else {
294 // If we are replacing the instruction with itself, this must be in a
295 // segment of unreachable code, so just clobber the instruction.
296 I.replaceAllUsesWith(UndefValue::get(I.getType()));
297 return &I;
298 }
299 }
300
301 // UpdateValueUsesWith - This method is to be used when an value is
302 // found to be replacable with another preexisting expression or was
303 // updated. Here we add all uses of I to the worklist, replace all uses of
304 // I with the new value (unless the instruction was just updated), then
305 // return true, so that the inst combiner will know that I was modified.
306 //
307 bool UpdateValueUsesWith(Value *Old, Value *New) {
308 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
309 if (Old != New)
310 Old->replaceAllUsesWith(New);
311 if (Instruction *I = dyn_cast<Instruction>(Old))
312 AddToWorkList(I);
313 if (Instruction *I = dyn_cast<Instruction>(New))
314 AddToWorkList(I);
315 return true;
316 }
317
318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
321 // this function.
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
325 RemoveFromWorkList(&I);
326 I.eraseFromParent();
327 return 0; // Don't do anything with FI
328 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000329
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333 }
334
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 }
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
341 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342
343 private:
344 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
345 /// InsertBefore instruction. This is specialized a bit to avoid inserting
346 /// casts that are known to not do anything...
347 ///
348 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
349 Value *V, const Type *DestTy,
350 Instruction *InsertBefore);
351
352 /// SimplifyCommutative - This performs a few simplifications for
353 /// commutative operators.
354 bool SimplifyCommutative(BinaryOperator &I);
355
356 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
357 /// most-complex to least-complex order.
358 bool SimplifyCompare(CmpInst &I);
359
360 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
361 /// on the demanded bits.
362 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
363 APInt& KnownZero, APInt& KnownOne,
364 unsigned Depth = 0);
365
366 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
367 uint64_t &UndefElts, unsigned Depth = 0);
368
369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
373
374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
379
380
381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
383
384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385 bool isSub, Instruction &I);
386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387 bool isSigned, bool Inside, Instruction &IB);
388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389 Instruction *MatchBSwap(BinaryOperator &I);
390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000393
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394
395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000396
Dan Gohman2d648bb2008-04-10 18:43:06 +0000397 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
398 unsigned CastOpc,
399 int &NumCastsRemoved);
400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000402
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404}
405
Dan Gohman089efff2008-05-13 00:00:25 +0000406char InstCombiner::ID = 0;
407static RegisterPass<InstCombiner>
408X("instcombine", "Combine redundant instructions");
409
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410// getComplexity: Assign a complexity or rank value to LLVM Values...
411// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412static unsigned getComplexity(Value *V) {
413 if (isa<Instruction>(V)) {
414 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
415 return 3;
416 return 4;
417 }
418 if (isa<Argument>(V)) return 3;
419 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
420}
421
422// isOnlyUse - Return true if this instruction will be deleted if we stop using
423// it.
424static bool isOnlyUse(Value *V) {
425 return V->hasOneUse() || isa<Constant>(V);
426}
427
428// getPromotedType - Return the specified type promoted as it would be to pass
429// though a va_arg area...
430static const Type *getPromotedType(const Type *Ty) {
431 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432 if (ITy->getBitWidth() < 32)
433 return Type::Int32Ty;
434 }
435 return Ty;
436}
437
438/// getBitCastOperand - If the specified operand is a CastInst or a constant
439/// expression bitcast, return the operand value, otherwise return null.
440static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442 return I->getOperand(0);
443 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
444 if (CE->getOpcode() == Instruction::BitCast)
445 return CE->getOperand(0);
446 return 0;
447}
448
449/// This function is a wrapper around CastInst::isEliminableCastPair. It
450/// simply extracts arguments and returns what that function returns.
451static Instruction::CastOps
452isEliminableCastPair(
453 const CastInst *CI, ///< The first cast instruction
454 unsigned opcode, ///< The opcode of the second cast instruction
455 const Type *DstTy, ///< The target type for the second cast instruction
456 TargetData *TD ///< The target data for pointer size
457) {
458
459 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
460 const Type *MidTy = CI->getType(); // B from above
461
462 // Get the opcodes of the two Cast instructions
463 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
464 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
465
466 return Instruction::CastOps(
467 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
468 DstTy, TD->getIntPtrType()));
469}
470
471/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
472/// in any code being generated. It does not require codegen if V is simple
473/// enough or if the cast can be folded into other casts.
474static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
475 const Type *Ty, TargetData *TD) {
476 if (V->getType() == Ty || isa<Constant>(V)) return false;
477
478 // If this is another cast that can be eliminated, it isn't codegen either.
479 if (const CastInst *CI = dyn_cast<CastInst>(V))
480 if (isEliminableCastPair(CI, opcode, Ty, TD))
481 return false;
482 return true;
483}
484
485/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
486/// InsertBefore instruction. This is specialized a bit to avoid inserting
487/// casts that are known to not do anything...
488///
489Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
490 Value *V, const Type *DestTy,
491 Instruction *InsertBefore) {
492 if (V->getType() == DestTy) return V;
493 if (Constant *C = dyn_cast<Constant>(V))
494 return ConstantExpr::getCast(opcode, C, DestTy);
495
496 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
497}
498
499// SimplifyCommutative - This performs a few simplifications for commutative
500// operators:
501//
502// 1. Order operands such that they are listed from right (least complex) to
503// left (most complex). This puts constants before unary operators before
504// binary operators.
505//
506// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
508//
509bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
510 bool Changed = false;
511 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
512 Changed = !I.swapOperands();
513
514 if (!I.isAssociative()) return Changed;
515 Instruction::BinaryOps Opcode = I.getOpcode();
516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518 if (isa<Constant>(I.getOperand(1))) {
519 Constant *Folded = ConstantExpr::get(I.getOpcode(),
520 cast<Constant>(I.getOperand(1)),
521 cast<Constant>(Op->getOperand(1)));
522 I.setOperand(0, Op->getOperand(0));
523 I.setOperand(1, Folded);
524 return true;
525 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527 isOnlyUse(Op) && isOnlyUse(Op1)) {
528 Constant *C1 = cast<Constant>(Op->getOperand(1));
529 Constant *C2 = cast<Constant>(Op1->getOperand(1));
530
531 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000533 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 Op1->getOperand(0),
535 Op1->getName(), &I);
536 AddToWorkList(New);
537 I.setOperand(0, New);
538 I.setOperand(1, Folded);
539 return true;
540 }
541 }
542 return Changed;
543}
544
545/// SimplifyCompare - For a CmpInst this function just orders the operands
546/// so that theyare listed from right (least complex) to left (most complex).
547/// This puts constants before unary operators before binary operators.
548bool InstCombiner::SimplifyCompare(CmpInst &I) {
549 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
550 return false;
551 I.swapOperands();
552 // Compare instructions are not associative so there's nothing else we can do.
553 return true;
554}
555
556// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557// if the LHS is a constant zero (which is the 'negate' form).
558//
559static inline Value *dyn_castNegVal(Value *V) {
560 if (BinaryOperator::isNeg(V))
561 return BinaryOperator::getNegArgument(V);
562
563 // Constants can be considered to be negated values if they can be folded.
564 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000566
567 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568 if (C->getType()->getElementType()->isInteger())
569 return ConstantExpr::getNeg(C);
570
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 return 0;
572}
573
574static inline Value *dyn_castNotVal(Value *V) {
575 if (BinaryOperator::isNot(V))
576 return BinaryOperator::getNotArgument(V);
577
578 // Constants can be considered to be not'ed values...
579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580 return ConstantInt::get(~C->getValue());
581 return 0;
582}
583
584// dyn_castFoldableMul - If this value is a multiply that can be folded into
585// other computations (because it has a constant operand), return the
586// non-constant operand of the multiply, and set CST to point to the multiplier.
587// Otherwise, return null.
588//
589static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
590 if (V->hasOneUse() && V->getType()->isInteger())
591 if (Instruction *I = dyn_cast<Instruction>(V)) {
592 if (I->getOpcode() == Instruction::Mul)
593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
594 return I->getOperand(0);
595 if (I->getOpcode() == Instruction::Shl)
596 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
597 // The multiplier is really 1 << CST.
598 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
599 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
600 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
601 return I->getOperand(0);
602 }
603 }
604 return 0;
605}
606
607/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
608/// expression, return it.
609static User *dyn_castGetElementPtr(Value *V) {
610 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
611 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
612 if (CE->getOpcode() == Instruction::GetElementPtr)
613 return cast<User>(V);
614 return false;
615}
616
Dan Gohman2d648bb2008-04-10 18:43:06 +0000617/// getOpcode - If this is an Instruction or a ConstantExpr, return the
618/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000619static unsigned getOpcode(const Value *V) {
620 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000621 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000622 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000623 return CE->getOpcode();
624 // Use UserOp1 to mean there's no opcode.
625 return Instruction::UserOp1;
626}
627
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628/// AddOne - Add one to a ConstantInt
629static ConstantInt *AddOne(ConstantInt *C) {
630 APInt Val(C->getValue());
631 return ConstantInt::get(++Val);
632}
633/// SubOne - Subtract one from a ConstantInt
634static ConstantInt *SubOne(ConstantInt *C) {
635 APInt Val(C->getValue());
636 return ConstantInt::get(--Val);
637}
638/// Add - Add two ConstantInts together
639static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
640 return ConstantInt::get(C1->getValue() + C2->getValue());
641}
642/// And - Bitwise AND two ConstantInts together
643static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() & C2->getValue());
645}
646/// Subtract - Subtract one ConstantInt from another
647static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() - C2->getValue());
649}
650/// Multiply - Multiply two ConstantInts together
651static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() * C2->getValue());
653}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000654/// MultiplyOverflows - True if the multiply can not be expressed in an int
655/// this size.
656static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
657 uint32_t W = C1->getBitWidth();
658 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
659 if (sign) {
660 LHSExt.sext(W * 2);
661 RHSExt.sext(W * 2);
662 } else {
663 LHSExt.zext(W * 2);
664 RHSExt.zext(W * 2);
665 }
666
667 APInt MulExt = LHSExt * RHSExt;
668
669 if (sign) {
670 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672 return MulExt.slt(Min) || MulExt.sgt(Max);
673 } else
674 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
675}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677
678/// ShrinkDemandedConstant - Check to see if the specified operand of the
679/// specified instruction is a constant integer. If so, check to see if there
680/// are any bits set in the constant that are not demanded. If so, shrink the
681/// constant and return true.
682static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
683 APInt Demanded) {
684 assert(I && "No instruction?");
685 assert(OpNo < I->getNumOperands() && "Operand index too large");
686
687 // If the operand is not a constant integer, nothing to do.
688 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689 if (!OpC) return false;
690
691 // If there are no bits set that aren't demanded, nothing to do.
692 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693 if ((~Demanded & OpC->getValue()) == 0)
694 return false;
695
696 // This instruction is producing bits that are not demanded. Shrink the RHS.
697 Demanded &= OpC->getValue();
698 I->setOperand(OpNo, ConstantInt::get(Demanded));
699 return true;
700}
701
702// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
703// set of known zero and one bits, compute the maximum and minimum values that
704// could have the specified known zero and known one bits, returning them in
705// min/max.
706static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
707 const APInt& KnownZero,
708 const APInt& KnownOne,
709 APInt& Min, APInt& Max) {
710 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
711 assert(KnownZero.getBitWidth() == BitWidth &&
712 KnownOne.getBitWidth() == BitWidth &&
713 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
714 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
715 APInt UnknownBits = ~(KnownZero|KnownOne);
716
717 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718 // bit if it is unknown.
719 Min = KnownOne;
720 Max = KnownOne|UnknownBits;
721
722 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
723 Min.set(BitWidth-1);
724 Max.clear(BitWidth-1);
725 }
726}
727
728// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729// a set of known zero and one bits, compute the maximum and minimum values that
730// could have the specified known zero and known one bits, returning them in
731// min/max.
732static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000733 const APInt &KnownZero,
734 const APInt &KnownOne,
735 APInt &Min, APInt &Max) {
736 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 assert(KnownZero.getBitWidth() == BitWidth &&
738 KnownOne.getBitWidth() == BitWidth &&
739 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
740 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
741 APInt UnknownBits = ~(KnownZero|KnownOne);
742
743 // The minimum value is when the unknown bits are all zeros.
744 Min = KnownOne;
745 // The maximum value is when the unknown bits are all ones.
746 Max = KnownOne|UnknownBits;
747}
748
749/// SimplifyDemandedBits - This function attempts to replace V with a simpler
750/// value based on the demanded bits. When this function is called, it is known
751/// that only the bits set in DemandedMask of the result of V are ever used
752/// downstream. Consequently, depending on the mask and V, it may be possible
753/// to replace V with a constant or one of its operands. In such cases, this
754/// function does the replacement and returns true. In all other cases, it
755/// returns false after analyzing the expression and setting KnownOne and known
756/// to be one in the expression. KnownZero contains all the bits that are known
757/// to be zero in the expression. These are provided to potentially allow the
758/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
759/// the expression. KnownOne and KnownZero always follow the invariant that
760/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
761/// the bits in KnownOne and KnownZero may only be accurate for those bits set
762/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
763/// and KnownOne must all be the same.
764bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
765 APInt& KnownZero, APInt& KnownOne,
766 unsigned Depth) {
767 assert(V != 0 && "Null pointer of Value???");
768 assert(Depth <= 6 && "Limit Search Depth");
769 uint32_t BitWidth = DemandedMask.getBitWidth();
770 const IntegerType *VTy = cast<IntegerType>(V->getType());
771 assert(VTy->getBitWidth() == BitWidth &&
772 KnownZero.getBitWidth() == BitWidth &&
773 KnownOne.getBitWidth() == BitWidth &&
774 "Value *V, DemandedMask, KnownZero and KnownOne \
775 must have same BitWidth");
776 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
777 // We know all of the bits for a constant!
778 KnownOne = CI->getValue() & DemandedMask;
779 KnownZero = ~KnownOne & DemandedMask;
780 return false;
781 }
782
783 KnownZero.clear();
784 KnownOne.clear();
785 if (!V->hasOneUse()) { // Other users may use these bits.
786 if (Depth != 0) { // Not at the root.
787 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
788 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
789 return false;
790 }
791 // If this is the root being simplified, allow it to have multiple uses,
792 // just set the DemandedMask to all bits.
793 DemandedMask = APInt::getAllOnesValue(BitWidth);
794 } else if (DemandedMask == 0) { // Not demanding any bits from V.
795 if (V != UndefValue::get(VTy))
796 return UpdateValueUsesWith(V, UndefValue::get(VTy));
797 return false;
798 } else if (Depth == 6) { // Limit search depth.
799 return false;
800 }
801
802 Instruction *I = dyn_cast<Instruction>(V);
803 if (!I) return false; // Only analyze instructions.
804
805 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
806 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
807 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000808 default:
809 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
810 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 case Instruction::And:
812 // If either the LHS or the RHS are Zero, the result is zero.
813 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
814 RHSKnownZero, RHSKnownOne, Depth+1))
815 return true;
816 assert((RHSKnownZero & RHSKnownOne) == 0 &&
817 "Bits known to be one AND zero?");
818
819 // If something is known zero on the RHS, the bits aren't demanded on the
820 // LHS.
821 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
822 LHSKnownZero, LHSKnownOne, Depth+1))
823 return true;
824 assert((LHSKnownZero & LHSKnownOne) == 0 &&
825 "Bits known to be one AND zero?");
826
827 // If all of the demanded bits are known 1 on one side, return the other.
828 // These bits cannot contribute to the result of the 'and'.
829 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
830 (DemandedMask & ~LHSKnownZero))
831 return UpdateValueUsesWith(I, I->getOperand(0));
832 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
833 (DemandedMask & ~RHSKnownZero))
834 return UpdateValueUsesWith(I, I->getOperand(1));
835
836 // If all of the demanded bits in the inputs are known zeros, return zero.
837 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
838 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
839
840 // If the RHS is a constant, see if we can simplify it.
841 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
842 return UpdateValueUsesWith(I, I);
843
844 // Output known-1 bits are only known if set in both the LHS & RHS.
845 RHSKnownOne &= LHSKnownOne;
846 // Output known-0 are known to be clear if zero in either the LHS | RHS.
847 RHSKnownZero |= LHSKnownZero;
848 break;
849 case Instruction::Or:
850 // If either the LHS or the RHS are One, the result is One.
851 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1))
853 return true;
854 assert((RHSKnownZero & RHSKnownOne) == 0 &&
855 "Bits known to be one AND zero?");
856 // If something is known one on the RHS, the bits aren't demanded on the
857 // LHS.
858 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
859 LHSKnownZero, LHSKnownOne, Depth+1))
860 return true;
861 assert((LHSKnownZero & LHSKnownOne) == 0 &&
862 "Bits known to be one AND zero?");
863
864 // If all of the demanded bits are known zero on one side, return the other.
865 // These bits cannot contribute to the result of the 'or'.
866 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
867 (DemandedMask & ~LHSKnownOne))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
870 (DemandedMask & ~RHSKnownOne))
871 return UpdateValueUsesWith(I, I->getOperand(1));
872
873 // If all of the potentially set bits on one side are known to be set on
874 // the other side, just use the 'other' side.
875 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
876 (DemandedMask & (~RHSKnownZero)))
877 return UpdateValueUsesWith(I, I->getOperand(0));
878 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
879 (DemandedMask & (~LHSKnownZero)))
880 return UpdateValueUsesWith(I, I->getOperand(1));
881
882 // If the RHS is a constant, see if we can simplify it.
883 if (ShrinkDemandedConstant(I, 1, DemandedMask))
884 return UpdateValueUsesWith(I, I);
885
886 // Output known-0 bits are only known if clear in both the LHS & RHS.
887 RHSKnownZero &= LHSKnownZero;
888 // Output known-1 are known to be set if set in either the LHS | RHS.
889 RHSKnownOne |= LHSKnownOne;
890 break;
891 case Instruction::Xor: {
892 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893 RHSKnownZero, RHSKnownOne, Depth+1))
894 return true;
895 assert((RHSKnownZero & RHSKnownOne) == 0 &&
896 "Bits known to be one AND zero?");
897 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
898 LHSKnownZero, LHSKnownOne, Depth+1))
899 return true;
900 assert((LHSKnownZero & LHSKnownOne) == 0 &&
901 "Bits known to be one AND zero?");
902
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'xor'.
905 if ((DemandedMask & RHSKnownZero) == DemandedMask)
906 return UpdateValueUsesWith(I, I->getOperand(0));
907 if ((DemandedMask & LHSKnownZero) == DemandedMask)
908 return UpdateValueUsesWith(I, I->getOperand(1));
909
910 // Output known-0 bits are known if clear or set in both the LHS & RHS.
911 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
912 (RHSKnownOne & LHSKnownOne);
913 // Output known-1 are known to be set if set in only one of the LHS, RHS.
914 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
915 (RHSKnownOne & LHSKnownZero);
916
917 // If all of the demanded bits are known to be zero on one side or the
918 // other, turn this into an *inclusive* or.
919 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
920 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
921 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +0000922 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 I->getName());
924 InsertNewInstBefore(Or, *I);
925 return UpdateValueUsesWith(I, Or);
926 }
927
928 // If all of the demanded bits on one side are known, and all of the set
929 // bits on that side are also known to be set on the other side, turn this
930 // into an AND, as we know the bits will be cleared.
931 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
932 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
933 // all known
934 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
935 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
936 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +0000937 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 InsertNewInstBefore(And, *I);
939 return UpdateValueUsesWith(I, And);
940 }
941 }
942
943 // If the RHS is a constant, see if we can simplify it.
944 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
945 if (ShrinkDemandedConstant(I, 1, DemandedMask))
946 return UpdateValueUsesWith(I, I);
947
948 RHSKnownZero = KnownZeroOut;
949 RHSKnownOne = KnownOneOut;
950 break;
951 }
952 case Instruction::Select:
953 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
954 RHSKnownZero, RHSKnownOne, Depth+1))
955 return true;
956 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
957 LHSKnownZero, LHSKnownOne, Depth+1))
958 return true;
959 assert((RHSKnownZero & RHSKnownOne) == 0 &&
960 "Bits known to be one AND zero?");
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
963
964 // If the operands are constants, see if we can simplify them.
965 if (ShrinkDemandedConstant(I, 1, DemandedMask))
966 return UpdateValueUsesWith(I, I);
967 if (ShrinkDemandedConstant(I, 2, DemandedMask))
968 return UpdateValueUsesWith(I, I);
969
970 // Only known if known in both the LHS and RHS.
971 RHSKnownOne &= LHSKnownOne;
972 RHSKnownZero &= LHSKnownZero;
973 break;
974 case Instruction::Trunc: {
975 uint32_t truncBf =
976 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
977 DemandedMask.zext(truncBf);
978 RHSKnownZero.zext(truncBf);
979 RHSKnownOne.zext(truncBf);
980 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
981 RHSKnownZero, RHSKnownOne, Depth+1))
982 return true;
983 DemandedMask.trunc(BitWidth);
984 RHSKnownZero.trunc(BitWidth);
985 RHSKnownOne.trunc(BitWidth);
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
988 break;
989 }
990 case Instruction::BitCast:
991 if (!I->getOperand(0)->getType()->isInteger())
992 return false;
993
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995 RHSKnownZero, RHSKnownOne, Depth+1))
996 return true;
997 assert((RHSKnownZero & RHSKnownOne) == 0 &&
998 "Bits known to be one AND zero?");
999 break;
1000 case Instruction::ZExt: {
1001 // Compute the bits in the result that are not present in the input.
1002 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1003 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1004
1005 DemandedMask.trunc(SrcBitWidth);
1006 RHSKnownZero.trunc(SrcBitWidth);
1007 RHSKnownOne.trunc(SrcBitWidth);
1008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1))
1010 return true;
1011 DemandedMask.zext(BitWidth);
1012 RHSKnownZero.zext(BitWidth);
1013 RHSKnownOne.zext(BitWidth);
1014 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1015 "Bits known to be one AND zero?");
1016 // The top bits are known to be zero.
1017 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1018 break;
1019 }
1020 case Instruction::SExt: {
1021 // Compute the bits in the result that are not present in the input.
1022 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1023 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1024
1025 APInt InputDemandedBits = DemandedMask &
1026 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1027
1028 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1029 // If any of the sign extended bits are demanded, we know that the sign
1030 // bit is demanded.
1031 if ((NewBits & DemandedMask) != 0)
1032 InputDemandedBits.set(SrcBitWidth-1);
1033
1034 InputDemandedBits.trunc(SrcBitWidth);
1035 RHSKnownZero.trunc(SrcBitWidth);
1036 RHSKnownOne.trunc(SrcBitWidth);
1037 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1038 RHSKnownZero, RHSKnownOne, Depth+1))
1039 return true;
1040 InputDemandedBits.zext(BitWidth);
1041 RHSKnownZero.zext(BitWidth);
1042 RHSKnownOne.zext(BitWidth);
1043 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1044 "Bits known to be one AND zero?");
1045
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
1048
1049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
1051 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1052 {
1053 // Convert to ZExt cast
1054 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1055 return UpdateValueUsesWith(I, NewCast);
1056 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1057 RHSKnownOne |= NewBits;
1058 }
1059 break;
1060 }
1061 case Instruction::Add: {
1062 // Figure out what the input bits are. If the top bits of the and result
1063 // are not demanded, then the add doesn't demand them from its input
1064 // either.
1065 uint32_t NLZ = DemandedMask.countLeadingZeros();
1066
1067 // If there is a constant on the RHS, there are a variety of xformations
1068 // we can do.
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1072 if (RHS->isZero())
1073 break;
1074
1075 // If the top bit of the output is demanded, demand everything from the
1076 // input. Otherwise, we demand all the input bits except NLZ top bits.
1077 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1078
1079 // Find information about known zero/one bits in the input.
1080 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1082 return true;
1083
1084 // If the RHS of the add has bits set that can't affect the input, reduce
1085 // the constant.
1086 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1087 return UpdateValueUsesWith(I, I);
1088
1089 // Avoid excess work.
1090 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1091 break;
1092
1093 // Turn it into OR if input bits are zero.
1094 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1095 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001096 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 I->getName());
1098 InsertNewInstBefore(Or, *I);
1099 return UpdateValueUsesWith(I, Or);
1100 }
1101
1102 // We can say something about the output known-zero and known-one bits,
1103 // depending on potential carries from the input constant and the
1104 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1105 // bits set and the RHS constant is 0x01001, then we know we have a known
1106 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1107
1108 // To compute this, we first compute the potential carry bits. These are
1109 // the bits which may be modified. I'm not aware of a better way to do
1110 // this scan.
1111 const APInt& RHSVal = RHS->getValue();
1112 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1113
1114 // Now that we know which bits have carries, compute the known-1/0 sets.
1115
1116 // Bits are known one if they are known zero in one operand and one in the
1117 // other, and there is no input carry.
1118 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1119 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1120
1121 // Bits are known zero if they are known zero in both operands and there
1122 // is no input carry.
1123 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1124 } else {
1125 // If the high-bits of this ADD are not demanded, then it does not demand
1126 // the high bits of its LHS or RHS.
1127 if (DemandedMask[BitWidth-1] == 0) {
1128 // Right fill the mask of bits for this ADD to demand the most
1129 // significant bit and all those below it.
1130 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1131 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1132 LHSKnownZero, LHSKnownOne, Depth+1))
1133 return true;
1134 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1135 LHSKnownZero, LHSKnownOne, Depth+1))
1136 return true;
1137 }
1138 }
1139 break;
1140 }
1141 case Instruction::Sub:
1142 // If the high-bits of this SUB are not demanded, then it does not demand
1143 // the high bits of its LHS or RHS.
1144 if (DemandedMask[BitWidth-1] == 0) {
1145 // Right fill the mask of bits for this SUB to demand the most
1146 // significant bit and all those below it.
1147 uint32_t NLZ = DemandedMask.countLeadingZeros();
1148 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1149 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1))
1151 return true;
1152 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1153 LHSKnownZero, LHSKnownOne, Depth+1))
1154 return true;
1155 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001156 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1157 // the known zeros and ones.
1158 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 break;
1160 case Instruction::Shl:
1161 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1162 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1163 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1165 RHSKnownZero, RHSKnownOne, Depth+1))
1166 return true;
1167 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1168 "Bits known to be one AND zero?");
1169 RHSKnownZero <<= ShiftAmt;
1170 RHSKnownOne <<= ShiftAmt;
1171 // low bits known zero.
1172 if (ShiftAmt)
1173 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1174 }
1175 break;
1176 case Instruction::LShr:
1177 // For a logical shift right
1178 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1180
1181 // Unsigned shift right.
1182 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1183 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1184 RHSKnownZero, RHSKnownOne, Depth+1))
1185 return true;
1186 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1187 "Bits known to be one AND zero?");
1188 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1189 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1190 if (ShiftAmt) {
1191 // Compute the new bits that are at the top now.
1192 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1193 RHSKnownZero |= HighBits; // high bits known zero.
1194 }
1195 }
1196 break;
1197 case Instruction::AShr:
1198 // If this is an arithmetic shift right and only the low-bit is set, we can
1199 // always convert this into a logical shr, even if the shift amount is
1200 // variable. The low bit of the shift cannot be an input sign bit unless
1201 // the shift amount is >= the size of the datatype, which is undefined.
1202 if (DemandedMask == 1) {
1203 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001204 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205 I->getOperand(0), I->getOperand(1), I->getName());
1206 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207 return UpdateValueUsesWith(I, NewVal);
1208 }
1209
1210 // If the sign bit is the only bit demanded by this ashr, then there is no
1211 // need to do it, the shift doesn't change the high bit.
1212 if (DemandedMask.isSignBit())
1213 return UpdateValueUsesWith(I, I->getOperand(0));
1214
1215 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1216 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1217
1218 // Signed shift right.
1219 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1220 // If any of the "high bits" are demanded, we should set the sign bit as
1221 // demanded.
1222 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1223 DemandedMaskIn.set(BitWidth-1);
1224 if (SimplifyDemandedBits(I->getOperand(0),
1225 DemandedMaskIn,
1226 RHSKnownZero, RHSKnownOne, Depth+1))
1227 return true;
1228 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1229 "Bits known to be one AND zero?");
1230 // Compute the new bits that are at the top now.
1231 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1232 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1233 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1234
1235 // Handle the sign bits.
1236 APInt SignBit(APInt::getSignBit(BitWidth));
1237 // Adjust to where it is now in the mask.
1238 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1239
1240 // If the input sign bit is known to be zero, or if none of the top bits
1241 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001242 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 (HighBits & ~DemandedMask) == HighBits) {
1244 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001245 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 I->getOperand(0), SA, I->getName());
1247 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1248 return UpdateValueUsesWith(I, NewVal);
1249 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1250 RHSKnownOne |= HighBits;
1251 }
1252 }
1253 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001254 case Instruction::SRem:
1255 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256 APInt RA = Rem->getValue();
1257 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Nick Lewycky245de422008-07-12 05:04:38 +00001258 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1259 return UpdateValueUsesWith(I, I->getOperand(0));
1260
Dan Gohman5a154a12008-05-06 00:51:48 +00001261 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001262 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1263 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1264 LHSKnownZero, LHSKnownOne, Depth+1))
1265 return true;
1266
1267 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1268 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001269
1270 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001271
1272 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1273 }
1274 }
1275 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001276 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001277 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1278 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001279 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1280 KnownZero2, KnownOne2, Depth+1))
1281 return true;
1282
Dan Gohmanbec16052008-04-28 17:02:21 +00001283 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001284 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001285 KnownZero2, KnownOne2, Depth+1))
1286 return true;
1287
1288 Leaders = std::max(Leaders,
1289 KnownZero2.countLeadingOnes());
1290 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001291 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 }
Chris Lattner989ba312008-06-18 04:33:20 +00001293 case Instruction::Call:
1294 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1295 switch (II->getIntrinsicID()) {
1296 default: break;
1297 case Intrinsic::bswap: {
1298 // If the only bits demanded come from one byte of the bswap result,
1299 // just shift the input byte into position to eliminate the bswap.
1300 unsigned NLZ = DemandedMask.countLeadingZeros();
1301 unsigned NTZ = DemandedMask.countTrailingZeros();
1302
1303 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1304 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1305 // have 14 leading zeros, round to 8.
1306 NLZ &= ~7;
1307 NTZ &= ~7;
1308 // If we need exactly one byte, we can do this transformation.
1309 if (BitWidth-NLZ-NTZ == 8) {
1310 unsigned ResultBit = NTZ;
1311 unsigned InputBit = BitWidth-NTZ-8;
1312
1313 // Replace this with either a left or right shift to get the byte into
1314 // the right place.
1315 Instruction *NewVal;
1316 if (InputBit > ResultBit)
1317 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1318 ConstantInt::get(I->getType(), InputBit-ResultBit));
1319 else
1320 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1321 ConstantInt::get(I->getType(), ResultBit-InputBit));
1322 NewVal->takeName(I);
1323 InsertNewInstBefore(NewVal, *I);
1324 return UpdateValueUsesWith(I, NewVal);
1325 }
1326
1327 // TODO: Could compute known zero/one bits based on the input.
1328 break;
1329 }
1330 }
1331 }
Chris Lattner4946e222008-06-18 18:11:55 +00001332 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001333 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001334 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335
1336 // If the client is only demanding bits that we know, return the known
1337 // constant.
1338 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1339 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1340 return false;
1341}
1342
1343
1344/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1345/// 64 or fewer elements. DemandedElts contains the set of elements that are
1346/// actually used by the caller. This method analyzes which elements of the
1347/// operand are undef and returns that information in UndefElts.
1348///
1349/// If the information about demanded elements can be used to simplify the
1350/// operation, the operation is simplified, then the resultant value is
1351/// returned. This returns null if no change was made.
1352Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1353 uint64_t &UndefElts,
1354 unsigned Depth) {
1355 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1356 assert(VWidth <= 64 && "Vector too wide to analyze!");
1357 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001358 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359
1360 if (isa<UndefValue>(V)) {
1361 // If the entire vector is undefined, just return this info.
1362 UndefElts = EltMask;
1363 return 0;
1364 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1365 UndefElts = EltMask;
1366 return UndefValue::get(V->getType());
1367 }
1368
1369 UndefElts = 0;
1370 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1371 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1372 Constant *Undef = UndefValue::get(EltTy);
1373
1374 std::vector<Constant*> Elts;
1375 for (unsigned i = 0; i != VWidth; ++i)
1376 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1377 Elts.push_back(Undef);
1378 UndefElts |= (1ULL << i);
1379 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1380 Elts.push_back(Undef);
1381 UndefElts |= (1ULL << i);
1382 } else { // Otherwise, defined.
1383 Elts.push_back(CP->getOperand(i));
1384 }
1385
1386 // If we changed the constant, return it.
1387 Constant *NewCP = ConstantVector::get(Elts);
1388 return NewCP != CP ? NewCP : 0;
1389 } else if (isa<ConstantAggregateZero>(V)) {
1390 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1391 // set to undef.
1392 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1393 Constant *Zero = Constant::getNullValue(EltTy);
1394 Constant *Undef = UndefValue::get(EltTy);
1395 std::vector<Constant*> Elts;
1396 for (unsigned i = 0; i != VWidth; ++i)
1397 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1398 UndefElts = DemandedElts ^ EltMask;
1399 return ConstantVector::get(Elts);
1400 }
1401
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001402 // Limit search depth.
1403 if (Depth == 10)
1404 return false;
1405
1406 // If multiple users are using the root value, procede with
1407 // simplification conservatively assuming that all elements
1408 // are needed.
1409 if (!V->hasOneUse()) {
1410 // Quit if we find multiple users of a non-root value though.
1411 // They'll be handled when it's their turn to be visited by
1412 // the main instcombine process.
1413 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414 // TODO: Just compute the UndefElts information recursively.
1415 return false;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001416
1417 // Conservatively assume that all elements are needed.
1418 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 }
1420
1421 Instruction *I = dyn_cast<Instruction>(V);
1422 if (!I) return false; // Only analyze instructions.
1423
1424 bool MadeChange = false;
1425 uint64_t UndefElts2;
1426 Value *TmpV;
1427 switch (I->getOpcode()) {
1428 default: break;
1429
1430 case Instruction::InsertElement: {
1431 // If this is a variable index, we don't know which element it overwrites.
1432 // demand exactly the same input as we produce.
1433 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1434 if (Idx == 0) {
1435 // Note that we can't propagate undef elt info, because we don't know
1436 // which elt is getting updated.
1437 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1438 UndefElts2, Depth+1);
1439 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1440 break;
1441 }
1442
1443 // If this is inserting an element that isn't demanded, remove this
1444 // insertelement.
1445 unsigned IdxNo = Idx->getZExtValue();
1446 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1447 return AddSoonDeadInstToWorklist(*I, 0);
1448
1449 // Otherwise, the element inserted overwrites whatever was there, so the
1450 // input demanded set is simpler than the output set.
1451 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1452 DemandedElts & ~(1ULL << IdxNo),
1453 UndefElts, Depth+1);
1454 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1455
1456 // The inserted element is defined.
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001457 UndefElts &= ~(1ULL << IdxNo);
1458 break;
1459 }
1460 case Instruction::ShuffleVector: {
1461 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1462 uint64_t LeftDemanded = 0, RightDemanded = 0;
1463 for (unsigned i = 0; i < VWidth; i++) {
1464 if (DemandedElts & (1ULL << i)) {
1465 unsigned MaskVal = Shuffle->getMaskValue(i);
1466 if (MaskVal != -1u) {
1467 assert(MaskVal < VWidth * 2 &&
1468 "shufflevector mask index out of range!");
1469 if (MaskVal < VWidth)
1470 LeftDemanded |= 1ULL << MaskVal;
1471 else
1472 RightDemanded |= 1ULL << (MaskVal - VWidth);
1473 }
1474 }
1475 }
1476
1477 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1478 UndefElts2, Depth+1);
1479 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1480
1481 uint64_t UndefElts3;
1482 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1483 UndefElts3, Depth+1);
1484 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1485
1486 bool NewUndefElts = false;
1487 for (unsigned i = 0; i < VWidth; i++) {
1488 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001489 if (MaskVal == -1u) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001490 uint64_t NewBit = 1ULL << i;
1491 UndefElts |= NewBit;
1492 } else if (MaskVal < VWidth) {
1493 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1494 NewUndefElts |= NewBit;
1495 UndefElts |= NewBit;
1496 } else {
1497 uint64_t NewBit = ((UndefElts3 >> (MaskVal - VWidth)) & 1) << i;
1498 NewUndefElts |= NewBit;
1499 UndefElts |= NewBit;
1500 }
1501 }
1502
1503 if (NewUndefElts) {
1504 // Add additional discovered undefs.
1505 std::vector<Constant*> Elts;
1506 for (unsigned i = 0; i < VWidth; ++i) {
1507 if (UndefElts & (1ULL << i))
1508 Elts.push_back(UndefValue::get(Type::Int32Ty));
1509 else
1510 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1511 Shuffle->getMaskValue(i)));
1512 }
1513 I->setOperand(2, ConstantVector::get(Elts));
1514 MadeChange = true;
1515 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001516 break;
1517 }
1518 case Instruction::BitCast: {
1519 // Vector->vector casts only.
1520 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1521 if (!VTy) break;
1522 unsigned InVWidth = VTy->getNumElements();
1523 uint64_t InputDemandedElts = 0;
1524 unsigned Ratio;
1525
1526 if (VWidth == InVWidth) {
1527 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1528 // elements as are demanded of us.
1529 Ratio = 1;
1530 InputDemandedElts = DemandedElts;
1531 } else if (VWidth > InVWidth) {
1532 // Untested so far.
1533 break;
1534
1535 // If there are more elements in the result than there are in the source,
1536 // then an input element is live if any of the corresponding output
1537 // elements are live.
1538 Ratio = VWidth/InVWidth;
1539 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1540 if (DemandedElts & (1ULL << OutIdx))
1541 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1542 }
1543 } else {
1544 // Untested so far.
1545 break;
1546
1547 // If there are more elements in the source than there are in the result,
1548 // then an input element is live if the corresponding output element is
1549 // live.
1550 Ratio = InVWidth/VWidth;
1551 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1552 if (DemandedElts & (1ULL << InIdx/Ratio))
1553 InputDemandedElts |= 1ULL << InIdx;
1554 }
1555
1556 // div/rem demand all inputs, because they don't want divide by zero.
1557 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1558 UndefElts2, Depth+1);
1559 if (TmpV) {
1560 I->setOperand(0, TmpV);
1561 MadeChange = true;
1562 }
1563
1564 UndefElts = UndefElts2;
1565 if (VWidth > InVWidth) {
1566 assert(0 && "Unimp");
1567 // If there are more elements in the result than there are in the source,
1568 // then an output element is undef if the corresponding input element is
1569 // undef.
1570 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1571 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1572 UndefElts |= 1ULL << OutIdx;
1573 } else if (VWidth < InVWidth) {
1574 assert(0 && "Unimp");
1575 // If there are more elements in the source than there are in the result,
1576 // then a result element is undef if all of the corresponding input
1577 // elements are undef.
1578 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1579 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1580 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1581 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1582 }
1583 break;
1584 }
1585 case Instruction::And:
1586 case Instruction::Or:
1587 case Instruction::Xor:
1588 case Instruction::Add:
1589 case Instruction::Sub:
1590 case Instruction::Mul:
1591 // div/rem demand all inputs, because they don't want divide by zero.
1592 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1593 UndefElts, Depth+1);
1594 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1595 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1596 UndefElts2, Depth+1);
1597 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1598
1599 // Output elements are undefined if both are undefined. Consider things
1600 // like undef&0. The result is known zero, not undef.
1601 UndefElts &= UndefElts2;
1602 break;
1603
1604 case Instruction::Call: {
1605 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1606 if (!II) break;
1607 switch (II->getIntrinsicID()) {
1608 default: break;
1609
1610 // Binary vector operations that work column-wise. A dest element is a
1611 // function of the corresponding input elements from the two inputs.
1612 case Intrinsic::x86_sse_sub_ss:
1613 case Intrinsic::x86_sse_mul_ss:
1614 case Intrinsic::x86_sse_min_ss:
1615 case Intrinsic::x86_sse_max_ss:
1616 case Intrinsic::x86_sse2_sub_sd:
1617 case Intrinsic::x86_sse2_mul_sd:
1618 case Intrinsic::x86_sse2_min_sd:
1619 case Intrinsic::x86_sse2_max_sd:
1620 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1621 UndefElts, Depth+1);
1622 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1623 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1624 UndefElts2, Depth+1);
1625 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1626
1627 // If only the low elt is demanded and this is a scalarizable intrinsic,
1628 // scalarize it now.
1629 if (DemandedElts == 1) {
1630 switch (II->getIntrinsicID()) {
1631 default: break;
1632 case Intrinsic::x86_sse_sub_ss:
1633 case Intrinsic::x86_sse_mul_ss:
1634 case Intrinsic::x86_sse2_sub_sd:
1635 case Intrinsic::x86_sse2_mul_sd:
1636 // TODO: Lower MIN/MAX/ABS/etc
1637 Value *LHS = II->getOperand(1);
1638 Value *RHS = II->getOperand(2);
1639 // Extract the element as scalars.
1640 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1641 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1642
1643 switch (II->getIntrinsicID()) {
1644 default: assert(0 && "Case stmts out of sync!");
1645 case Intrinsic::x86_sse_sub_ss:
1646 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001647 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 II->getName()), *II);
1649 break;
1650 case Intrinsic::x86_sse_mul_ss:
1651 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001652 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 II->getName()), *II);
1654 break;
1655 }
1656
1657 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001658 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1659 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 InsertNewInstBefore(New, *II);
1661 AddSoonDeadInstToWorklist(*II, 0);
1662 return New;
1663 }
1664 }
1665
1666 // Output elements are undefined if both are undefined. Consider things
1667 // like undef&0. The result is known zero, not undef.
1668 UndefElts &= UndefElts2;
1669 break;
1670 }
1671 break;
1672 }
1673 }
1674 return MadeChange ? I : 0;
1675}
1676
Dan Gohman5d56fd42008-05-19 22:14:15 +00001677
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678/// AssociativeOpt - Perform an optimization on an associative operator. This
1679/// function is designed to check a chain of associative operators for a
1680/// potential to apply a certain optimization. Since the optimization may be
1681/// applicable if the expression was reassociated, this checks the chain, then
1682/// reassociates the expression as necessary to expose the optimization
1683/// opportunity. This makes use of a special Functor, which must define
1684/// 'shouldApply' and 'apply' methods.
1685///
1686template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001687static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 unsigned Opcode = Root.getOpcode();
1689 Value *LHS = Root.getOperand(0);
1690
1691 // Quick check, see if the immediate LHS matches...
1692 if (F.shouldApply(LHS))
1693 return F.apply(Root);
1694
1695 // Otherwise, if the LHS is not of the same opcode as the root, return.
1696 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1697 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1698 // Should we apply this transform to the RHS?
1699 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1700
1701 // If not to the RHS, check to see if we should apply to the LHS...
1702 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1703 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1704 ShouldApply = true;
1705 }
1706
1707 // If the functor wants to apply the optimization to the RHS of LHSI,
1708 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1709 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001710 // Now all of the instructions are in the current basic block, go ahead
1711 // and perform the reassociation.
1712 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1713
1714 // First move the selected RHS to the LHS of the root...
1715 Root.setOperand(0, LHSI->getOperand(1));
1716
1717 // Make what used to be the LHS of the root be the user of the root...
1718 Value *ExtraOperand = TmpLHSI->getOperand(1);
1719 if (&Root == TmpLHSI) {
1720 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1721 return 0;
1722 }
1723 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1724 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001726 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 ARI = Root;
1728
1729 // Now propagate the ExtraOperand down the chain of instructions until we
1730 // get to LHSI.
1731 while (TmpLHSI != LHSI) {
1732 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1733 // Move the instruction to immediately before the chain we are
1734 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001735 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001736 ARI = NextLHSI;
1737
1738 Value *NextOp = NextLHSI->getOperand(1);
1739 NextLHSI->setOperand(1, ExtraOperand);
1740 TmpLHSI = NextLHSI;
1741 ExtraOperand = NextOp;
1742 }
1743
1744 // Now that the instructions are reassociated, have the functor perform
1745 // the transformation...
1746 return F.apply(Root);
1747 }
1748
1749 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1750 }
1751 return 0;
1752}
1753
Dan Gohman089efff2008-05-13 00:00:25 +00001754namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755
Nick Lewycky27f6c132008-05-23 04:34:58 +00001756// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757struct AddRHS {
1758 Value *RHS;
1759 AddRHS(Value *rhs) : RHS(rhs) {}
1760 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1761 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001762 return BinaryOperator::CreateShl(Add.getOperand(0),
1763 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764 }
1765};
1766
1767// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1768// iff C1&C2 == 0
1769struct AddMaskingAnd {
1770 Constant *C2;
1771 AddMaskingAnd(Constant *c) : C2(c) {}
1772 bool shouldApply(Value *LHS) const {
1773 ConstantInt *C1;
1774 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1775 ConstantExpr::getAnd(C1, C2)->isNullValue();
1776 }
1777 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001778 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779 }
1780};
1781
Dan Gohman089efff2008-05-13 00:00:25 +00001782}
1783
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1785 InstCombiner *IC) {
1786 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1787 if (Constant *SOC = dyn_cast<Constant>(SO))
1788 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1789
Gabor Greifa645dd32008-05-16 19:29:10 +00001790 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1792 }
1793
1794 // Figure out if the constant is the left or the right argument.
1795 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1796 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1797
1798 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1799 if (ConstIsRHS)
1800 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1801 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1802 }
1803
1804 Value *Op0 = SO, *Op1 = ConstOperand;
1805 if (!ConstIsRHS)
1806 std::swap(Op0, Op1);
1807 Instruction *New;
1808 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001809 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001810 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001811 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812 SO->getName()+".cmp");
1813 else {
1814 assert(0 && "Unknown binary instruction type!");
1815 abort();
1816 }
1817 return IC->InsertNewInstBefore(New, I);
1818}
1819
1820// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1821// constant as the other operand, try to fold the binary operator into the
1822// select arguments. This also works for Cast instructions, which obviously do
1823// not have a second operand.
1824static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1825 InstCombiner *IC) {
1826 // Don't modify shared select instructions
1827 if (!SI->hasOneUse()) return 0;
1828 Value *TV = SI->getOperand(1);
1829 Value *FV = SI->getOperand(2);
1830
1831 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1832 // Bool selects with constant operands can be folded to logical ops.
1833 if (SI->getType() == Type::Int1Ty) return 0;
1834
1835 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1836 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1837
Gabor Greifd6da1d02008-04-06 20:25:17 +00001838 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1839 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840 }
1841 return 0;
1842}
1843
1844
1845/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1846/// node as operand #0, see if we can fold the instruction into the PHI (which
1847/// is only possible if all operands to the PHI are constants).
1848Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1849 PHINode *PN = cast<PHINode>(I.getOperand(0));
1850 unsigned NumPHIValues = PN->getNumIncomingValues();
1851 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1852
1853 // Check to see if all of the operands of the PHI are constants. If there is
1854 // one non-constant value, remember the BB it is. If there is more than one
1855 // or if *it* is a PHI, bail out.
1856 BasicBlock *NonConstBB = 0;
1857 for (unsigned i = 0; i != NumPHIValues; ++i)
1858 if (!isa<Constant>(PN->getIncomingValue(i))) {
1859 if (NonConstBB) return 0; // More than one non-const value.
1860 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1861 NonConstBB = PN->getIncomingBlock(i);
1862
1863 // If the incoming non-constant value is in I's block, we have an infinite
1864 // loop.
1865 if (NonConstBB == I.getParent())
1866 return 0;
1867 }
1868
1869 // If there is exactly one non-constant value, we can insert a copy of the
1870 // operation in that block. However, if this is a critical edge, we would be
1871 // inserting the computation one some other paths (e.g. inside a loop). Only
1872 // do this if the pred block is unconditionally branching into the phi block.
1873 if (NonConstBB) {
1874 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1875 if (!BI || !BI->isUnconditional()) return 0;
1876 }
1877
1878 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001879 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1881 InsertNewInstBefore(NewPN, *PN);
1882 NewPN->takeName(PN);
1883
1884 // Next, add all of the operands to the PHI.
1885 if (I.getNumOperands() == 2) {
1886 Constant *C = cast<Constant>(I.getOperand(1));
1887 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001888 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001889 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1890 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1891 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1892 else
1893 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1894 } else {
1895 assert(PN->getIncomingBlock(i) == NonConstBB);
1896 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001897 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898 PN->getIncomingValue(i), C, "phitmp",
1899 NonConstBB->getTerminator());
1900 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001901 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001902 CI->getPredicate(),
1903 PN->getIncomingValue(i), C, "phitmp",
1904 NonConstBB->getTerminator());
1905 else
1906 assert(0 && "Unknown binop!");
1907
1908 AddToWorkList(cast<Instruction>(InV));
1909 }
1910 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1911 }
1912 } else {
1913 CastInst *CI = cast<CastInst>(&I);
1914 const Type *RetTy = CI->getType();
1915 for (unsigned i = 0; i != NumPHIValues; ++i) {
1916 Value *InV;
1917 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1918 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1919 } else {
1920 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001921 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001922 I.getType(), "phitmp",
1923 NonConstBB->getTerminator());
1924 AddToWorkList(cast<Instruction>(InV));
1925 }
1926 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1927 }
1928 }
1929 return ReplaceInstUsesWith(I, NewPN);
1930}
1931
Chris Lattner55476162008-01-29 06:52:45 +00001932
Chris Lattner3554f972008-05-20 05:46:13 +00001933/// WillNotOverflowSignedAdd - Return true if we can prove that:
1934/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1935/// This basically requires proving that the add in the original type would not
1936/// overflow to change the sign bit or have a carry out.
1937bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1938 // There are different heuristics we can use for this. Here are some simple
1939 // ones.
1940
1941 // Add has the property that adding any two 2's complement numbers can only
1942 // have one carry bit which can change a sign. As such, if LHS and RHS each
1943 // have at least two sign bits, we know that the addition of the two values will
1944 // sign extend fine.
1945 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1946 return true;
1947
1948
1949 // If one of the operands only has one non-zero bit, and if the other operand
1950 // has a known-zero bit in a more significant place than it (not including the
1951 // sign bit) the ripple may go up to and fill the zero, but won't change the
1952 // sign. For example, (X & ~4) + 1.
1953
1954 // TODO: Implement.
1955
1956 return false;
1957}
1958
Chris Lattner55476162008-01-29 06:52:45 +00001959
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1961 bool Changed = SimplifyCommutative(I);
1962 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1963
1964 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1965 // X + undef -> undef
1966 if (isa<UndefValue>(RHS))
1967 return ReplaceInstUsesWith(I, RHS);
1968
1969 // X + 0 --> X
1970 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1971 if (RHSC->isNullValue())
1972 return ReplaceInstUsesWith(I, LHS);
1973 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001974 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1975 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 return ReplaceInstUsesWith(I, LHS);
1977 }
1978
1979 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1980 // X + (signbit) --> X ^ signbit
1981 const APInt& Val = CI->getValue();
1982 uint32_t BitWidth = Val.getBitWidth();
1983 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00001984 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001985
1986 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1987 // (X & 254)+1 -> (X&254)|1
1988 if (!isa<VectorType>(I.getType())) {
1989 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1990 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1991 KnownZero, KnownOne))
1992 return &I;
1993 }
1994 }
1995
1996 if (isa<PHINode>(LHS))
1997 if (Instruction *NV = FoldOpIntoPhi(I))
1998 return NV;
1999
2000 ConstantInt *XorRHS = 0;
2001 Value *XorLHS = 0;
2002 if (isa<ConstantInt>(RHSC) &&
2003 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2004 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2005 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2006
2007 uint32_t Size = TySizeBits / 2;
2008 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2009 APInt CFF80Val(-C0080Val);
2010 do {
2011 if (TySizeBits > Size) {
2012 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2013 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2014 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2015 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2016 // This is a sign extend if the top bits are known zero.
2017 if (!MaskedValueIsZero(XorLHS,
2018 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2019 Size = 0; // Not a sign ext, but can't be any others either.
2020 break;
2021 }
2022 }
2023 Size >>= 1;
2024 C0080Val = APIntOps::lshr(C0080Val, Size);
2025 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2026 } while (Size >= 1);
2027
2028 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002029 // with funny bit widths then this switch statement should be removed. It
2030 // is just here to get the size of the "middle" type back up to something
2031 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002032 const Type *MiddleType = 0;
2033 switch (Size) {
2034 default: break;
2035 case 32: MiddleType = Type::Int32Ty; break;
2036 case 16: MiddleType = Type::Int16Ty; break;
2037 case 8: MiddleType = Type::Int8Ty; break;
2038 }
2039 if (MiddleType) {
2040 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2041 InsertNewInstBefore(NewTrunc, I);
2042 return new SExtInst(NewTrunc, I.getType(), I.getName());
2043 }
2044 }
2045 }
2046
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002047 if (I.getType() == Type::Int1Ty)
2048 return BinaryOperator::CreateXor(LHS, RHS);
2049
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002050 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002051 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002052 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2053
2054 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2055 if (RHSI->getOpcode() == Instruction::Sub)
2056 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2057 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2058 }
2059 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2060 if (LHSI->getOpcode() == Instruction::Sub)
2061 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2062 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2063 }
2064 }
2065
2066 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002067 // -A + -B --> -(A + B)
2068 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002069 if (LHS->getType()->isIntOrIntVector()) {
2070 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002071 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002072 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002073 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002074 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002075 }
2076
Gabor Greifa645dd32008-05-16 19:29:10 +00002077 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002078 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002079
2080 // A + -B --> A - B
2081 if (!isa<Constant>(RHS))
2082 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002083 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084
2085
2086 ConstantInt *C2;
2087 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2088 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002089 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002090
2091 // X*C1 + X*C2 --> X * (C1+C2)
2092 ConstantInt *C1;
2093 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002094 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095 }
2096
2097 // X + X*C --> X * (C+1)
2098 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002099 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100
2101 // X + ~X --> -1 since ~X = -X-1
2102 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2103 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2104
2105
2106 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2107 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2108 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2109 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002110
2111 // A+B --> A|B iff A and B have no bits set in common.
2112 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2113 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2114 APInt LHSKnownOne(IT->getBitWidth(), 0);
2115 APInt LHSKnownZero(IT->getBitWidth(), 0);
2116 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2117 if (LHSKnownZero != 0) {
2118 APInt RHSKnownOne(IT->getBitWidth(), 0);
2119 APInt RHSKnownZero(IT->getBitWidth(), 0);
2120 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2121
2122 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002123 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002124 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002125 }
2126 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127
Nick Lewycky83598a72008-02-03 07:42:09 +00002128 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002129 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002130 Value *W, *X, *Y, *Z;
2131 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2132 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2133 if (W != Y) {
2134 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002135 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002136 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002137 std::swap(W, X);
2138 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002139 std::swap(Y, Z);
2140 std::swap(W, X);
2141 }
2142 }
2143
2144 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002145 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002146 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002147 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002148 }
2149 }
2150 }
2151
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2153 Value *X = 0;
2154 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002155 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002156
2157 // (X & FF00) + xx00 -> (X+xx00) & FF00
2158 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2159 Constant *Anded = And(CRHS, C2);
2160 if (Anded == CRHS) {
2161 // See if all bits from the first bit set in the Add RHS up are included
2162 // in the mask. First, get the rightmost bit.
2163 const APInt& AddRHSV = CRHS->getValue();
2164
2165 // Form a mask of all bits from the lowest bit added through the top.
2166 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2167
2168 // See if the and mask includes all of these bits.
2169 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2170
2171 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2172 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002173 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002174 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002175 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002176 }
2177 }
2178 }
2179
2180 // Try to fold constant add into select arguments.
2181 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2182 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2183 return R;
2184 }
2185
2186 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002187 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 {
2189 CastInst *CI = dyn_cast<CastInst>(LHS);
2190 Value *Other = RHS;
2191 if (!CI) {
2192 CI = dyn_cast<CastInst>(RHS);
2193 Other = LHS;
2194 }
2195 if (CI && CI->getType()->isSized() &&
2196 (CI->getType()->getPrimitiveSizeInBits() ==
2197 TD->getIntPtrType()->getPrimitiveSizeInBits())
2198 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002199 unsigned AS =
2200 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002201 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2202 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002203 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002204 return new PtrToIntInst(I2, CI->getType());
2205 }
2206 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002207
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002208 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002209 {
2210 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2211 Value *Other = RHS;
2212 if (!SI) {
2213 SI = dyn_cast<SelectInst>(RHS);
2214 Other = LHS;
2215 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002216 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002217 Value *TV = SI->getTrueValue();
2218 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002219 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002220
2221 // Can we fold the add into the argument of the select?
2222 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002223 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2224 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002225 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002226 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2227 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002228 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002229 }
2230 }
Chris Lattner55476162008-01-29 06:52:45 +00002231
2232 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2234 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2235 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002236
Chris Lattner3554f972008-05-20 05:46:13 +00002237 // Check for (add (sext x), y), see if we can merge this into an
2238 // integer add followed by a sext.
2239 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2240 // (add (sext x), cst) --> (sext (add x, cst'))
2241 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2242 Constant *CI =
2243 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2244 if (LHSConv->hasOneUse() &&
2245 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2246 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2247 // Insert the new, smaller add.
2248 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2249 CI, "addconv");
2250 InsertNewInstBefore(NewAdd, I);
2251 return new SExtInst(NewAdd, I.getType());
2252 }
2253 }
2254
2255 // (add (sext x), (sext y)) --> (sext (add int x, y))
2256 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2257 // Only do this if x/y have the same type, if at last one of them has a
2258 // single use (so we don't increase the number of sexts), and if the
2259 // integer add will not overflow.
2260 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2261 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2262 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2263 RHSConv->getOperand(0))) {
2264 // Insert the new integer add.
2265 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2266 RHSConv->getOperand(0),
2267 "addconv");
2268 InsertNewInstBefore(NewAdd, I);
2269 return new SExtInst(NewAdd, I.getType());
2270 }
2271 }
2272 }
2273
2274 // Check for (add double (sitofp x), y), see if we can merge this into an
2275 // integer add followed by a promotion.
2276 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2277 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2278 // ... if the constant fits in the integer value. This is useful for things
2279 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2280 // requires a constant pool load, and generally allows the add to be better
2281 // instcombined.
2282 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2283 Constant *CI =
2284 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2285 if (LHSConv->hasOneUse() &&
2286 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2287 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2288 // Insert the new integer add.
2289 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2290 CI, "addconv");
2291 InsertNewInstBefore(NewAdd, I);
2292 return new SIToFPInst(NewAdd, I.getType());
2293 }
2294 }
2295
2296 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2297 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2298 // Only do this if x/y have the same type, if at last one of them has a
2299 // single use (so we don't increase the number of int->fp conversions),
2300 // and if the integer add will not overflow.
2301 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2302 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2303 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2304 RHSConv->getOperand(0))) {
2305 // Insert the new integer add.
2306 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2307 RHSConv->getOperand(0),
2308 "addconv");
2309 InsertNewInstBefore(NewAdd, I);
2310 return new SIToFPInst(NewAdd, I.getType());
2311 }
2312 }
2313 }
2314
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002315 return Changed ? &I : 0;
2316}
2317
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002318Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2319 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2320
Chris Lattner27fbef42008-07-17 06:07:20 +00002321 if (Op0 == Op1 && // sub X, X -> 0
2322 !I.getType()->isFPOrFPVector())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002323 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2324
2325 // If this is a 'B = x-(-A)', change to B = x+A...
2326 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002327 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002328
2329 if (isa<UndefValue>(Op0))
2330 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2331 if (isa<UndefValue>(Op1))
2332 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2333
2334 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2335 // Replace (-1 - A) with (~A)...
2336 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002337 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338
2339 // C - ~X == X + (1+C)
2340 Value *X = 0;
2341 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002342 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002343
2344 // -(X >>u 31) -> (X >>s 31)
2345 // -(X >>s 31) -> (X >>u 31)
2346 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002347 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002348 if (SI->getOpcode() == Instruction::LShr) {
2349 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2350 // Check to see if we are shifting out everything but the sign bit.
2351 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2352 SI->getType()->getPrimitiveSizeInBits()-1) {
2353 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002354 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355 SI->getOperand(0), CU, SI->getName());
2356 }
2357 }
2358 }
2359 else if (SI->getOpcode() == Instruction::AShr) {
2360 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2361 // Check to see if we are shifting out everything but the sign bit.
2362 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2363 SI->getType()->getPrimitiveSizeInBits()-1) {
2364 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002365 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366 SI->getOperand(0), CU, SI->getName());
2367 }
2368 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002369 }
2370 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002371 }
2372
2373 // Try to fold constant sub into select arguments.
2374 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2375 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2376 return R;
2377
2378 if (isa<PHINode>(Op0))
2379 if (Instruction *NV = FoldOpIntoPhi(I))
2380 return NV;
2381 }
2382
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002383 if (I.getType() == Type::Int1Ty)
2384 return BinaryOperator::CreateXor(Op0, Op1);
2385
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2387 if (Op1I->getOpcode() == Instruction::Add &&
2388 !Op0->getType()->isFPOrFPVector()) {
2389 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002390 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002391 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002392 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002393 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2394 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2395 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002396 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002397 Op1I->getOperand(0));
2398 }
2399 }
2400
2401 if (Op1I->hasOneUse()) {
2402 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2403 // is not used by anyone else...
2404 //
2405 if (Op1I->getOpcode() == Instruction::Sub &&
2406 !Op1I->getType()->isFPOrFPVector()) {
2407 // Swap the two operands of the subexpr...
2408 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2409 Op1I->setOperand(0, IIOp1);
2410 Op1I->setOperand(1, IIOp0);
2411
2412 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002413 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002414 }
2415
2416 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2417 //
2418 if (Op1I->getOpcode() == Instruction::And &&
2419 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2420 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2421
2422 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002423 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2424 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002425 }
2426
2427 // 0 - (X sdiv C) -> (X sdiv -C)
2428 if (Op1I->getOpcode() == Instruction::SDiv)
2429 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2430 if (CSI->isZero())
2431 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002432 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002433 ConstantExpr::getNeg(DivRHS));
2434
2435 // X - X*C --> X * (1-C)
2436 ConstantInt *C2 = 0;
2437 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2438 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002439 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002440 }
Dan Gohmanda338742007-09-17 17:31:57 +00002441
2442 // X - ((X / Y) * Y) --> X % Y
2443 if (Op1I->getOpcode() == Instruction::Mul)
2444 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2445 if (Op0 == I->getOperand(0) &&
2446 Op1I->getOperand(1) == I->getOperand(1)) {
2447 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002448 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002449 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002450 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002451 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452 }
2453 }
2454
2455 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002456 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002457 if (Op0I->getOpcode() == Instruction::Add) {
2458 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2459 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2460 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2461 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2462 } else if (Op0I->getOpcode() == Instruction::Sub) {
2463 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002464 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002466 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002467
2468 ConstantInt *C1;
2469 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2470 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002472
2473 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2474 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002475 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002476 }
2477 return 0;
2478}
2479
2480/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2481/// comparison only checks the sign bit. If it only checks the sign bit, set
2482/// TrueIfSigned if the result of the comparison is true when the input value is
2483/// signed.
2484static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2485 bool &TrueIfSigned) {
2486 switch (pred) {
2487 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2488 TrueIfSigned = true;
2489 return RHS->isZero();
2490 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2491 TrueIfSigned = true;
2492 return RHS->isAllOnesValue();
2493 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2494 TrueIfSigned = false;
2495 return RHS->isAllOnesValue();
2496 case ICmpInst::ICMP_UGT:
2497 // True if LHS u> RHS and RHS == high-bit-mask - 1
2498 TrueIfSigned = true;
2499 return RHS->getValue() ==
2500 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2501 case ICmpInst::ICMP_UGE:
2502 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2503 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002504 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505 default:
2506 return false;
2507 }
2508}
2509
2510Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2511 bool Changed = SimplifyCommutative(I);
2512 Value *Op0 = I.getOperand(0);
2513
2514 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2515 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2516
2517 // Simplify mul instructions with a constant RHS...
2518 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2519 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2520
2521 // ((X << C1)*C2) == (X * (C2 << C1))
2522 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2523 if (SI->getOpcode() == Instruction::Shl)
2524 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002525 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002526 ConstantExpr::getShl(CI, ShOp));
2527
2528 if (CI->isZero())
2529 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2530 if (CI->equalsInt(1)) // X * 1 == X
2531 return ReplaceInstUsesWith(I, Op0);
2532 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002533 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002534
2535 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2536 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002537 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002538 ConstantInt::get(Op0->getType(), Val.logBase2()));
2539 }
2540 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2541 if (Op1F->isNullValue())
2542 return ReplaceInstUsesWith(I, Op1);
2543
2544 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2545 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattner6297fc72008-08-11 22:06:05 +00002546 if (Op1F->isExactlyValue(1.0))
2547 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2548 } else if (isa<VectorType>(Op1->getType())) {
2549 if (isa<ConstantAggregateZero>(Op1))
2550 return ReplaceInstUsesWith(I, Op1);
2551
2552 // As above, vector X*splat(1.0) -> X in all defined cases.
2553 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2554 if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2555 if (F->isExactlyValue(1.0))
2556 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002557 }
2558
2559 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2560 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002561 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002563 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002564 Op1, "tmp");
2565 InsertNewInstBefore(Add, I);
2566 Value *C1C2 = ConstantExpr::getMul(Op1,
2567 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002568 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569
2570 }
2571
2572 // Try to fold constant mul into select arguments.
2573 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2574 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2575 return R;
2576
2577 if (isa<PHINode>(Op0))
2578 if (Instruction *NV = FoldOpIntoPhi(I))
2579 return NV;
2580 }
2581
2582 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2583 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002584 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002586 if (I.getType() == Type::Int1Ty)
2587 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2588
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002589 // If one of the operands of the multiply is a cast from a boolean value, then
2590 // we know the bool is either zero or one, so this is a 'masking' multiply.
2591 // See if we can simplify things based on how the boolean was originally
2592 // formed.
2593 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002594 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002595 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2596 BoolCast = CI;
2597 if (!BoolCast)
2598 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2599 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2600 BoolCast = CI;
2601 if (BoolCast) {
2602 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2603 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2604 const Type *SCOpTy = SCIOp0->getType();
2605 bool TIS = false;
2606
2607 // If the icmp is true iff the sign bit of X is set, then convert this
2608 // multiply into a shift/and combination.
2609 if (isa<ConstantInt>(SCIOp1) &&
2610 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2611 TIS) {
2612 // Shift the X value right to turn it into "all signbits".
2613 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2614 SCOpTy->getPrimitiveSizeInBits()-1);
2615 Value *V =
2616 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002617 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002618 BoolCast->getOperand(0)->getName()+
2619 ".mask"), I);
2620
2621 // If the multiply type is not the same as the source type, sign extend
2622 // or truncate to the multiply type.
2623 if (I.getType() != V->getType()) {
2624 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2625 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2626 Instruction::CastOps opcode =
2627 (SrcBits == DstBits ? Instruction::BitCast :
2628 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2629 V = InsertCastBefore(opcode, V, I.getType(), I);
2630 }
2631
2632 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002633 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002634 }
2635 }
2636 }
2637
2638 return Changed ? &I : 0;
2639}
2640
Chris Lattner76972db2008-07-14 00:15:52 +00002641/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2642/// instruction.
2643bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2644 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2645
2646 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2647 int NonNullOperand = -1;
2648 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2649 if (ST->isNullValue())
2650 NonNullOperand = 2;
2651 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2652 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2653 if (ST->isNullValue())
2654 NonNullOperand = 1;
2655
2656 if (NonNullOperand == -1)
2657 return false;
2658
2659 Value *SelectCond = SI->getOperand(0);
2660
2661 // Change the div/rem to use 'Y' instead of the select.
2662 I.setOperand(1, SI->getOperand(NonNullOperand));
2663
2664 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2665 // problem. However, the select, or the condition of the select may have
2666 // multiple uses. Based on our knowledge that the operand must be non-zero,
2667 // propagate the known value for the select into other uses of it, and
2668 // propagate a known value of the condition into its other users.
2669
2670 // If the select and condition only have a single use, don't bother with this,
2671 // early exit.
2672 if (SI->use_empty() && SelectCond->hasOneUse())
2673 return true;
2674
2675 // Scan the current block backward, looking for other uses of SI.
2676 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2677
2678 while (BBI != BBFront) {
2679 --BBI;
2680 // If we found a call to a function, we can't assume it will return, so
2681 // information from below it cannot be propagated above it.
2682 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2683 break;
2684
2685 // Replace uses of the select or its condition with the known values.
2686 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2687 I != E; ++I) {
2688 if (*I == SI) {
2689 *I = SI->getOperand(NonNullOperand);
2690 AddToWorkList(BBI);
2691 } else if (*I == SelectCond) {
2692 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2693 ConstantInt::getFalse();
2694 AddToWorkList(BBI);
2695 }
2696 }
2697
2698 // If we past the instruction, quit looking for it.
2699 if (&*BBI == SI)
2700 SI = 0;
2701 if (&*BBI == SelectCond)
2702 SelectCond = 0;
2703
2704 // If we ran out of things to eliminate, break out of the loop.
2705 if (SelectCond == 0 && SI == 0)
2706 break;
2707
2708 }
2709 return true;
2710}
2711
2712
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713/// This function implements the transforms on div instructions that work
2714/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2715/// used by the visitors to those instructions.
2716/// @brief Transforms common to all three div instructions
2717Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2719
Chris Lattner653ef3c2008-02-19 06:12:18 +00002720 // undef / X -> 0 for integer.
2721 // undef / X -> undef for FP (the undef could be a snan).
2722 if (isa<UndefValue>(Op0)) {
2723 if (Op0->getType()->isFPOrFPVector())
2724 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002725 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002726 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002727
2728 // X / undef -> undef
2729 if (isa<UndefValue>(Op1))
2730 return ReplaceInstUsesWith(I, Op1);
2731
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732 return 0;
2733}
2734
2735/// This function implements the transforms common to both integer division
2736/// instructions (udiv and sdiv). It is called by the visitors to those integer
2737/// division instructions.
2738/// @brief Common integer divide transforms
2739Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2740 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2741
Chris Lattnercefb36c2008-05-16 02:59:42 +00002742 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002743 if (Op0 == Op1) {
2744 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2745 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2746 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2747 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2748 }
2749
2750 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2751 return ReplaceInstUsesWith(I, CI);
2752 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002753
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754 if (Instruction *Common = commonDivTransforms(I))
2755 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002756
2757 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2758 // This does not apply for fdiv.
2759 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2760 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761
2762 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2763 // div X, 1 == X
2764 if (RHS->equalsInt(1))
2765 return ReplaceInstUsesWith(I, Op0);
2766
2767 // (X / C1) / C2 -> X / (C1*C2)
2768 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2769 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2770 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002771 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2772 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2773 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002774 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002775 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002776 }
2777
2778 if (!RHS->isZero()) { // avoid X udiv 0
2779 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2780 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2781 return R;
2782 if (isa<PHINode>(Op0))
2783 if (Instruction *NV = FoldOpIntoPhi(I))
2784 return NV;
2785 }
2786 }
2787
2788 // 0 / X == 0, we don't need to preserve faults!
2789 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2790 if (LHS->equalsInt(0))
2791 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2792
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002793 // It can't be division by zero, hence it must be division by one.
2794 if (I.getType() == Type::Int1Ty)
2795 return ReplaceInstUsesWith(I, Op0);
2796
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797 return 0;
2798}
2799
2800Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2801 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2802
2803 // Handle the integer div common cases
2804 if (Instruction *Common = commonIDivTransforms(I))
2805 return Common;
2806
2807 // X udiv C^2 -> X >> C
2808 // Check to see if this is an unsigned division with an exact power of 2,
2809 // if so, convert to a right shift.
2810 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2811 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002812 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2814 }
2815
2816 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2817 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2818 if (RHSI->getOpcode() == Instruction::Shl &&
2819 isa<ConstantInt>(RHSI->getOperand(0))) {
2820 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2821 if (C1.isPowerOf2()) {
2822 Value *N = RHSI->getOperand(1);
2823 const Type *NTy = N->getType();
2824 if (uint32_t C2 = C1.logBase2()) {
2825 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002826 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002827 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002828 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002829 }
2830 }
2831 }
2832
2833 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2834 // where C1&C2 are powers of two.
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2836 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2837 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2838 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2839 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2840 // Compute the shift amounts
2841 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2842 // Construct the "on true" case of the select
2843 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002844 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002845 Op0, TC, SI->getName()+".t");
2846 TSI = InsertNewInstBefore(TSI, I);
2847
2848 // Construct the "on false" case of the select
2849 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002850 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002851 Op0, FC, SI->getName()+".f");
2852 FSI = InsertNewInstBefore(FSI, I);
2853
2854 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002855 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002856 }
2857 }
2858 return 0;
2859}
2860
2861Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2862 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2863
2864 // Handle the integer div common cases
2865 if (Instruction *Common = commonIDivTransforms(I))
2866 return Common;
2867
2868 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2869 // sdiv X, -1 == -X
2870 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002871 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002872
2873 // -X/C -> X/-C
2874 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00002875 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002876 }
2877
2878 // If the sign bits of both operands are zero (i.e. we can prove they are
2879 // unsigned inputs), turn this into a udiv.
2880 if (I.getType()->isInteger()) {
2881 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2882 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002883 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002884 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002885 }
2886 }
2887
2888 return 0;
2889}
2890
2891Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2892 return commonDivTransforms(I);
2893}
2894
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895/// This function implements the transforms on rem instructions that work
2896/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2897/// is used by the visitors to those instructions.
2898/// @brief Transforms common to all three rem instructions
2899Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2900 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2901
Chris Lattner653ef3c2008-02-19 06:12:18 +00002902 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 if (Constant *LHS = dyn_cast<Constant>(Op0))
2904 if (LHS->isNullValue())
2905 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2906
Chris Lattner653ef3c2008-02-19 06:12:18 +00002907 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2908 if (I.getType()->isFPOrFPVector())
2909 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002911 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002912 if (isa<UndefValue>(Op1))
2913 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2914
2915 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00002916 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2917 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918
2919 return 0;
2920}
2921
2922/// This function implements the transforms common to both integer remainder
2923/// instructions (urem and srem). It is called by the visitors to those integer
2924/// remainder instructions.
2925/// @brief Common integer remainder transforms
2926Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2927 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2928
2929 if (Instruction *common = commonRemTransforms(I))
2930 return common;
2931
2932 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2933 // X % 0 == undef, we don't need to preserve faults!
2934 if (RHS->equalsInt(0))
2935 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2936
2937 if (RHS->equalsInt(1)) // X % 1 == 0
2938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2939
2940 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2941 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2942 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2943 return R;
2944 } else if (isa<PHINode>(Op0I)) {
2945 if (Instruction *NV = FoldOpIntoPhi(I))
2946 return NV;
2947 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00002948
2949 // See if we can fold away this rem instruction.
2950 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2951 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2952 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2953 KnownZero, KnownOne))
2954 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002955 }
2956 }
2957
2958 return 0;
2959}
2960
2961Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2963
2964 if (Instruction *common = commonIRemTransforms(I))
2965 return common;
2966
2967 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2968 // X urem C^2 -> X and C
2969 // Check to see if this is an unsigned remainder with an exact power of 2,
2970 // if so, convert to a bitwise and.
2971 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2972 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00002973 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974 }
2975
2976 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2977 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2978 if (RHSI->getOpcode() == Instruction::Shl &&
2979 isa<ConstantInt>(RHSI->getOperand(0))) {
2980 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2981 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00002982 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002984 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002985 }
2986 }
2987 }
2988
2989 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2990 // where C1&C2 are powers of two.
2991 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2992 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2993 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2994 // STO == 0 and SFO == 0 handled above.
2995 if ((STO->getValue().isPowerOf2()) &&
2996 (SFO->getValue().isPowerOf2())) {
2997 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002998 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002999 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003000 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003001 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003002 }
3003 }
3004 }
3005
3006 return 0;
3007}
3008
3009Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3011
Dan Gohmandb3dd962007-11-05 23:16:33 +00003012 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 if (Instruction *common = commonIRemTransforms(I))
3014 return common;
3015
3016 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003017 if (!isa<Constant>(RHSNeg) ||
3018 (isa<ConstantInt>(RHSNeg) &&
3019 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 // X % -Y -> X % Y
3021 AddUsesToWorkList(I);
3022 I.setOperand(1, RHSNeg);
3023 return &I;
3024 }
3025
Dan Gohmandb3dd962007-11-05 23:16:33 +00003026 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003028 if (I.getType()->isInteger()) {
3029 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3030 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3031 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003032 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003033 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003034 }
3035
3036 return 0;
3037}
3038
3039Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3040 return commonRemTransforms(I);
3041}
3042
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043// isOneBitSet - Return true if there is exactly one bit set in the specified
3044// constant.
3045static bool isOneBitSet(const ConstantInt *CI) {
3046 return CI->getValue().isPowerOf2();
3047}
3048
3049// isHighOnes - Return true if the constant is of the form 1+0+.
3050// This is the same as lowones(~X).
3051static bool isHighOnes(const ConstantInt *CI) {
3052 return (~CI->getValue() + 1).isPowerOf2();
3053}
3054
3055/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3056/// are carefully arranged to allow folding of expressions such as:
3057///
3058/// (A < B) | (A > B) --> (A != B)
3059///
3060/// Note that this is only valid if the first and second predicates have the
3061/// same sign. Is illegal to do: (A u< B) | (A s> B)
3062///
3063/// Three bits are used to represent the condition, as follows:
3064/// 0 A > B
3065/// 1 A == B
3066/// 2 A < B
3067///
3068/// <=> Value Definition
3069/// 000 0 Always false
3070/// 001 1 A > B
3071/// 010 2 A == B
3072/// 011 3 A >= B
3073/// 100 4 A < B
3074/// 101 5 A != B
3075/// 110 6 A <= B
3076/// 111 7 Always true
3077///
3078static unsigned getICmpCode(const ICmpInst *ICI) {
3079 switch (ICI->getPredicate()) {
3080 // False -> 0
3081 case ICmpInst::ICMP_UGT: return 1; // 001
3082 case ICmpInst::ICMP_SGT: return 1; // 001
3083 case ICmpInst::ICMP_EQ: return 2; // 010
3084 case ICmpInst::ICMP_UGE: return 3; // 011
3085 case ICmpInst::ICMP_SGE: return 3; // 011
3086 case ICmpInst::ICMP_ULT: return 4; // 100
3087 case ICmpInst::ICMP_SLT: return 4; // 100
3088 case ICmpInst::ICMP_NE: return 5; // 101
3089 case ICmpInst::ICMP_ULE: return 6; // 110
3090 case ICmpInst::ICMP_SLE: return 6; // 110
3091 // True -> 7
3092 default:
3093 assert(0 && "Invalid ICmp predicate!");
3094 return 0;
3095 }
3096}
3097
3098/// getICmpValue - This is the complement of getICmpCode, which turns an
3099/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003100/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003101/// of predicate to use in new icmp instructions.
3102static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3103 switch (code) {
3104 default: assert(0 && "Illegal ICmp code!");
3105 case 0: return ConstantInt::getFalse();
3106 case 1:
3107 if (sign)
3108 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3109 else
3110 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3111 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3112 case 3:
3113 if (sign)
3114 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3115 else
3116 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3117 case 4:
3118 if (sign)
3119 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3120 else
3121 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3122 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3123 case 6:
3124 if (sign)
3125 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3126 else
3127 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3128 case 7: return ConstantInt::getTrue();
3129 }
3130}
3131
3132static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3133 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3134 (ICmpInst::isSignedPredicate(p1) &&
3135 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3136 (ICmpInst::isSignedPredicate(p2) &&
3137 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3138}
3139
3140namespace {
3141// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3142struct FoldICmpLogical {
3143 InstCombiner &IC;
3144 Value *LHS, *RHS;
3145 ICmpInst::Predicate pred;
3146 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3147 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3148 pred(ICI->getPredicate()) {}
3149 bool shouldApply(Value *V) const {
3150 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3151 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003152 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3153 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 return false;
3155 }
3156 Instruction *apply(Instruction &Log) const {
3157 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3158 if (ICI->getOperand(0) != LHS) {
3159 assert(ICI->getOperand(1) == LHS);
3160 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3161 }
3162
3163 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3164 unsigned LHSCode = getICmpCode(ICI);
3165 unsigned RHSCode = getICmpCode(RHSICI);
3166 unsigned Code;
3167 switch (Log.getOpcode()) {
3168 case Instruction::And: Code = LHSCode & RHSCode; break;
3169 case Instruction::Or: Code = LHSCode | RHSCode; break;
3170 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3171 default: assert(0 && "Illegal logical opcode!"); return 0;
3172 }
3173
3174 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3175 ICmpInst::isSignedPredicate(ICI->getPredicate());
3176
3177 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3178 if (Instruction *I = dyn_cast<Instruction>(RV))
3179 return I;
3180 // Otherwise, it's a constant boolean value...
3181 return IC.ReplaceInstUsesWith(Log, RV);
3182 }
3183};
3184} // end anonymous namespace
3185
3186// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3187// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3188// guaranteed to be a binary operator.
3189Instruction *InstCombiner::OptAndOp(Instruction *Op,
3190 ConstantInt *OpRHS,
3191 ConstantInt *AndRHS,
3192 BinaryOperator &TheAnd) {
3193 Value *X = Op->getOperand(0);
3194 Constant *Together = 0;
3195 if (!Op->isShift())
3196 Together = And(AndRHS, OpRHS);
3197
3198 switch (Op->getOpcode()) {
3199 case Instruction::Xor:
3200 if (Op->hasOneUse()) {
3201 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003202 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203 InsertNewInstBefore(And, TheAnd);
3204 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003205 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003206 }
3207 break;
3208 case Instruction::Or:
3209 if (Together == AndRHS) // (X | C) & C --> C
3210 return ReplaceInstUsesWith(TheAnd, AndRHS);
3211
3212 if (Op->hasOneUse() && Together != OpRHS) {
3213 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003214 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 InsertNewInstBefore(Or, TheAnd);
3216 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003217 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 }
3219 break;
3220 case Instruction::Add:
3221 if (Op->hasOneUse()) {
3222 // Adding a one to a single bit bit-field should be turned into an XOR
3223 // of the bit. First thing to check is to see if this AND is with a
3224 // single bit constant.
3225 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3226
3227 // If there is only one bit set...
3228 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3229 // Ok, at this point, we know that we are masking the result of the
3230 // ADD down to exactly one bit. If the constant we are adding has
3231 // no bits set below this bit, then we can eliminate the ADD.
3232 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3233
3234 // Check to see if any bits below the one bit set in AndRHSV are set.
3235 if ((AddRHS & (AndRHSV-1)) == 0) {
3236 // If not, the only thing that can effect the output of the AND is
3237 // the bit specified by AndRHSV. If that bit is set, the effect of
3238 // the XOR is to toggle the bit. If it is clear, then the ADD has
3239 // no effect.
3240 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3241 TheAnd.setOperand(0, X);
3242 return &TheAnd;
3243 } else {
3244 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003245 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003246 InsertNewInstBefore(NewAnd, TheAnd);
3247 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003248 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 }
3250 }
3251 }
3252 }
3253 break;
3254
3255 case Instruction::Shl: {
3256 // We know that the AND will not produce any of the bits shifted in, so if
3257 // the anded constant includes them, clear them now!
3258 //
3259 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3260 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3261 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3262 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3263
3264 if (CI->getValue() == ShlMask) {
3265 // Masking out bits that the shift already masks
3266 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3267 } else if (CI != AndRHS) { // Reducing bits set in and.
3268 TheAnd.setOperand(1, CI);
3269 return &TheAnd;
3270 }
3271 break;
3272 }
3273 case Instruction::LShr:
3274 {
3275 // We know that the AND will not produce any of the bits shifted in, so if
3276 // the anded constant includes them, clear them now! This only applies to
3277 // unsigned shifts, because a signed shr may bring in set bits!
3278 //
3279 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3280 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3281 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3282 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3283
3284 if (CI->getValue() == ShrMask) {
3285 // Masking out bits that the shift already masks.
3286 return ReplaceInstUsesWith(TheAnd, Op);
3287 } else if (CI != AndRHS) {
3288 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3289 return &TheAnd;
3290 }
3291 break;
3292 }
3293 case Instruction::AShr:
3294 // Signed shr.
3295 // See if this is shifting in some sign extension, then masking it out
3296 // with an and.
3297 if (Op->hasOneUse()) {
3298 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3299 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3300 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3301 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3302 if (C == AndRHS) { // Masking out bits shifted in.
3303 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3304 // Make the argument unsigned.
3305 Value *ShVal = Op->getOperand(0);
3306 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003307 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003309 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003310 }
3311 }
3312 break;
3313 }
3314 return 0;
3315}
3316
3317
3318/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3319/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3320/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3321/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3322/// insert new instructions.
3323Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3324 bool isSigned, bool Inside,
3325 Instruction &IB) {
3326 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3327 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3328 "Lo is not <= Hi in range emission code!");
3329
3330 if (Inside) {
3331 if (Lo == Hi) // Trivially false.
3332 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3333
3334 // V >= Min && V < Hi --> V < Hi
3335 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3336 ICmpInst::Predicate pred = (isSigned ?
3337 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3338 return new ICmpInst(pred, V, Hi);
3339 }
3340
3341 // Emit V-Lo <u Hi-Lo
3342 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003343 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344 InsertNewInstBefore(Add, IB);
3345 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3346 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3347 }
3348
3349 if (Lo == Hi) // Trivially true.
3350 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3351
3352 // V < Min || V >= Hi -> V > Hi-1
3353 Hi = SubOne(cast<ConstantInt>(Hi));
3354 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3355 ICmpInst::Predicate pred = (isSigned ?
3356 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3357 return new ICmpInst(pred, V, Hi);
3358 }
3359
3360 // Emit V-Lo >u Hi-1-Lo
3361 // Note that Hi has already had one subtracted from it, above.
3362 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003363 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003364 InsertNewInstBefore(Add, IB);
3365 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3366 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3367}
3368
3369// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3370// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3371// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3372// not, since all 1s are not contiguous.
3373static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3374 const APInt& V = Val->getValue();
3375 uint32_t BitWidth = Val->getType()->getBitWidth();
3376 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3377
3378 // look for the first zero bit after the run of ones
3379 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3380 // look for the first non-zero bit
3381 ME = V.getActiveBits();
3382 return true;
3383}
3384
3385/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3386/// where isSub determines whether the operator is a sub. If we can fold one of
3387/// the following xforms:
3388///
3389/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3390/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3391/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3392///
3393/// return (A +/- B).
3394///
3395Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3396 ConstantInt *Mask, bool isSub,
3397 Instruction &I) {
3398 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3399 if (!LHSI || LHSI->getNumOperands() != 2 ||
3400 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3401
3402 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3403
3404 switch (LHSI->getOpcode()) {
3405 default: return 0;
3406 case Instruction::And:
3407 if (And(N, Mask) == Mask) {
3408 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3409 if ((Mask->getValue().countLeadingZeros() +
3410 Mask->getValue().countPopulation()) ==
3411 Mask->getValue().getBitWidth())
3412 break;
3413
3414 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3415 // part, we don't need any explicit masks to take them out of A. If that
3416 // is all N is, ignore it.
3417 uint32_t MB = 0, ME = 0;
3418 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3419 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3420 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3421 if (MaskedValueIsZero(RHS, Mask))
3422 break;
3423 }
3424 }
3425 return 0;
3426 case Instruction::Or:
3427 case Instruction::Xor:
3428 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3429 if ((Mask->getValue().countLeadingZeros() +
3430 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3431 && And(N, Mask)->isZero())
3432 break;
3433 return 0;
3434 }
3435
3436 Instruction *New;
3437 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003438 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003439 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003440 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003441 return InsertNewInstBefore(New, I);
3442}
3443
3444Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3445 bool Changed = SimplifyCommutative(I);
3446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3447
3448 if (isa<UndefValue>(Op1)) // X & undef -> 0
3449 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3450
3451 // and X, X = X
3452 if (Op0 == Op1)
3453 return ReplaceInstUsesWith(I, Op1);
3454
3455 // See if we can simplify any instructions used by the instruction whose sole
3456 // purpose is to compute bits we don't care about.
3457 if (!isa<VectorType>(I.getType())) {
3458 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3459 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3460 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3461 KnownZero, KnownOne))
3462 return &I;
3463 } else {
3464 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3465 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3466 return ReplaceInstUsesWith(I, I.getOperand(0));
3467 } else if (isa<ConstantAggregateZero>(Op1)) {
3468 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3469 }
3470 }
3471
3472 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3473 const APInt& AndRHSMask = AndRHS->getValue();
3474 APInt NotAndRHS(~AndRHSMask);
3475
3476 // Optimize a variety of ((val OP C1) & C2) combinations...
3477 if (isa<BinaryOperator>(Op0)) {
3478 Instruction *Op0I = cast<Instruction>(Op0);
3479 Value *Op0LHS = Op0I->getOperand(0);
3480 Value *Op0RHS = Op0I->getOperand(1);
3481 switch (Op0I->getOpcode()) {
3482 case Instruction::Xor:
3483 case Instruction::Or:
3484 // If the mask is only needed on one incoming arm, push it up.
3485 if (Op0I->hasOneUse()) {
3486 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3487 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003488 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489 Op0RHS->getName()+".masked");
3490 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003491 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003492 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3493 }
3494 if (!isa<Constant>(Op0RHS) &&
3495 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3496 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003497 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003498 Op0LHS->getName()+".masked");
3499 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003500 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003501 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3502 }
3503 }
3504
3505 break;
3506 case Instruction::Add:
3507 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3508 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3509 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3510 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003511 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003513 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514 break;
3515
3516 case Instruction::Sub:
3517 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3518 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3519 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3520 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003521 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003522
Nick Lewyckya349ba42008-07-10 05:51:40 +00003523 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3524 // has 1's for all bits that the subtraction with A might affect.
3525 if (Op0I->hasOneUse()) {
3526 uint32_t BitWidth = AndRHSMask.getBitWidth();
3527 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3528 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3529
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003530 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00003531 if (!(A && A->isZero()) && // avoid infinite recursion.
3532 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003533 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3534 InsertNewInstBefore(NewNeg, I);
3535 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3536 }
3537 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003538 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003539
3540 case Instruction::Shl:
3541 case Instruction::LShr:
3542 // (1 << x) & 1 --> zext(x == 0)
3543 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00003544 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003545 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3546 Constant::getNullValue(I.getType()));
3547 InsertNewInstBefore(NewICmp, I);
3548 return new ZExtInst(NewICmp, I.getType());
3549 }
3550 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003551 }
3552
3553 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3554 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3555 return Res;
3556 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3557 // If this is an integer truncation or change from signed-to-unsigned, and
3558 // if the source is an and/or with immediate, transform it. This
3559 // frequently occurs for bitfield accesses.
3560 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3561 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3562 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003563 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003564 if (CastOp->getOpcode() == Instruction::And) {
3565 // Change: and (cast (and X, C1) to T), C2
3566 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3567 // This will fold the two constants together, which may allow
3568 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003569 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570 CastOp->getOperand(0), I.getType(),
3571 CastOp->getName()+".shrunk");
3572 NewCast = InsertNewInstBefore(NewCast, I);
3573 // trunc_or_bitcast(C1)&C2
3574 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3575 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003576 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577 } else if (CastOp->getOpcode() == Instruction::Or) {
3578 // Change: and (cast (or X, C1) to T), C2
3579 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3580 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3581 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3582 return ReplaceInstUsesWith(I, AndRHS);
3583 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003584 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003585 }
3586 }
3587
3588 // Try to fold constant and into select arguments.
3589 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3590 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3591 return R;
3592 if (isa<PHINode>(Op0))
3593 if (Instruction *NV = FoldOpIntoPhi(I))
3594 return NV;
3595 }
3596
3597 Value *Op0NotVal = dyn_castNotVal(Op0);
3598 Value *Op1NotVal = dyn_castNotVal(Op1);
3599
3600 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3601 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3602
3603 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3604 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003605 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003606 I.getName()+".demorgan");
3607 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003608 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003609 }
3610
3611 {
3612 Value *A = 0, *B = 0, *C = 0, *D = 0;
3613 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3614 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3615 return ReplaceInstUsesWith(I, Op1);
3616
3617 // (A|B) & ~(A&B) -> A^B
3618 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3619 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003620 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003621 }
3622 }
3623
3624 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3625 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3626 return ReplaceInstUsesWith(I, Op0);
3627
3628 // ~(A&B) & (A|B) -> A^B
3629 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3630 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003631 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003632 }
3633 }
3634
3635 if (Op0->hasOneUse() &&
3636 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3637 if (A == Op1) { // (A^B)&A -> A&(A^B)
3638 I.swapOperands(); // Simplify below
3639 std::swap(Op0, Op1);
3640 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3641 cast<BinaryOperator>(Op0)->swapOperands();
3642 I.swapOperands(); // Simplify below
3643 std::swap(Op0, Op1);
3644 }
3645 }
3646 if (Op1->hasOneUse() &&
3647 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3648 if (B == Op0) { // B&(A^B) -> B&(B^A)
3649 cast<BinaryOperator>(Op1)->swapOperands();
3650 std::swap(A, B);
3651 }
3652 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003653 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003655 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003656 }
3657 }
3658 }
3659
Nick Lewycky771d6052008-08-06 04:54:03 +00003660 { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3661 // where C is a power of 2
3662 Value *A, *B;
3663 ConstantInt *C1, *C2;
Evan Cheng94fd9742008-08-20 23:36:48 +00003664 ICmpInst::Predicate LHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3665 ICmpInst::Predicate RHSCC = ICmpInst::BAD_ICMP_PREDICATE;
Nick Lewycky771d6052008-08-06 04:54:03 +00003666 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3667 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3668 if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3669 C1->getValue().isPowerOf2()) {
3670 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3671 InsertNewInstBefore(NewOr, I);
3672 return new ICmpInst(LHSCC, NewOr, C1);
3673 }
3674 }
3675
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003676 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3677 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3678 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3679 return R;
3680
3681 Value *LHSVal, *RHSVal;
3682 ConstantInt *LHSCst, *RHSCst;
3683 ICmpInst::Predicate LHSCC, RHSCC;
3684 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3685 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3686 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3687 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3688 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3689 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3690 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003691 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3692
3693 // Don't try to fold ICMP_SLT + ICMP_ULT.
3694 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3695 ICmpInst::isSignedPredicate(LHSCC) ==
3696 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003698 ICmpInst::Predicate GT;
3699 if (ICmpInst::isSignedPredicate(LHSCC) ||
3700 (ICmpInst::isEquality(LHSCC) &&
3701 ICmpInst::isSignedPredicate(RHSCC)))
3702 GT = ICmpInst::ICMP_SGT;
3703 else
3704 GT = ICmpInst::ICMP_UGT;
3705
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3707 ICmpInst *LHS = cast<ICmpInst>(Op0);
3708 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3709 std::swap(LHS, RHS);
3710 std::swap(LHSCst, RHSCst);
3711 std::swap(LHSCC, RHSCC);
3712 }
3713
3714 // At this point, we know we have have two icmp instructions
3715 // comparing a value against two constants and and'ing the result
3716 // together. Because of the above check, we know that we only have
3717 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3718 // (from the FoldICmpLogical check above), that the two constants
3719 // are not equal and that the larger constant is on the RHS
3720 assert(LHSCst != RHSCst && "Compares not folded above?");
3721
3722 switch (LHSCC) {
3723 default: assert(0 && "Unknown integer condition code!");
3724 case ICmpInst::ICMP_EQ:
3725 switch (RHSCC) {
3726 default: assert(0 && "Unknown integer condition code!");
3727 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3728 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3729 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3730 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3731 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3732 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3733 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3734 return ReplaceInstUsesWith(I, LHS);
3735 }
3736 case ICmpInst::ICMP_NE:
3737 switch (RHSCC) {
3738 default: assert(0 && "Unknown integer condition code!");
3739 case ICmpInst::ICMP_ULT:
3740 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3741 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3742 break; // (X != 13 & X u< 15) -> no change
3743 case ICmpInst::ICMP_SLT:
3744 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3745 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3746 break; // (X != 13 & X s< 15) -> no change
3747 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3748 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3749 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3750 return ReplaceInstUsesWith(I, RHS);
3751 case ICmpInst::ICMP_NE:
3752 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3753 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00003754 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003755 LHSVal->getName()+".off");
3756 InsertNewInstBefore(Add, I);
3757 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3758 ConstantInt::get(Add->getType(), 1));
3759 }
3760 break; // (X != 13 & X != 15) -> no change
3761 }
3762 break;
3763 case ICmpInst::ICMP_ULT:
3764 switch (RHSCC) {
3765 default: assert(0 && "Unknown integer condition code!");
3766 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3767 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3768 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3769 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3770 break;
3771 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3772 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3773 return ReplaceInstUsesWith(I, LHS);
3774 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3775 break;
3776 }
3777 break;
3778 case ICmpInst::ICMP_SLT:
3779 switch (RHSCC) {
3780 default: assert(0 && "Unknown integer condition code!");
3781 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3782 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3783 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3784 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3785 break;
3786 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3787 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3788 return ReplaceInstUsesWith(I, LHS);
3789 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3790 break;
3791 }
3792 break;
3793 case ICmpInst::ICMP_UGT:
3794 switch (RHSCC) {
3795 default: assert(0 && "Unknown integer condition code!");
Eli Friedman22b85622008-06-21 23:36:13 +00003796 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003797 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3798 return ReplaceInstUsesWith(I, RHS);
3799 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3800 break;
3801 case ICmpInst::ICMP_NE:
3802 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3803 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3804 break; // (X u> 13 & X != 15) -> no change
3805 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3806 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3807 true, I);
3808 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3809 break;
3810 }
3811 break;
3812 case ICmpInst::ICMP_SGT:
3813 switch (RHSCC) {
3814 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003815 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003816 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3817 return ReplaceInstUsesWith(I, RHS);
3818 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3819 break;
3820 case ICmpInst::ICMP_NE:
3821 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3822 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3823 break; // (X s> 13 & X != 15) -> no change
3824 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3825 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3826 true, I);
3827 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3828 break;
3829 }
3830 break;
3831 }
3832 }
3833 }
3834
3835 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3836 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3837 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3838 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3839 const Type *SrcTy = Op0C->getOperand(0)->getType();
3840 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3841 // Only do this if the casts both really cause code to be generated.
3842 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3843 I.getType(), TD) &&
3844 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3845 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003846 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003847 Op1C->getOperand(0),
3848 I.getName());
3849 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003850 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003851 }
3852 }
3853
3854 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3855 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3856 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3857 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3858 SI0->getOperand(1) == SI1->getOperand(1) &&
3859 (SI0->hasOneUse() || SI1->hasOneUse())) {
3860 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00003861 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003862 SI1->getOperand(0),
3863 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003864 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003865 SI1->getOperand(1));
3866 }
3867 }
3868
Chris Lattner91882432007-10-24 05:38:08 +00003869 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3870 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3871 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3872 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3873 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3874 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3875 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3876 // If either of the constants are nans, then the whole thing returns
3877 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003878 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003879 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3880 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3881 RHS->getOperand(0));
3882 }
3883 }
3884 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003885
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003886 return Changed ? &I : 0;
3887}
3888
3889/// CollectBSwapParts - Look to see if the specified value defines a single byte
3890/// in the result. If it does, and if the specified byte hasn't been filled in
3891/// yet, fill it in and return false.
3892static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3893 Instruction *I = dyn_cast<Instruction>(V);
3894 if (I == 0) return true;
3895
3896 // If this is an or instruction, it is an inner node of the bswap.
3897 if (I->getOpcode() == Instruction::Or)
3898 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3899 CollectBSwapParts(I->getOperand(1), ByteValues);
3900
3901 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3902 // If this is a shift by a constant int, and it is "24", then its operand
3903 // defines a byte. We only handle unsigned types here.
3904 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3905 // Not shifting the entire input by N-1 bytes?
3906 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3907 8*(ByteValues.size()-1))
3908 return true;
3909
3910 unsigned DestNo;
3911 if (I->getOpcode() == Instruction::Shl) {
3912 // X << 24 defines the top byte with the lowest of the input bytes.
3913 DestNo = ByteValues.size()-1;
3914 } else {
3915 // X >>u 24 defines the low byte with the highest of the input bytes.
3916 DestNo = 0;
3917 }
3918
3919 // If the destination byte value is already defined, the values are or'd
3920 // together, which isn't a bswap (unless it's an or of the same bits).
3921 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3922 return true;
3923 ByteValues[DestNo] = I->getOperand(0);
3924 return false;
3925 }
3926
3927 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3928 // don't have this.
3929 Value *Shift = 0, *ShiftLHS = 0;
3930 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3931 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3932 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3933 return true;
3934 Instruction *SI = cast<Instruction>(Shift);
3935
3936 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3937 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3938 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3939 return true;
3940
3941 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3942 unsigned DestByte;
3943 if (AndAmt->getValue().getActiveBits() > 64)
3944 return true;
3945 uint64_t AndAmtVal = AndAmt->getZExtValue();
3946 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3947 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3948 break;
3949 // Unknown mask for bswap.
3950 if (DestByte == ByteValues.size()) return true;
3951
3952 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3953 unsigned SrcByte;
3954 if (SI->getOpcode() == Instruction::Shl)
3955 SrcByte = DestByte - ShiftBytes;
3956 else
3957 SrcByte = DestByte + ShiftBytes;
3958
3959 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3960 if (SrcByte != ByteValues.size()-DestByte-1)
3961 return true;
3962
3963 // If the destination byte value is already defined, the values are or'd
3964 // together, which isn't a bswap (unless it's an or of the same bits).
3965 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3966 return true;
3967 ByteValues[DestByte] = SI->getOperand(0);
3968 return false;
3969}
3970
3971/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3972/// If so, insert the new bswap intrinsic and return it.
3973Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3974 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3975 if (!ITy || ITy->getBitWidth() % 16)
3976 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3977
3978 /// ByteValues - For each byte of the result, we keep track of which value
3979 /// defines each byte.
3980 SmallVector<Value*, 8> ByteValues;
3981 ByteValues.resize(ITy->getBitWidth()/8);
3982
3983 // Try to find all the pieces corresponding to the bswap.
3984 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3985 CollectBSwapParts(I.getOperand(1), ByteValues))
3986 return 0;
3987
3988 // Check to see if all of the bytes come from the same value.
3989 Value *V = ByteValues[0];
3990 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3991
3992 // Check to make sure that all of the bytes come from the same value.
3993 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3994 if (ByteValues[i] != V)
3995 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003996 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003997 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003998 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003999 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004000}
4001
4002
4003Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4004 bool Changed = SimplifyCommutative(I);
4005 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4006
4007 if (isa<UndefValue>(Op1)) // X | undef -> -1
4008 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4009
4010 // or X, X = X
4011 if (Op0 == Op1)
4012 return ReplaceInstUsesWith(I, Op0);
4013
4014 // See if we can simplify any instructions used by the instruction whose sole
4015 // purpose is to compute bits we don't care about.
4016 if (!isa<VectorType>(I.getType())) {
4017 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4018 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4019 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4020 KnownZero, KnownOne))
4021 return &I;
4022 } else if (isa<ConstantAggregateZero>(Op1)) {
4023 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4024 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4025 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4026 return ReplaceInstUsesWith(I, I.getOperand(1));
4027 }
4028
4029
4030
4031 // or X, -1 == -1
4032 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4033 ConstantInt *C1 = 0; Value *X = 0;
4034 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4035 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004036 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004037 InsertNewInstBefore(Or, I);
4038 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004039 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004040 ConstantInt::get(RHS->getValue() | C1->getValue()));
4041 }
4042
4043 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4044 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004045 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004046 InsertNewInstBefore(Or, I);
4047 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004048 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004049 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4050 }
4051
4052 // Try to fold constant and into select arguments.
4053 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4054 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4055 return R;
4056 if (isa<PHINode>(Op0))
4057 if (Instruction *NV = FoldOpIntoPhi(I))
4058 return NV;
4059 }
4060
4061 Value *A = 0, *B = 0;
4062 ConstantInt *C1 = 0, *C2 = 0;
4063
4064 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4065 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4066 return ReplaceInstUsesWith(I, Op1);
4067 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4068 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4069 return ReplaceInstUsesWith(I, Op0);
4070
4071 // (A | B) | C and A | (B | C) -> bswap if possible.
4072 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4073 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4074 match(Op1, m_Or(m_Value(), m_Value())) ||
4075 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4076 match(Op1, m_Shift(m_Value(), m_Value())))) {
4077 if (Instruction *BSwap = MatchBSwap(I))
4078 return BSwap;
4079 }
4080
4081 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4082 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4083 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004084 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004085 InsertNewInstBefore(NOr, I);
4086 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004087 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004088 }
4089
4090 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4091 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4092 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004093 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004094 InsertNewInstBefore(NOr, I);
4095 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004096 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004097 }
4098
4099 // (A & C)|(B & D)
4100 Value *C = 0, *D = 0;
4101 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4102 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4103 Value *V1 = 0, *V2 = 0, *V3 = 0;
4104 C1 = dyn_cast<ConstantInt>(C);
4105 C2 = dyn_cast<ConstantInt>(D);
4106 if (C1 && C2) { // (A & C1)|(B & C2)
4107 // If we have: ((V + N) & C1) | (V & C2)
4108 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4109 // replace with V+N.
4110 if (C1->getValue() == ~C2->getValue()) {
4111 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4112 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4113 // Add commutes, try both ways.
4114 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4115 return ReplaceInstUsesWith(I, A);
4116 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4117 return ReplaceInstUsesWith(I, A);
4118 }
4119 // Or commutes, try both ways.
4120 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4121 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4122 // Add commutes, try both ways.
4123 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4124 return ReplaceInstUsesWith(I, B);
4125 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4126 return ReplaceInstUsesWith(I, B);
4127 }
4128 }
4129 V1 = 0; V2 = 0; V3 = 0;
4130 }
4131
4132 // Check to see if we have any common things being and'ed. If so, find the
4133 // terms for V1 & (V2|V3).
4134 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4135 if (A == B) // (A & C)|(A & D) == A & (C|D)
4136 V1 = A, V2 = C, V3 = D;
4137 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4138 V1 = A, V2 = B, V3 = C;
4139 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4140 V1 = C, V2 = A, V3 = D;
4141 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4142 V1 = C, V2 = A, V3 = B;
4143
4144 if (V1) {
4145 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004146 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4147 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004148 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149 }
4150 }
4151
4152 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4153 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4154 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4155 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4156 SI0->getOperand(1) == SI1->getOperand(1) &&
4157 (SI0->hasOneUse() || SI1->hasOneUse())) {
4158 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004159 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160 SI1->getOperand(0),
4161 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004162 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004163 SI1->getOperand(1));
4164 }
4165 }
4166
4167 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4168 if (A == Op1) // ~A | A == -1
4169 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4170 } else {
4171 A = 0;
4172 }
4173 // Note, A is still live here!
4174 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4175 if (Op0 == B)
4176 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4177
4178 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4179 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004180 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004181 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004182 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004183 }
4184 }
4185
4186 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4187 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4188 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4189 return R;
4190
4191 Value *LHSVal, *RHSVal;
4192 ConstantInt *LHSCst, *RHSCst;
4193 ICmpInst::Predicate LHSCC, RHSCC;
4194 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4195 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4196 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4197 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4198 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4199 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4200 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4201 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4202 // We can't fold (ugt x, C) | (sgt x, C2).
4203 PredicatesFoldable(LHSCC, RHSCC)) {
4204 // Ensure that the larger constant is on the RHS.
4205 ICmpInst *LHS = cast<ICmpInst>(Op0);
4206 bool NeedsSwap;
4207 if (ICmpInst::isSignedPredicate(LHSCC))
4208 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4209 else
4210 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4211
4212 if (NeedsSwap) {
4213 std::swap(LHS, RHS);
4214 std::swap(LHSCst, RHSCst);
4215 std::swap(LHSCC, RHSCC);
4216 }
4217
4218 // At this point, we know we have have two icmp instructions
4219 // comparing a value against two constants and or'ing the result
4220 // together. Because of the above check, we know that we only have
4221 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4222 // FoldICmpLogical check above), that the two constants are not
4223 // equal.
4224 assert(LHSCst != RHSCst && "Compares not folded above?");
4225
4226 switch (LHSCC) {
4227 default: assert(0 && "Unknown integer condition code!");
4228 case ICmpInst::ICMP_EQ:
4229 switch (RHSCC) {
4230 default: assert(0 && "Unknown integer condition code!");
4231 case ICmpInst::ICMP_EQ:
4232 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4233 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004234 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235 LHSVal->getName()+".off");
4236 InsertNewInstBefore(Add, I);
4237 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4238 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4239 }
4240 break; // (X == 13 | X == 15) -> no change
4241 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4242 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4243 break;
4244 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4245 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4246 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4247 return ReplaceInstUsesWith(I, RHS);
4248 }
4249 break;
4250 case ICmpInst::ICMP_NE:
4251 switch (RHSCC) {
4252 default: assert(0 && "Unknown integer condition code!");
4253 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4254 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4255 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4256 return ReplaceInstUsesWith(I, LHS);
4257 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4258 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4259 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4260 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4261 }
4262 break;
4263 case ICmpInst::ICMP_ULT:
4264 switch (RHSCC) {
4265 default: assert(0 && "Unknown integer condition code!");
4266 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4267 break;
4268 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004269 // If RHSCst is [us]MAXINT, it is always false. Not handling
4270 // this can cause overflow.
4271 if (RHSCst->isMaxValue(false))
4272 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004273 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4274 false, I);
4275 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4276 break;
4277 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4278 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4279 return ReplaceInstUsesWith(I, RHS);
4280 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4281 break;
4282 }
4283 break;
4284 case ICmpInst::ICMP_SLT:
4285 switch (RHSCC) {
4286 default: assert(0 && "Unknown integer condition code!");
4287 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4288 break;
4289 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004290 // If RHSCst is [us]MAXINT, it is always false. Not handling
4291 // this can cause overflow.
4292 if (RHSCst->isMaxValue(true))
4293 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004294 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4295 false, I);
4296 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4297 break;
4298 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4299 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4300 return ReplaceInstUsesWith(I, RHS);
4301 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4302 break;
4303 }
4304 break;
4305 case ICmpInst::ICMP_UGT:
4306 switch (RHSCC) {
4307 default: assert(0 && "Unknown integer condition code!");
4308 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4309 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4310 return ReplaceInstUsesWith(I, LHS);
4311 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4312 break;
4313 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4314 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4315 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4316 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4317 break;
4318 }
4319 break;
4320 case ICmpInst::ICMP_SGT:
4321 switch (RHSCC) {
4322 default: assert(0 && "Unknown integer condition code!");
4323 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4324 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4325 return ReplaceInstUsesWith(I, LHS);
4326 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4327 break;
4328 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4329 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4330 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4331 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4332 break;
4333 }
4334 break;
4335 }
4336 }
4337 }
4338
4339 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004340 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004341 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4342 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004343 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4344 !isa<ICmpInst>(Op1C->getOperand(0))) {
4345 const Type *SrcTy = Op0C->getOperand(0)->getType();
4346 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4347 // Only do this if the casts both really cause code to be
4348 // generated.
4349 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4350 I.getType(), TD) &&
4351 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4352 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004353 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004354 Op1C->getOperand(0),
4355 I.getName());
4356 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004357 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004358 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004359 }
4360 }
Chris Lattner91882432007-10-24 05:38:08 +00004361 }
4362
4363
4364 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4365 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4366 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4367 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004368 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4369 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004370 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4371 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4372 // If either of the constants are nans, then the whole thing returns
4373 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004374 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004375 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4376
4377 // Otherwise, no need to compare the two constants, compare the
4378 // rest.
4379 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4380 RHS->getOperand(0));
4381 }
4382 }
4383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384
4385 return Changed ? &I : 0;
4386}
4387
Dan Gohman089efff2008-05-13 00:00:25 +00004388namespace {
4389
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004390// XorSelf - Implements: X ^ X --> 0
4391struct XorSelf {
4392 Value *RHS;
4393 XorSelf(Value *rhs) : RHS(rhs) {}
4394 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4395 Instruction *apply(BinaryOperator &Xor) const {
4396 return &Xor;
4397 }
4398};
4399
Dan Gohman089efff2008-05-13 00:00:25 +00004400}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004401
4402Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4403 bool Changed = SimplifyCommutative(I);
4404 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4405
Evan Chenge5cd8032008-03-25 20:07:13 +00004406 if (isa<UndefValue>(Op1)) {
4407 if (isa<UndefValue>(Op0))
4408 // Handle undef ^ undef -> 0 special case. This is a common
4409 // idiom (misuse).
4410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004411 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004412 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004413
4414 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4415 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004416 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4418 }
4419
4420 // See if we can simplify any instructions used by the instruction whose sole
4421 // purpose is to compute bits we don't care about.
4422 if (!isa<VectorType>(I.getType())) {
4423 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4424 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4425 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4426 KnownZero, KnownOne))
4427 return &I;
4428 } else if (isa<ConstantAggregateZero>(Op1)) {
4429 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4430 }
4431
4432 // Is this a ~ operation?
4433 if (Value *NotOp = dyn_castNotVal(&I)) {
4434 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4435 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4436 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4437 if (Op0I->getOpcode() == Instruction::And ||
4438 Op0I->getOpcode() == Instruction::Or) {
4439 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4440 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4441 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004442 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004443 Op0I->getOperand(1)->getName()+".not");
4444 InsertNewInstBefore(NotY, I);
4445 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004446 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004447 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004448 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004449 }
4450 }
4451 }
4452 }
4453
4454
4455 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004456 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4457 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4458 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004459 return new ICmpInst(ICI->getInversePredicate(),
4460 ICI->getOperand(0), ICI->getOperand(1));
4461
Nick Lewycky1405e922007-08-06 20:04:16 +00004462 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4463 return new FCmpInst(FCI->getInversePredicate(),
4464 FCI->getOperand(0), FCI->getOperand(1));
4465 }
4466
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004467 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4468 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4469 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4470 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4471 Instruction::CastOps Opcode = Op0C->getOpcode();
4472 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4473 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4474 Op0C->getDestTy())) {
4475 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4476 CI->getOpcode(), CI->getInversePredicate(),
4477 CI->getOperand(0), CI->getOperand(1)), I);
4478 NewCI->takeName(CI);
4479 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4480 }
4481 }
4482 }
4483 }
4484 }
4485
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004486 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4487 // ~(c-X) == X-c-1 == X+(-c-1)
4488 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4489 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4490 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4491 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4492 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004493 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004494 }
4495
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004496 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004497 if (Op0I->getOpcode() == Instruction::Add) {
4498 // ~(X-c) --> (-c-1)-X
4499 if (RHS->isAllOnesValue()) {
4500 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004501 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004502 ConstantExpr::getSub(NegOp0CI,
4503 ConstantInt::get(I.getType(), 1)),
4504 Op0I->getOperand(0));
4505 } else if (RHS->getValue().isSignBit()) {
4506 // (X + C) ^ signbit -> (X + C + signbit)
4507 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004508 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004509
4510 }
4511 } else if (Op0I->getOpcode() == Instruction::Or) {
4512 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4513 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4514 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4515 // Anything in both C1 and C2 is known to be zero, remove it from
4516 // NewRHS.
4517 Constant *CommonBits = And(Op0CI, RHS);
4518 NewRHS = ConstantExpr::getAnd(NewRHS,
4519 ConstantExpr::getNot(CommonBits));
4520 AddToWorkList(Op0I);
4521 I.setOperand(0, Op0I->getOperand(0));
4522 I.setOperand(1, NewRHS);
4523 return &I;
4524 }
4525 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004526 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004527 }
4528
4529 // Try to fold constant and into select arguments.
4530 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4531 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4532 return R;
4533 if (isa<PHINode>(Op0))
4534 if (Instruction *NV = FoldOpIntoPhi(I))
4535 return NV;
4536 }
4537
4538 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4539 if (X == Op1)
4540 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4541
4542 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4543 if (X == Op0)
4544 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4545
4546
4547 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4548 if (Op1I) {
4549 Value *A, *B;
4550 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4551 if (A == Op0) { // B^(B|A) == (A|B)^B
4552 Op1I->swapOperands();
4553 I.swapOperands();
4554 std::swap(Op0, Op1);
4555 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4556 I.swapOperands(); // Simplified below.
4557 std::swap(Op0, Op1);
4558 }
4559 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4560 if (Op0 == A) // A^(A^B) == B
4561 return ReplaceInstUsesWith(I, B);
4562 else if (Op0 == B) // A^(B^A) == B
4563 return ReplaceInstUsesWith(I, A);
4564 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4565 if (A == Op0) { // A^(A&B) -> A^(B&A)
4566 Op1I->swapOperands();
4567 std::swap(A, B);
4568 }
4569 if (B == Op0) { // A^(B&A) -> (B&A)^A
4570 I.swapOperands(); // Simplified below.
4571 std::swap(Op0, Op1);
4572 }
4573 }
4574 }
4575
4576 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4577 if (Op0I) {
4578 Value *A, *B;
4579 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4580 if (A == Op1) // (B|A)^B == (A|B)^B
4581 std::swap(A, B);
4582 if (B == Op1) { // (A|B)^B == A & ~B
4583 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004584 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4585 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004586 }
4587 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4588 if (Op1 == A) // (A^B)^A == B
4589 return ReplaceInstUsesWith(I, B);
4590 else if (Op1 == B) // (B^A)^A == B
4591 return ReplaceInstUsesWith(I, A);
4592 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4593 if (A == Op1) // (A&B)^A -> (B&A)^A
4594 std::swap(A, B);
4595 if (B == Op1 && // (B&A)^A == ~B & A
4596 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4597 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004598 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4599 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004600 }
4601 }
4602 }
4603
4604 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4605 if (Op0I && Op1I && Op0I->isShift() &&
4606 Op0I->getOpcode() == Op1I->getOpcode() &&
4607 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4608 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4609 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004610 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004611 Op1I->getOperand(0),
4612 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004613 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004614 Op1I->getOperand(1));
4615 }
4616
4617 if (Op0I && Op1I) {
4618 Value *A, *B, *C, *D;
4619 // (A & B)^(A | B) -> A ^ B
4620 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4621 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4622 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004623 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004624 }
4625 // (A | B)^(A & B) -> A ^ B
4626 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4627 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4628 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004629 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004630 }
4631
4632 // (A & B)^(C & D)
4633 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4634 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4635 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4636 // (X & Y)^(X & Y) -> (Y^Z) & X
4637 Value *X = 0, *Y = 0, *Z = 0;
4638 if (A == C)
4639 X = A, Y = B, Z = D;
4640 else if (A == D)
4641 X = A, Y = B, Z = C;
4642 else if (B == C)
4643 X = B, Y = A, Z = D;
4644 else if (B == D)
4645 X = B, Y = A, Z = C;
4646
4647 if (X) {
4648 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004649 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4650 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004651 }
4652 }
4653 }
4654
4655 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4656 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4657 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4658 return R;
4659
4660 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004661 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4663 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4664 const Type *SrcTy = Op0C->getOperand(0)->getType();
4665 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4666 // Only do this if the casts both really cause code to be generated.
4667 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4668 I.getType(), TD) &&
4669 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4670 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004671 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672 Op1C->getOperand(0),
4673 I.getName());
4674 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004675 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004676 }
4677 }
Chris Lattner91882432007-10-24 05:38:08 +00004678 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004679
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004680 return Changed ? &I : 0;
4681}
4682
4683/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4684/// overflowed for this type.
4685static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4686 ConstantInt *In2, bool IsSigned = false) {
4687 Result = cast<ConstantInt>(Add(In1, In2));
4688
4689 if (IsSigned)
4690 if (In2->getValue().isNegative())
4691 return Result->getValue().sgt(In1->getValue());
4692 else
4693 return Result->getValue().slt(In1->getValue());
4694 else
4695 return Result->getValue().ult(In1->getValue());
4696}
4697
Dan Gohmanb80d5612008-09-10 23:30:57 +00004698/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
4699/// overflowed for this type.
4700static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4701 ConstantInt *In2, bool IsSigned = false) {
Dan Gohman2c3b4892008-09-11 18:53:02 +00004702 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohmanb80d5612008-09-10 23:30:57 +00004703
4704 if (IsSigned)
4705 if (In2->getValue().isNegative())
4706 return Result->getValue().slt(In1->getValue());
4707 else
4708 return Result->getValue().sgt(In1->getValue());
4709 else
4710 return Result->getValue().ugt(In1->getValue());
4711}
4712
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004713/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4714/// code necessary to compute the offset from the base pointer (without adding
4715/// in the base pointer). Return the result as a signed integer of intptr size.
4716static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4717 TargetData &TD = IC.getTargetData();
4718 gep_type_iterator GTI = gep_type_begin(GEP);
4719 const Type *IntPtrTy = TD.getIntPtrType();
4720 Value *Result = Constant::getNullValue(IntPtrTy);
4721
4722 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004723 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004724 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4725
Gabor Greif17396002008-06-12 21:37:33 +00004726 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4727 ++i, ++GTI) {
4728 Value *Op = *i;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004729 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004730 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4731 if (OpC->isZero()) continue;
4732
4733 // Handle a struct index, which adds its field offset to the pointer.
4734 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4735 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4736
4737 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4738 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4739 else
4740 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004741 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004742 ConstantInt::get(IntPtrTy, Size),
4743 GEP->getName()+".offs"), I);
4744 continue;
4745 }
4746
4747 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4748 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4749 Scale = ConstantExpr::getMul(OC, Scale);
4750 if (Constant *RC = dyn_cast<Constant>(Result))
4751 Result = ConstantExpr::getAdd(RC, Scale);
4752 else {
4753 // Emit an add instruction.
4754 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004755 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004756 GEP->getName()+".offs"), I);
4757 }
4758 continue;
4759 }
4760 // Convert to correct type.
4761 if (Op->getType() != IntPtrTy) {
4762 if (Constant *OpC = dyn_cast<Constant>(Op))
4763 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4764 else
4765 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4766 Op->getName()+".c"), I);
4767 }
4768 if (Size != 1) {
4769 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4770 if (Constant *OpC = dyn_cast<Constant>(Op))
4771 Op = ConstantExpr::getMul(OpC, Scale);
4772 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00004773 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004774 GEP->getName()+".idx"), I);
4775 }
4776
4777 // Emit an add instruction.
4778 if (isa<Constant>(Op) && isa<Constant>(Result))
4779 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4780 cast<Constant>(Result));
4781 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004782 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004783 GEP->getName()+".offs"), I);
4784 }
4785 return Result;
4786}
4787
Chris Lattnereba75862008-04-22 02:53:33 +00004788
4789/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4790/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4791/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4792/// complex, and scales are involved. The above expression would also be legal
4793/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4794/// later form is less amenable to optimization though, and we are allowed to
4795/// generate the first by knowing that pointer arithmetic doesn't overflow.
4796///
4797/// If we can't emit an optimized form for this expression, this returns null.
4798///
4799static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4800 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00004801 TargetData &TD = IC.getTargetData();
4802 gep_type_iterator GTI = gep_type_begin(GEP);
4803
4804 // Check to see if this gep only has a single variable index. If so, and if
4805 // any constant indices are a multiple of its scale, then we can compute this
4806 // in terms of the scale of the variable index. For example, if the GEP
4807 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4808 // because the expression will cross zero at the same point.
4809 unsigned i, e = GEP->getNumOperands();
4810 int64_t Offset = 0;
4811 for (i = 1; i != e; ++i, ++GTI) {
4812 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4813 // Compute the aggregate offset of constant indices.
4814 if (CI->isZero()) continue;
4815
4816 // Handle a struct index, which adds its field offset to the pointer.
4817 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4818 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4819 } else {
4820 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4821 Offset += Size*CI->getSExtValue();
4822 }
4823 } else {
4824 // Found our variable index.
4825 break;
4826 }
4827 }
4828
4829 // If there are no variable indices, we must have a constant offset, just
4830 // evaluate it the general way.
4831 if (i == e) return 0;
4832
4833 Value *VariableIdx = GEP->getOperand(i);
4834 // Determine the scale factor of the variable element. For example, this is
4835 // 4 if the variable index is into an array of i32.
4836 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4837
4838 // Verify that there are no other variable indices. If so, emit the hard way.
4839 for (++i, ++GTI; i != e; ++i, ++GTI) {
4840 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4841 if (!CI) return 0;
4842
4843 // Compute the aggregate offset of constant indices.
4844 if (CI->isZero()) continue;
4845
4846 // Handle a struct index, which adds its field offset to the pointer.
4847 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4848 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4849 } else {
4850 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4851 Offset += Size*CI->getSExtValue();
4852 }
4853 }
4854
4855 // Okay, we know we have a single variable index, which must be a
4856 // pointer/array/vector index. If there is no offset, life is simple, return
4857 // the index.
4858 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4859 if (Offset == 0) {
4860 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4861 // we don't need to bother extending: the extension won't affect where the
4862 // computation crosses zero.
4863 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4864 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4865 VariableIdx->getNameStart(), &I);
4866 return VariableIdx;
4867 }
4868
4869 // Otherwise, there is an index. The computation we will do will be modulo
4870 // the pointer size, so get it.
4871 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4872
4873 Offset &= PtrSizeMask;
4874 VariableScale &= PtrSizeMask;
4875
4876 // To do this transformation, any constant index must be a multiple of the
4877 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4878 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4879 // multiple of the variable scale.
4880 int64_t NewOffs = Offset / (int64_t)VariableScale;
4881 if (Offset != NewOffs*(int64_t)VariableScale)
4882 return 0;
4883
4884 // Okay, we can do this evaluation. Start by converting the index to intptr.
4885 const Type *IntPtrTy = TD.getIntPtrType();
4886 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00004887 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00004888 true /*SExt*/,
4889 VariableIdx->getNameStart(), &I);
4890 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00004891 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00004892}
4893
4894
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004895/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4896/// else. At this point we know that the GEP is on the LHS of the comparison.
4897Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4898 ICmpInst::Predicate Cond,
4899 Instruction &I) {
4900 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4901
Chris Lattnereba75862008-04-22 02:53:33 +00004902 // Look through bitcasts.
4903 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4904 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004905
4906 Value *PtrBase = GEPLHS->getOperand(0);
4907 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004908 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00004909 // This transformation (ignoring the base and scales) is valid because we
4910 // know pointers can't overflow. See if we can output an optimized form.
4911 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4912
4913 // If not, synthesize the offset the hard way.
4914 if (Offset == 0)
4915 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00004916 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4917 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004918 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4919 // If the base pointers are different, but the indices are the same, just
4920 // compare the base pointer.
4921 if (PtrBase != GEPRHS->getOperand(0)) {
4922 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4923 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4924 GEPRHS->getOperand(0)->getType();
4925 if (IndicesTheSame)
4926 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4927 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4928 IndicesTheSame = false;
4929 break;
4930 }
4931
4932 // If all indices are the same, just compare the base pointers.
4933 if (IndicesTheSame)
4934 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4935 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4936
4937 // Otherwise, the base pointers are different and the indices are
4938 // different, bail out.
4939 return 0;
4940 }
4941
4942 // If one of the GEPs has all zero indices, recurse.
4943 bool AllZeros = true;
4944 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4945 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4946 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4947 AllZeros = false;
4948 break;
4949 }
4950 if (AllZeros)
4951 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4952 ICmpInst::getSwappedPredicate(Cond), I);
4953
4954 // If the other GEP has all zero indices, recurse.
4955 AllZeros = true;
4956 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4957 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4958 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4959 AllZeros = false;
4960 break;
4961 }
4962 if (AllZeros)
4963 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4964
4965 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4966 // If the GEPs only differ by one index, compare it.
4967 unsigned NumDifferences = 0; // Keep track of # differences.
4968 unsigned DiffOperand = 0; // The operand that differs.
4969 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4970 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4971 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4972 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4973 // Irreconcilable differences.
4974 NumDifferences = 2;
4975 break;
4976 } else {
4977 if (NumDifferences++) break;
4978 DiffOperand = i;
4979 }
4980 }
4981
4982 if (NumDifferences == 0) // SAME GEP?
4983 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004984 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00004985 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00004986
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004987 else if (NumDifferences == 1) {
4988 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4989 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4990 // Make sure we do a signed comparison here.
4991 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4992 }
4993 }
4994
4995 // Only lower this if the icmp is the only user of the GEP or if we expect
4996 // the result to fold to a constant!
4997 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4998 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4999 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5000 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5001 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5002 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5003 }
5004 }
5005 return 0;
5006}
5007
Chris Lattnere6b62d92008-05-19 20:18:56 +00005008/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5009///
5010Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5011 Instruction *LHSI,
5012 Constant *RHSC) {
5013 if (!isa<ConstantFP>(RHSC)) return 0;
5014 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5015
5016 // Get the width of the mantissa. We don't want to hack on conversions that
5017 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005018 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005019 if (MantissaWidth == -1) return 0; // Unknown.
5020
5021 // Check to see that the input is converted from an integer type that is small
5022 // enough that preserves all bits. TODO: check here for "known" sign bits.
5023 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5024 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5025
5026 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5027 if (isa<UIToFPInst>(LHSI))
5028 ++InputSize;
5029
5030 // If the conversion would lose info, don't hack on this.
5031 if ((int)InputSize > MantissaWidth)
5032 return 0;
5033
5034 // Otherwise, we can potentially simplify the comparison. We know that it
5035 // will always come through as an integer value and we know the constant is
5036 // not a NAN (it would have been previously simplified).
5037 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5038
5039 ICmpInst::Predicate Pred;
5040 switch (I.getPredicate()) {
5041 default: assert(0 && "Unexpected predicate!");
5042 case FCmpInst::FCMP_UEQ:
5043 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5044 case FCmpInst::FCMP_UGT:
5045 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5046 case FCmpInst::FCMP_UGE:
5047 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5048 case FCmpInst::FCMP_ULT:
5049 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5050 case FCmpInst::FCMP_ULE:
5051 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5052 case FCmpInst::FCMP_UNE:
5053 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5054 case FCmpInst::FCMP_ORD:
5055 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5056 case FCmpInst::FCMP_UNO:
5057 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5058 }
5059
5060 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5061
5062 // Now we know that the APFloat is a normal number, zero or inf.
5063
Chris Lattnerf13ff492008-05-20 03:50:52 +00005064 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005065 // comparing an i8 to 300.0.
5066 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5067
5068 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5069 // and large values.
5070 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5071 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5072 APFloat::rmNearestTiesToEven);
5073 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner82a80002008-05-24 04:06:28 +00005074 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5075 Pred == ICmpInst::ICMP_SLE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005076 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5077 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5078 }
5079
5080 // See if the RHS value is < SignedMin.
5081 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5082 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5083 APFloat::rmNearestTiesToEven);
5084 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner82a80002008-05-24 04:06:28 +00005085 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5086 Pred == ICmpInst::ICMP_SGE)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005087 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5088 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5089 }
5090
5091 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5092 // it may still be fractional. See if it is fractional by casting the FP
5093 // value to the integer value and back, checking for equality. Don't do this
5094 // for zero, because -0.0 is not fractional.
5095 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5096 if (!RHS.isZero() &&
5097 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5098 // If we had a comparison against a fractional value, we have to adjust
5099 // the compare predicate and sometimes the value. RHSC is rounded towards
5100 // zero at this point.
5101 switch (Pred) {
5102 default: assert(0 && "Unexpected integer comparison!");
5103 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5104 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5105 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5106 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5107 case ICmpInst::ICMP_SLE:
5108 // (float)int <= 4.4 --> int <= 4
5109 // (float)int <= -4.4 --> int < -4
5110 if (RHS.isNegative())
5111 Pred = ICmpInst::ICMP_SLT;
5112 break;
5113 case ICmpInst::ICMP_SLT:
5114 // (float)int < -4.4 --> int < -4
5115 // (float)int < 4.4 --> int <= 4
5116 if (!RHS.isNegative())
5117 Pred = ICmpInst::ICMP_SLE;
5118 break;
5119 case ICmpInst::ICMP_SGT:
5120 // (float)int > 4.4 --> int > 4
5121 // (float)int > -4.4 --> int >= -4
5122 if (RHS.isNegative())
5123 Pred = ICmpInst::ICMP_SGE;
5124 break;
5125 case ICmpInst::ICMP_SGE:
5126 // (float)int >= -4.4 --> int >= -4
5127 // (float)int >= 4.4 --> int > 4
5128 if (!RHS.isNegative())
5129 Pred = ICmpInst::ICMP_SGT;
5130 break;
5131 }
5132 }
5133
5134 // Lower this FP comparison into an appropriate integer version of the
5135 // comparison.
5136 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5137}
5138
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5140 bool Changed = SimplifyCompare(I);
5141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5142
5143 // Fold trivial predicates.
5144 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5145 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5146 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5147 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5148
5149 // Simplify 'fcmp pred X, X'
5150 if (Op0 == Op1) {
5151 switch (I.getPredicate()) {
5152 default: assert(0 && "Unknown predicate!");
5153 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5154 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5155 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5156 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5157 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5158 case FCmpInst::FCMP_OLT: // True if ordered and less than
5159 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5160 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5161
5162 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5163 case FCmpInst::FCMP_ULT: // True if unordered or less than
5164 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5165 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5166 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5167 I.setPredicate(FCmpInst::FCMP_UNO);
5168 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5169 return &I;
5170
5171 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5172 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5173 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5174 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5175 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5176 I.setPredicate(FCmpInst::FCMP_ORD);
5177 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5178 return &I;
5179 }
5180 }
5181
5182 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5183 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5184
5185 // Handle fcmp with constant RHS
5186 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005187 // If the constant is a nan, see if we can fold the comparison based on it.
5188 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5189 if (CFP->getValueAPF().isNaN()) {
5190 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5191 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattnerf13ff492008-05-20 03:50:52 +00005192 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5193 "Comparison must be either ordered or unordered!");
5194 // True if unordered.
5195 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnere6b62d92008-05-19 20:18:56 +00005196 }
5197 }
5198
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005199 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5200 switch (LHSI->getOpcode()) {
5201 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005202 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5203 // block. If in the same block, we're encouraging jump threading. If
5204 // not, we are just pessimizing the code by making an i1 phi.
5205 if (LHSI->getParent() == I.getParent())
5206 if (Instruction *NV = FoldOpIntoPhi(I))
5207 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005208 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005209 case Instruction::SIToFP:
5210 case Instruction::UIToFP:
5211 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5212 return NV;
5213 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005214 case Instruction::Select:
5215 // If either operand of the select is a constant, we can fold the
5216 // comparison into the select arms, which will cause one to be
5217 // constant folded and the select turned into a bitwise or.
5218 Value *Op1 = 0, *Op2 = 0;
5219 if (LHSI->hasOneUse()) {
5220 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5221 // Fold the known value into the constant operand.
5222 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5223 // Insert a new FCmp of the other select operand.
5224 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5225 LHSI->getOperand(2), RHSC,
5226 I.getName()), I);
5227 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5228 // Fold the known value into the constant operand.
5229 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5230 // Insert a new FCmp of the other select operand.
5231 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5232 LHSI->getOperand(1), RHSC,
5233 I.getName()), I);
5234 }
5235 }
5236
5237 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005238 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005239 break;
5240 }
5241 }
5242
5243 return Changed ? &I : 0;
5244}
5245
5246Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5247 bool Changed = SimplifyCompare(I);
5248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5249 const Type *Ty = Op0->getType();
5250
5251 // icmp X, X
5252 if (Op0 == Op1)
5253 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005254 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005255
5256 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5257 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005258
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005259 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5260 // addresses never equal each other! We already know that Op0 != Op1.
5261 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5262 isa<ConstantPointerNull>(Op0)) &&
5263 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5264 isa<ConstantPointerNull>(Op1)))
5265 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005266 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005267
5268 // icmp's with boolean values can always be turned into bitwise operations
5269 if (Ty == Type::Int1Ty) {
5270 switch (I.getPredicate()) {
5271 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005272 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005273 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005274 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005275 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005276 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005277 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005278 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005279
5280 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005281 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005282 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005283 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00005284 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005285 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005286 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005287 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005288 case ICmpInst::ICMP_SGT:
5289 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005290 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005291 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5292 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5293 InsertNewInstBefore(Not, I);
5294 return BinaryOperator::CreateAnd(Not, Op0);
5295 }
5296 case ICmpInst::ICMP_UGE:
5297 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5298 // FALL THROUGH
5299 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005300 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005301 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005302 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005303 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005304 case ICmpInst::ICMP_SGE:
5305 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5306 // FALL THROUGH
5307 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5308 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5309 InsertNewInstBefore(Not, I);
5310 return BinaryOperator::CreateOr(Not, Op0);
5311 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005312 }
5313 }
5314
5315 // See if we are doing a comparison between a constant and an instruction that
5316 // can be folded into the comparison.
5317 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3d816532008-07-11 04:09:09 +00005318 Value *A, *B;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005319
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005320 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5321 if (I.isEquality() && CI->isNullValue() &&
5322 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5323 // (icmp cond A B) if cond is equality
5324 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005325 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005326
Chris Lattner62d0f232008-07-11 05:08:55 +00005327 // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5328 // icmp lt or icmp gt instruction. This allows us to rely on them being
5329 // folded in the code below.
5330 switch (I.getPredicate()) {
5331 default: break;
5332 case ICmpInst::ICMP_ULE:
5333 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5334 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5335 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5336 case ICmpInst::ICMP_SLE:
5337 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5338 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5339 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5340 case ICmpInst::ICMP_UGE:
5341 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5342 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5343 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5344 case ICmpInst::ICMP_SGE:
5345 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5346 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5347 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5348 }
5349
Chris Lattnera1308652008-07-11 05:40:05 +00005350 // See if we can fold the comparison based on range information we can get
5351 // by checking whether bits are known to be zero or one in the input.
5352 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5353 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5354
5355 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005356 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005357 bool UnusedBit;
5358 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5359
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005360 if (SimplifyDemandedBits(Op0,
5361 isSignBit ? APInt::getSignBit(BitWidth)
5362 : APInt::getAllOnesValue(BitWidth),
5363 KnownZero, KnownOne, 0))
5364 return &I;
5365
5366 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00005367 // in. Compute the Min, Max and RHS values based on the known bits. For the
5368 // EQ and NE we use unsigned values.
5369 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner62d0f232008-07-11 05:08:55 +00005370 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5371 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5372 else
5373 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5374
Chris Lattnera1308652008-07-11 05:40:05 +00005375 // If Min and Max are known to be the same, then SimplifyDemandedBits
5376 // figured out that the LHS is a constant. Just constant fold this now so
5377 // that code below can assume that Min != Max.
5378 if (Min == Max)
5379 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5380 ConstantInt::get(Min),
5381 CI));
5382
5383 // Based on the range information we know about the LHS, see if we can
5384 // simplify this comparison. For example, (x&4) < 8 is always true.
5385 const APInt &RHSVal = CI->getValue();
Chris Lattner62d0f232008-07-11 05:08:55 +00005386 switch (I.getPredicate()) { // LE/GE have been folded already.
5387 default: assert(0 && "Unknown icmp opcode!");
5388 case ICmpInst::ICMP_EQ:
5389 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5390 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5391 break;
5392 case ICmpInst::ICMP_NE:
5393 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5394 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5395 break;
5396 case ICmpInst::ICMP_ULT:
Chris Lattnera1308652008-07-11 05:40:05 +00005397 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005398 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005399 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005400 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005401 if (RHSVal == Max) // A <u MAX -> A != MAX
5402 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5403 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5404 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5405
5406 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5407 if (CI->isMinValue(true))
5408 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5409 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005410 break;
5411 case ICmpInst::ICMP_UGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005412 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005413 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005414 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005415 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005416
5417 if (RHSVal == Min) // A >u MIN -> A != MIN
5418 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5419 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5420 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5421
5422 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5423 if (CI->isMaxValue(true))
5424 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5425 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005426 break;
5427 case ICmpInst::ICMP_SLT:
Chris Lattnera1308652008-07-11 05:40:05 +00005428 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005429 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner611b43e2008-07-11 06:40:29 +00005430 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005431 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005432 if (RHSVal == Max) // A <s MAX -> A != MAX
5433 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattner3496f3e2008-07-11 06:36:01 +00005434 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattner55ab3152008-07-11 06:38:16 +00005435 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005436 break;
5437 case ICmpInst::ICMP_SGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005438 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005439 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005440 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005441 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005442
5443 if (RHSVal == Min) // A >s MIN -> A != MIN
5444 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5445 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5446 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005447 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005448 }
5449
5450 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5451 // instruction, see if that instruction also has constants so that the
5452 // instruction can be folded into the icmp
5453 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5454 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5455 return Res;
5456 }
5457
5458 // Handle icmp with constant (but not simple integer constant) RHS
5459 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5460 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5461 switch (LHSI->getOpcode()) {
5462 case Instruction::GetElementPtr:
5463 if (RHSC->isNullValue()) {
5464 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5465 bool isAllZeros = true;
5466 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5467 if (!isa<Constant>(LHSI->getOperand(i)) ||
5468 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5469 isAllZeros = false;
5470 break;
5471 }
5472 if (isAllZeros)
5473 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5474 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5475 }
5476 break;
5477
5478 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005479 // Only fold icmp into the PHI if the phi and fcmp are in the same
5480 // block. If in the same block, we're encouraging jump threading. If
5481 // not, we are just pessimizing the code by making an i1 phi.
5482 if (LHSI->getParent() == I.getParent())
5483 if (Instruction *NV = FoldOpIntoPhi(I))
5484 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005485 break;
5486 case Instruction::Select: {
5487 // If either operand of the select is a constant, we can fold the
5488 // comparison into the select arms, which will cause one to be
5489 // constant folded and the select turned into a bitwise or.
5490 Value *Op1 = 0, *Op2 = 0;
5491 if (LHSI->hasOneUse()) {
5492 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5493 // Fold the known value into the constant operand.
5494 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5495 // Insert a new ICmp of the other select operand.
5496 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5497 LHSI->getOperand(2), RHSC,
5498 I.getName()), I);
5499 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5500 // Fold the known value into the constant operand.
5501 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5502 // Insert a new ICmp of the other select operand.
5503 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5504 LHSI->getOperand(1), RHSC,
5505 I.getName()), I);
5506 }
5507 }
5508
5509 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005510 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005511 break;
5512 }
5513 case Instruction::Malloc:
5514 // If we have (malloc != null), and if the malloc has a single use, we
5515 // can assume it is successful and remove the malloc.
5516 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5517 AddToWorkList(LHSI);
5518 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005519 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005520 }
5521 break;
5522 }
5523 }
5524
5525 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5526 if (User *GEP = dyn_castGetElementPtr(Op0))
5527 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5528 return NI;
5529 if (User *GEP = dyn_castGetElementPtr(Op1))
5530 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5531 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5532 return NI;
5533
5534 // Test to see if the operands of the icmp are casted versions of other
5535 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5536 // now.
5537 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5538 if (isa<PointerType>(Op0->getType()) &&
5539 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5540 // We keep moving the cast from the left operand over to the right
5541 // operand, where it can often be eliminated completely.
5542 Op0 = CI->getOperand(0);
5543
5544 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5545 // so eliminate it as well.
5546 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5547 Op1 = CI2->getOperand(0);
5548
5549 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005550 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005551 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5552 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5553 } else {
5554 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005555 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005556 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005557 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005558 return new ICmpInst(I.getPredicate(), Op0, Op1);
5559 }
5560 }
5561
5562 if (isa<CastInst>(Op0)) {
5563 // Handle the special case of: icmp (cast bool to X), <cst>
5564 // This comes up when you have code like
5565 // int X = A < B;
5566 // if (X) ...
5567 // For generality, we handle any zero-extension of any operand comparison
5568 // with a constant or another cast from the same type.
5569 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5570 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5571 return R;
5572 }
5573
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005574 // See if it's the same type of instruction on the left and right.
5575 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5576 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005577 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5578 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5579 I.isEquality()) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00005580 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005581 default: break;
5582 case Instruction::Add:
5583 case Instruction::Sub:
5584 case Instruction::Xor:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005585 // a+x icmp eq/ne b+x --> a icmp b
5586 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5587 Op1I->getOperand(0));
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005588 break;
5589 case Instruction::Mul:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005590 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5591 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5592 // Mask = -1 >> count-trailing-zeros(Cst).
5593 if (!CI->isZero() && !CI->isOne()) {
5594 const APInt &AP = CI->getValue();
5595 ConstantInt *Mask = ConstantInt::get(
5596 APInt::getLowBitsSet(AP.getBitWidth(),
5597 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005598 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00005599 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5600 Mask);
5601 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5602 Mask);
5603 InsertNewInstBefore(And1, I);
5604 InsertNewInstBefore(And2, I);
5605 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00005606 }
5607 }
5608 break;
5609 }
5610 }
5611 }
5612 }
5613
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005614 // ~x < ~y --> y < x
5615 { Value *A, *B;
5616 if (match(Op0, m_Not(m_Value(A))) &&
5617 match(Op1, m_Not(m_Value(B))))
5618 return new ICmpInst(I.getPredicate(), B, A);
5619 }
5620
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005621 if (I.isEquality()) {
5622 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005623
5624 // -x == -y --> x == y
5625 if (match(Op0, m_Neg(m_Value(A))) &&
5626 match(Op1, m_Neg(m_Value(B))))
5627 return new ICmpInst(I.getPredicate(), A, B);
5628
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005629 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5630 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5631 Value *OtherVal = A == Op1 ? B : A;
5632 return new ICmpInst(I.getPredicate(), OtherVal,
5633 Constant::getNullValue(A->getType()));
5634 }
5635
5636 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5637 // A^c1 == C^c2 --> A == C^(c1^c2)
5638 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5639 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5640 if (Op1->hasOneUse()) {
5641 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005642 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005643 return new ICmpInst(I.getPredicate(), A,
5644 InsertNewInstBefore(Xor, I));
5645 }
5646
5647 // A^B == A^D -> B == D
5648 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5649 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5650 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5651 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5652 }
5653 }
5654
5655 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5656 (A == Op0 || B == Op0)) {
5657 // A == (A^B) -> B == 0
5658 Value *OtherVal = A == Op0 ? B : A;
5659 return new ICmpInst(I.getPredicate(), OtherVal,
5660 Constant::getNullValue(A->getType()));
5661 }
5662 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5663 // (A-B) == A -> B == 0
5664 return new ICmpInst(I.getPredicate(), B,
5665 Constant::getNullValue(B->getType()));
5666 }
5667 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5668 // A == (A-B) -> B == 0
5669 return new ICmpInst(I.getPredicate(), B,
5670 Constant::getNullValue(B->getType()));
5671 }
5672
5673 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5674 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5675 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5676 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5677 Value *X = 0, *Y = 0, *Z = 0;
5678
5679 if (A == C) {
5680 X = B; Y = D; Z = A;
5681 } else if (A == D) {
5682 X = B; Y = C; Z = A;
5683 } else if (B == C) {
5684 X = A; Y = D; Z = B;
5685 } else if (B == D) {
5686 X = A; Y = C; Z = B;
5687 }
5688
5689 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005690 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5691 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005692 I.setOperand(0, Op1);
5693 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5694 return &I;
5695 }
5696 }
5697 }
5698 return Changed ? &I : 0;
5699}
5700
5701
5702/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5703/// and CmpRHS are both known to be integer constants.
5704Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5705 ConstantInt *DivRHS) {
5706 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5707 const APInt &CmpRHSV = CmpRHS->getValue();
5708
5709 // FIXME: If the operand types don't match the type of the divide
5710 // then don't attempt this transform. The code below doesn't have the
5711 // logic to deal with a signed divide and an unsigned compare (and
5712 // vice versa). This is because (x /s C1) <s C2 produces different
5713 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5714 // (x /u C1) <u C2. Simply casting the operands and result won't
5715 // work. :( The if statement below tests that condition and bails
5716 // if it finds it.
5717 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5718 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5719 return 0;
5720 if (DivRHS->isZero())
5721 return 0; // The ProdOV computation fails on divide by zero.
5722
5723 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5724 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5725 // C2 (CI). By solving for X we can turn this into a range check
5726 // instead of computing a divide.
5727 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5728
5729 // Determine if the product overflows by seeing if the product is
5730 // not equal to the divide. Make sure we do the same kind of divide
5731 // as in the LHS instruction that we're folding.
5732 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5733 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5734
5735 // Get the ICmp opcode
5736 ICmpInst::Predicate Pred = ICI.getPredicate();
5737
5738 // Figure out the interval that is being checked. For example, a comparison
5739 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5740 // Compute this interval based on the constants involved and the signedness of
5741 // the compare/divide. This computes a half-open interval, keeping track of
5742 // whether either value in the interval overflows. After analysis each
5743 // overflow variable is set to 0 if it's corresponding bound variable is valid
5744 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5745 int LoOverflow = 0, HiOverflow = 0;
5746 ConstantInt *LoBound = 0, *HiBound = 0;
5747
5748
5749 if (!DivIsSigned) { // udiv
5750 // e.g. X/5 op 3 --> [15, 20)
5751 LoBound = Prod;
5752 HiOverflow = LoOverflow = ProdOV;
5753 if (!HiOverflow)
5754 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005755 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005756 if (CmpRHSV == 0) { // (X / pos) op 0
5757 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5758 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5759 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005760 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005761 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5762 HiOverflow = LoOverflow = ProdOV;
5763 if (!HiOverflow)
5764 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5765 } else { // (X / pos) op neg
5766 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5767 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5768 LoOverflow = AddWithOverflow(LoBound, Prod,
5769 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5770 HiBound = AddOne(Prod);
5771 HiOverflow = ProdOV ? -1 : 0;
5772 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005773 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005774 if (CmpRHSV == 0) { // (X / neg) op 0
5775 // e.g. X/-5 op 0 --> [-4, 5)
5776 LoBound = AddOne(DivRHS);
5777 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5778 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5779 HiOverflow = 1; // [INTMIN+1, overflow)
5780 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5781 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005782 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005783 // e.g. X/-5 op 3 --> [-19, -14)
5784 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5785 if (!LoOverflow)
5786 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5787 HiBound = AddOne(Prod);
5788 } else { // (X / neg) op neg
5789 // e.g. X/-5 op -3 --> [15, 20)
5790 LoBound = Prod;
5791 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Dan Gohman45408ea2008-09-11 00:25:00 +00005792 if (!HiOverflow)
5793 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005794 }
5795
5796 // Dividing by a negative swaps the condition. LT <-> GT
5797 Pred = ICmpInst::getSwappedPredicate(Pred);
5798 }
5799
5800 Value *X = DivI->getOperand(0);
5801 switch (Pred) {
5802 default: assert(0 && "Unhandled icmp opcode!");
5803 case ICmpInst::ICMP_EQ:
5804 if (LoOverflow && HiOverflow)
5805 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5806 else if (HiOverflow)
5807 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5808 ICmpInst::ICMP_UGE, X, LoBound);
5809 else if (LoOverflow)
5810 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5811 ICmpInst::ICMP_ULT, X, HiBound);
5812 else
5813 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5814 case ICmpInst::ICMP_NE:
5815 if (LoOverflow && HiOverflow)
5816 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5817 else if (HiOverflow)
5818 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5819 ICmpInst::ICMP_ULT, X, LoBound);
5820 else if (LoOverflow)
5821 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5822 ICmpInst::ICMP_UGE, X, HiBound);
5823 else
5824 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5825 case ICmpInst::ICMP_ULT:
5826 case ICmpInst::ICMP_SLT:
5827 if (LoOverflow == +1) // Low bound is greater than input range.
5828 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5829 if (LoOverflow == -1) // Low bound is less than input range.
5830 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5831 return new ICmpInst(Pred, X, LoBound);
5832 case ICmpInst::ICMP_UGT:
5833 case ICmpInst::ICMP_SGT:
5834 if (HiOverflow == +1) // High bound greater than input range.
5835 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5836 else if (HiOverflow == -1) // High bound less than input range.
5837 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5838 if (Pred == ICmpInst::ICMP_UGT)
5839 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5840 else
5841 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5842 }
5843}
5844
5845
5846/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5847///
5848Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5849 Instruction *LHSI,
5850 ConstantInt *RHS) {
5851 const APInt &RHSV = RHS->getValue();
5852
5853 switch (LHSI->getOpcode()) {
5854 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5855 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5856 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5857 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005858 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5859 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005860 Value *CompareVal = LHSI->getOperand(0);
5861
5862 // If the sign bit of the XorCST is not set, there is no change to
5863 // the operation, just stop using the Xor.
5864 if (!XorCST->getValue().isNegative()) {
5865 ICI.setOperand(0, CompareVal);
5866 AddToWorkList(LHSI);
5867 return &ICI;
5868 }
5869
5870 // Was the old condition true if the operand is positive?
5871 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5872
5873 // If so, the new one isn't.
5874 isTrueIfPositive ^= true;
5875
5876 if (isTrueIfPositive)
5877 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5878 else
5879 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5880 }
5881 }
5882 break;
5883 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5884 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5885 LHSI->getOperand(0)->hasOneUse()) {
5886 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5887
5888 // If the LHS is an AND of a truncating cast, we can widen the
5889 // and/compare to be the input width without changing the value
5890 // produced, eliminating a cast.
5891 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5892 // We can do this transformation if either the AND constant does not
5893 // have its sign bit set or if it is an equality comparison.
5894 // Extending a relational comparison when we're checking the sign
5895 // bit would not work.
5896 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005897 (ICI.isEquality() ||
5898 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005899 uint32_t BitWidth =
5900 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5901 APInt NewCST = AndCST->getValue();
5902 NewCST.zext(BitWidth);
5903 APInt NewCI = RHSV;
5904 NewCI.zext(BitWidth);
5905 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005906 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005907 ConstantInt::get(NewCST),LHSI->getName());
5908 InsertNewInstBefore(NewAnd, ICI);
5909 return new ICmpInst(ICI.getPredicate(), NewAnd,
5910 ConstantInt::get(NewCI));
5911 }
5912 }
5913
5914 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5915 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5916 // happens a LOT in code produced by the C front-end, for bitfield
5917 // access.
5918 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5919 if (Shift && !Shift->isShift())
5920 Shift = 0;
5921
5922 ConstantInt *ShAmt;
5923 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5924 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5925 const Type *AndTy = AndCST->getType(); // Type of the and.
5926
5927 // We can fold this as long as we can't shift unknown bits
5928 // into the mask. This can only happen with signed shift
5929 // rights, as they sign-extend.
5930 if (ShAmt) {
5931 bool CanFold = Shift->isLogicalShift();
5932 if (!CanFold) {
5933 // To test for the bad case of the signed shr, see if any
5934 // of the bits shifted in could be tested after the mask.
5935 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5936 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5937
5938 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5939 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5940 AndCST->getValue()) == 0)
5941 CanFold = true;
5942 }
5943
5944 if (CanFold) {
5945 Constant *NewCst;
5946 if (Shift->getOpcode() == Instruction::Shl)
5947 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5948 else
5949 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5950
5951 // Check to see if we are shifting out any of the bits being
5952 // compared.
5953 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5954 // If we shifted bits out, the fold is not going to work out.
5955 // As a special case, check to see if this means that the
5956 // result is always true or false now.
5957 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5958 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5959 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5960 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5961 } else {
5962 ICI.setOperand(1, NewCst);
5963 Constant *NewAndCST;
5964 if (Shift->getOpcode() == Instruction::Shl)
5965 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5966 else
5967 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5968 LHSI->setOperand(1, NewAndCST);
5969 LHSI->setOperand(0, Shift->getOperand(0));
5970 AddToWorkList(Shift); // Shift is dead.
5971 AddUsesToWorkList(ICI);
5972 return &ICI;
5973 }
5974 }
5975 }
5976
5977 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5978 // preferable because it allows the C<<Y expression to be hoisted out
5979 // of a loop if Y is invariant and X is not.
5980 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5981 ICI.isEquality() && !Shift->isArithmeticShift() &&
5982 isa<Instruction>(Shift->getOperand(0))) {
5983 // Compute C << Y.
5984 Value *NS;
5985 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005986 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005987 Shift->getOperand(1), "tmp");
5988 } else {
5989 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00005990 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005991 Shift->getOperand(1), "tmp");
5992 }
5993 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5994
5995 // Compute X & (C << Y).
5996 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005997 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005998 InsertNewInstBefore(NewAnd, ICI);
5999
6000 ICI.setOperand(0, NewAnd);
6001 return &ICI;
6002 }
6003 }
6004 break;
6005
6006 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6007 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6008 if (!ShAmt) break;
6009
6010 uint32_t TypeBits = RHSV.getBitWidth();
6011
6012 // Check that the shift amount is in range. If not, don't perform
6013 // undefined shifts. When the shift is visited it will be
6014 // simplified.
6015 if (ShAmt->uge(TypeBits))
6016 break;
6017
6018 if (ICI.isEquality()) {
6019 // If we are comparing against bits always shifted out, the
6020 // comparison cannot succeed.
6021 Constant *Comp =
6022 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6023 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6024 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6025 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6026 return ReplaceInstUsesWith(ICI, Cst);
6027 }
6028
6029 if (LHSI->hasOneUse()) {
6030 // Otherwise strength reduce the shift into an and.
6031 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6032 Constant *Mask =
6033 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6034
6035 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006036 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006037 Mask, LHSI->getName()+".mask");
6038 Value *And = InsertNewInstBefore(AndI, ICI);
6039 return new ICmpInst(ICI.getPredicate(), And,
6040 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6041 }
6042 }
6043
6044 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6045 bool TrueIfSigned = false;
6046 if (LHSI->hasOneUse() &&
6047 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6048 // (X << 31) <s 0 --> (X&1) != 0
6049 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6050 (TypeBits-ShAmt->getZExtValue()-1));
6051 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006052 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006053 Mask, LHSI->getName()+".mask");
6054 Value *And = InsertNewInstBefore(AndI, ICI);
6055
6056 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6057 And, Constant::getNullValue(And->getType()));
6058 }
6059 break;
6060 }
6061
6062 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6063 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006064 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006065 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006066 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006067
Chris Lattner5ee84f82008-03-21 05:19:58 +00006068 // Check that the shift amount is in range. If not, don't perform
6069 // undefined shifts. When the shift is visited it will be
6070 // simplified.
6071 uint32_t TypeBits = RHSV.getBitWidth();
6072 if (ShAmt->uge(TypeBits))
6073 break;
6074
6075 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006076
Chris Lattner5ee84f82008-03-21 05:19:58 +00006077 // If we are comparing against bits always shifted out, the
6078 // comparison cannot succeed.
6079 APInt Comp = RHSV << ShAmtVal;
6080 if (LHSI->getOpcode() == Instruction::LShr)
6081 Comp = Comp.lshr(ShAmtVal);
6082 else
6083 Comp = Comp.ashr(ShAmtVal);
6084
6085 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6086 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6087 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6088 return ReplaceInstUsesWith(ICI, Cst);
6089 }
6090
6091 // Otherwise, check to see if the bits shifted out are known to be zero.
6092 // If so, we can compare against the unshifted value:
6093 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006094 if (LHSI->hasOneUse() &&
6095 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006096 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6097 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6098 ConstantExpr::getShl(RHS, ShAmt));
6099 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006100
Evan Chengfb9292a2008-04-23 00:38:06 +00006101 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006102 // Otherwise strength reduce the shift into an and.
6103 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6104 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006105
Chris Lattner5ee84f82008-03-21 05:19:58 +00006106 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006107 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006108 Mask, LHSI->getName()+".mask");
6109 Value *And = InsertNewInstBefore(AndI, ICI);
6110 return new ICmpInst(ICI.getPredicate(), And,
6111 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006112 }
6113 break;
6114 }
6115
6116 case Instruction::SDiv:
6117 case Instruction::UDiv:
6118 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6119 // Fold this div into the comparison, producing a range check.
6120 // Determine, based on the divide type, what the range is being
6121 // checked. If there is an overflow on the low or high side, remember
6122 // it, otherwise compute the range [low, hi) bounding the new value.
6123 // See: InsertRangeTest above for the kinds of replacements possible.
6124 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6125 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6126 DivRHS))
6127 return R;
6128 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006129
6130 case Instruction::Add:
6131 // Fold: icmp pred (add, X, C1), C2
6132
6133 if (!ICI.isEquality()) {
6134 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6135 if (!LHSC) break;
6136 const APInt &LHSV = LHSC->getValue();
6137
6138 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6139 .subtract(LHSV);
6140
6141 if (ICI.isSignedPredicate()) {
6142 if (CR.getLower().isSignBit()) {
6143 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6144 ConstantInt::get(CR.getUpper()));
6145 } else if (CR.getUpper().isSignBit()) {
6146 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6147 ConstantInt::get(CR.getLower()));
6148 }
6149 } else {
6150 if (CR.getLower().isMinValue()) {
6151 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6152 ConstantInt::get(CR.getUpper()));
6153 } else if (CR.getUpper().isMinValue()) {
6154 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6155 ConstantInt::get(CR.getLower()));
6156 }
6157 }
6158 }
6159 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006160 }
6161
6162 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6163 if (ICI.isEquality()) {
6164 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6165
6166 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6167 // the second operand is a constant, simplify a bit.
6168 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6169 switch (BO->getOpcode()) {
6170 case Instruction::SRem:
6171 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6172 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6173 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6174 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6175 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006176 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006177 BO->getName());
6178 InsertNewInstBefore(NewRem, ICI);
6179 return new ICmpInst(ICI.getPredicate(), NewRem,
6180 Constant::getNullValue(BO->getType()));
6181 }
6182 }
6183 break;
6184 case Instruction::Add:
6185 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6186 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6187 if (BO->hasOneUse())
6188 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6189 Subtract(RHS, BOp1C));
6190 } else if (RHSV == 0) {
6191 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6192 // efficiently invertible, or if the add has just this one use.
6193 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6194
6195 if (Value *NegVal = dyn_castNegVal(BOp1))
6196 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6197 else if (Value *NegVal = dyn_castNegVal(BOp0))
6198 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6199 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006200 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006201 InsertNewInstBefore(Neg, ICI);
6202 Neg->takeName(BO);
6203 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6204 }
6205 }
6206 break;
6207 case Instruction::Xor:
6208 // For the xor case, we can xor two constants together, eliminating
6209 // the explicit xor.
6210 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6211 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6212 ConstantExpr::getXor(RHS, BOC));
6213
6214 // FALLTHROUGH
6215 case Instruction::Sub:
6216 // Replace (([sub|xor] A, B) != 0) with (A != B)
6217 if (RHSV == 0)
6218 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6219 BO->getOperand(1));
6220 break;
6221
6222 case Instruction::Or:
6223 // If bits are being or'd in that are not present in the constant we
6224 // are comparing against, then the comparison could never succeed!
6225 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6226 Constant *NotCI = ConstantExpr::getNot(RHS);
6227 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6228 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6229 isICMP_NE));
6230 }
6231 break;
6232
6233 case Instruction::And:
6234 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6235 // If bits are being compared against that are and'd out, then the
6236 // comparison can never succeed!
6237 if ((RHSV & ~BOC->getValue()) != 0)
6238 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6239 isICMP_NE));
6240
6241 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6242 if (RHS == BOC && RHSV.isPowerOf2())
6243 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6244 ICmpInst::ICMP_NE, LHSI,
6245 Constant::getNullValue(RHS->getType()));
6246
6247 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00006248 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006249 Value *X = BO->getOperand(0);
6250 Constant *Zero = Constant::getNullValue(X->getType());
6251 ICmpInst::Predicate pred = isICMP_NE ?
6252 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6253 return new ICmpInst(pred, X, Zero);
6254 }
6255
6256 // ((X & ~7) == 0) --> X < 8
6257 if (RHSV == 0 && isHighOnes(BOC)) {
6258 Value *X = BO->getOperand(0);
6259 Constant *NegX = ConstantExpr::getNeg(BOC);
6260 ICmpInst::Predicate pred = isICMP_NE ?
6261 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6262 return new ICmpInst(pred, X, NegX);
6263 }
6264 }
6265 default: break;
6266 }
6267 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6268 // Handle icmp {eq|ne} <intrinsic>, intcst.
6269 if (II->getIntrinsicID() == Intrinsic::bswap) {
6270 AddToWorkList(II);
6271 ICI.setOperand(0, II->getOperand(1));
6272 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6273 return &ICI;
6274 }
6275 }
6276 } else { // Not a ICMP_EQ/ICMP_NE
6277 // If the LHS is a cast from an integral value of the same size,
6278 // then since we know the RHS is a constant, try to simlify.
6279 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6280 Value *CastOp = Cast->getOperand(0);
6281 const Type *SrcTy = CastOp->getType();
6282 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6283 if (SrcTy->isInteger() &&
6284 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6285 // If this is an unsigned comparison, try to make the comparison use
6286 // smaller constant values.
6287 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6288 // X u< 128 => X s> -1
6289 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6290 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6291 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6292 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6293 // X u> 127 => X s< 0
6294 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6295 Constant::getNullValue(SrcTy));
6296 }
6297 }
6298 }
6299 }
6300 return 0;
6301}
6302
6303/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6304/// We only handle extending casts so far.
6305///
6306Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6307 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6308 Value *LHSCIOp = LHSCI->getOperand(0);
6309 const Type *SrcTy = LHSCIOp->getType();
6310 const Type *DestTy = LHSCI->getType();
6311 Value *RHSCIOp;
6312
6313 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6314 // integer type is the same size as the pointer type.
6315 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6316 getTargetData().getPointerSizeInBits() ==
6317 cast<IntegerType>(DestTy)->getBitWidth()) {
6318 Value *RHSOp = 0;
6319 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6320 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6321 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6322 RHSOp = RHSC->getOperand(0);
6323 // If the pointer types don't match, insert a bitcast.
6324 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006325 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006326 }
6327
6328 if (RHSOp)
6329 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6330 }
6331
6332 // The code below only handles extension cast instructions, so far.
6333 // Enforce this.
6334 if (LHSCI->getOpcode() != Instruction::ZExt &&
6335 LHSCI->getOpcode() != Instruction::SExt)
6336 return 0;
6337
6338 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6339 bool isSignedCmp = ICI.isSignedPredicate();
6340
6341 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6342 // Not an extension from the same type?
6343 RHSCIOp = CI->getOperand(0);
6344 if (RHSCIOp->getType() != LHSCIOp->getType())
6345 return 0;
6346
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006347 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006348 // and the other is a zext), then we can't handle this.
6349 if (CI->getOpcode() != LHSCI->getOpcode())
6350 return 0;
6351
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006352 // Deal with equality cases early.
6353 if (ICI.isEquality())
6354 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6355
6356 // A signed comparison of sign extended values simplifies into a
6357 // signed comparison.
6358 if (isSignedCmp && isSignedExt)
6359 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6360
6361 // The other three cases all fold into an unsigned comparison.
6362 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006363 }
6364
6365 // If we aren't dealing with a constant on the RHS, exit early
6366 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6367 if (!CI)
6368 return 0;
6369
6370 // Compute the constant that would happen if we truncated to SrcTy then
6371 // reextended to DestTy.
6372 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6373 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6374
6375 // If the re-extended constant didn't change...
6376 if (Res2 == CI) {
6377 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6378 // For example, we might have:
6379 // %A = sext short %X to uint
6380 // %B = icmp ugt uint %A, 1330
6381 // It is incorrect to transform this into
6382 // %B = icmp ugt short %X, 1330
6383 // because %A may have negative value.
6384 //
Chris Lattner3d816532008-07-11 04:09:09 +00006385 // However, we allow this when the compare is EQ/NE, because they are
6386 // signless.
6387 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006388 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00006389 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006390 }
6391
6392 // The re-extended constant changed so the constant cannot be represented
6393 // in the shorter type. Consequently, we cannot emit a simple comparison.
6394
6395 // First, handle some easy cases. We know the result cannot be equal at this
6396 // point so handle the ICI.isEquality() cases
6397 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6398 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6399 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6400 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6401
6402 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6403 // should have been folded away previously and not enter in here.
6404 Value *Result;
6405 if (isSignedCmp) {
6406 // We're performing a signed comparison.
6407 if (cast<ConstantInt>(CI)->getValue().isNegative())
6408 Result = ConstantInt::getFalse(); // X < (small) --> false
6409 else
6410 Result = ConstantInt::getTrue(); // X < (large) --> true
6411 } else {
6412 // We're performing an unsigned comparison.
6413 if (isSignedExt) {
6414 // We're performing an unsigned comp with a sign extended value.
6415 // This is true if the input is >= 0. [aka >s -1]
6416 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6417 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6418 NegOne, ICI.getName()), ICI);
6419 } else {
6420 // Unsigned extend & unsigned compare -> always true.
6421 Result = ConstantInt::getTrue();
6422 }
6423 }
6424
6425 // Finally, return the value computed.
6426 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00006427 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006428 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00006429
6430 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6431 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6432 "ICmp should be folded!");
6433 if (Constant *CI = dyn_cast<Constant>(Result))
6434 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6435 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006436}
6437
6438Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6439 return commonShiftTransforms(I);
6440}
6441
6442Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6443 return commonShiftTransforms(I);
6444}
6445
6446Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006447 if (Instruction *R = commonShiftTransforms(I))
6448 return R;
6449
6450 Value *Op0 = I.getOperand(0);
6451
6452 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6453 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6454 if (CSI->isAllOnesValue())
6455 return ReplaceInstUsesWith(I, CSI);
6456
6457 // See if we can turn a signed shr into an unsigned shr.
Nate Begemanbb1ce942008-07-29 15:49:41 +00006458 if (!isa<VectorType>(I.getType()) &&
6459 MaskedValueIsZero(Op0,
Chris Lattnere3c504f2007-12-06 01:59:46 +00006460 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006461 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006462
6463 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006464}
6465
6466Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6467 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6469
6470 // shl X, 0 == X and shr X, 0 == X
6471 // shl 0, X == 0 and shr 0, X == 0
6472 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6473 Op0 == Constant::getNullValue(Op0->getType()))
6474 return ReplaceInstUsesWith(I, Op0);
6475
6476 if (isa<UndefValue>(Op0)) {
6477 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6478 return ReplaceInstUsesWith(I, Op0);
6479 else // undef << X -> 0, undef >>u X -> 0
6480 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6481 }
6482 if (isa<UndefValue>(Op1)) {
6483 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6484 return ReplaceInstUsesWith(I, Op0);
6485 else // X << undef, X >>u undef -> 0
6486 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6487 }
6488
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006489 // Try to fold constant and into select arguments.
6490 if (isa<Constant>(Op0))
6491 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6493 return R;
6494
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006495 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6496 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6497 return Res;
6498 return 0;
6499}
6500
6501Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6502 BinaryOperator &I) {
6503 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6504
6505 // See if we can simplify any instructions used by the instruction whose sole
6506 // purpose is to compute bits we don't care about.
6507 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6508 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6509 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6510 KnownZero, KnownOne))
6511 return &I;
6512
6513 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6514 // of a signed value.
6515 //
6516 if (Op1->uge(TypeBits)) {
6517 if (I.getOpcode() != Instruction::AShr)
6518 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6519 else {
6520 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6521 return &I;
6522 }
6523 }
6524
6525 // ((X*C1) << C2) == (X * (C1 << C2))
6526 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6527 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6528 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006529 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006530 ConstantExpr::getShl(BOOp, Op1));
6531
6532 // Try to fold constant and into select arguments.
6533 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6534 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6535 return R;
6536 if (isa<PHINode>(Op0))
6537 if (Instruction *NV = FoldOpIntoPhi(I))
6538 return NV;
6539
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006540 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6541 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6542 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6543 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6544 // place. Don't try to do this transformation in this case. Also, we
6545 // require that the input operand is a shift-by-constant so that we have
6546 // confidence that the shifts will get folded together. We could do this
6547 // xform in more cases, but it is unlikely to be profitable.
6548 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6549 isa<ConstantInt>(TrOp->getOperand(1))) {
6550 // Okay, we'll do this xform. Make the shift of shift.
6551 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006552 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006553 I.getName());
6554 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6555
6556 // For logical shifts, the truncation has the effect of making the high
6557 // part of the register be zeros. Emulate this by inserting an AND to
6558 // clear the top bits as needed. This 'and' will usually be zapped by
6559 // other xforms later if dead.
6560 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6561 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6562 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6563
6564 // The mask we constructed says what the trunc would do if occurring
6565 // between the shifts. We want to know the effect *after* the second
6566 // shift. We know that it is a logical shift by a constant, so adjust the
6567 // mask as appropriate.
6568 if (I.getOpcode() == Instruction::Shl)
6569 MaskV <<= Op1->getZExtValue();
6570 else {
6571 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6572 MaskV = MaskV.lshr(Op1->getZExtValue());
6573 }
6574
Gabor Greifa645dd32008-05-16 19:29:10 +00006575 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006576 TI->getName());
6577 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6578
6579 // Return the value truncated to the interesting size.
6580 return new TruncInst(And, I.getType());
6581 }
6582 }
6583
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006584 if (Op0->hasOneUse()) {
6585 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6586 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6587 Value *V1, *V2;
6588 ConstantInt *CC;
6589 switch (Op0BO->getOpcode()) {
6590 default: break;
6591 case Instruction::Add:
6592 case Instruction::And:
6593 case Instruction::Or:
6594 case Instruction::Xor: {
6595 // These operators commute.
6596 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6597 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6598 match(Op0BO->getOperand(1),
6599 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006600 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006601 Op0BO->getOperand(0), Op1,
6602 Op0BO->getName());
6603 InsertNewInstBefore(YS, I); // (Y << C)
6604 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006605 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006606 Op0BO->getOperand(1)->getName());
6607 InsertNewInstBefore(X, I); // (X + (Y << C))
6608 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006609 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006610 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6611 }
6612
6613 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6614 Value *Op0BOOp1 = Op0BO->getOperand(1);
6615 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6616 match(Op0BOOp1,
6617 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6618 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6619 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006620 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006621 Op0BO->getOperand(0), Op1,
6622 Op0BO->getName());
6623 InsertNewInstBefore(YS, I); // (Y << C)
6624 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006625 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006626 V1->getName()+".mask");
6627 InsertNewInstBefore(XM, I); // X & (CC << C)
6628
Gabor Greifa645dd32008-05-16 19:29:10 +00006629 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006630 }
6631 }
6632
6633 // FALL THROUGH.
6634 case Instruction::Sub: {
6635 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6636 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6637 match(Op0BO->getOperand(0),
6638 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006639 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006640 Op0BO->getOperand(1), Op1,
6641 Op0BO->getName());
6642 InsertNewInstBefore(YS, I); // (Y << C)
6643 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006644 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006645 Op0BO->getOperand(0)->getName());
6646 InsertNewInstBefore(X, I); // (X + (Y << C))
6647 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006648 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006649 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6650 }
6651
6652 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6653 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6654 match(Op0BO->getOperand(0),
6655 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6656 m_ConstantInt(CC))) && V2 == Op1 &&
6657 cast<BinaryOperator>(Op0BO->getOperand(0))
6658 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006659 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006660 Op0BO->getOperand(1), Op1,
6661 Op0BO->getName());
6662 InsertNewInstBefore(YS, I); // (Y << C)
6663 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006664 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006665 V1->getName()+".mask");
6666 InsertNewInstBefore(XM, I); // X & (CC << C)
6667
Gabor Greifa645dd32008-05-16 19:29:10 +00006668 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006669 }
6670
6671 break;
6672 }
6673 }
6674
6675
6676 // If the operand is an bitwise operator with a constant RHS, and the
6677 // shift is the only use, we can pull it out of the shift.
6678 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6679 bool isValid = true; // Valid only for And, Or, Xor
6680 bool highBitSet = false; // Transform if high bit of constant set?
6681
6682 switch (Op0BO->getOpcode()) {
6683 default: isValid = false; break; // Do not perform transform!
6684 case Instruction::Add:
6685 isValid = isLeftShift;
6686 break;
6687 case Instruction::Or:
6688 case Instruction::Xor:
6689 highBitSet = false;
6690 break;
6691 case Instruction::And:
6692 highBitSet = true;
6693 break;
6694 }
6695
6696 // If this is a signed shift right, and the high bit is modified
6697 // by the logical operation, do not perform the transformation.
6698 // The highBitSet boolean indicates the value of the high bit of
6699 // the constant which would cause it to be modified for this
6700 // operation.
6701 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006702 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006703 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006704
6705 if (isValid) {
6706 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6707
6708 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006709 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006710 InsertNewInstBefore(NewShift, I);
6711 NewShift->takeName(Op0BO);
6712
Gabor Greifa645dd32008-05-16 19:29:10 +00006713 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006714 NewRHS);
6715 }
6716 }
6717 }
6718 }
6719
6720 // Find out if this is a shift of a shift by a constant.
6721 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6722 if (ShiftOp && !ShiftOp->isShift())
6723 ShiftOp = 0;
6724
6725 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6726 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6727 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6728 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6729 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6730 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6731 Value *X = ShiftOp->getOperand(0);
6732
6733 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6734 if (AmtSum > TypeBits)
6735 AmtSum = TypeBits;
6736
6737 const IntegerType *Ty = cast<IntegerType>(I.getType());
6738
6739 // Check for (X << c1) << c2 and (X >> c1) >> c2
6740 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006741 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006742 ConstantInt::get(Ty, AmtSum));
6743 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6744 I.getOpcode() == Instruction::AShr) {
6745 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006746 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006747 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6748 I.getOpcode() == Instruction::LShr) {
6749 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6750 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006751 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006752 InsertNewInstBefore(Shift, I);
6753
6754 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006755 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006756 }
6757
6758 // Okay, if we get here, one shift must be left, and the other shift must be
6759 // right. See if the amounts are equal.
6760 if (ShiftAmt1 == ShiftAmt2) {
6761 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6762 if (I.getOpcode() == Instruction::Shl) {
6763 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006764 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006765 }
6766 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6767 if (I.getOpcode() == Instruction::LShr) {
6768 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006769 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006770 }
6771 // We can simplify ((X << C) >>s C) into a trunc + sext.
6772 // NOTE: we could do this for any C, but that would make 'unusual' integer
6773 // types. For now, just stick to ones well-supported by the code
6774 // generators.
6775 const Type *SExtType = 0;
6776 switch (Ty->getBitWidth() - ShiftAmt1) {
6777 case 1 :
6778 case 8 :
6779 case 16 :
6780 case 32 :
6781 case 64 :
6782 case 128:
6783 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6784 break;
6785 default: break;
6786 }
6787 if (SExtType) {
6788 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6789 InsertNewInstBefore(NewTrunc, I);
6790 return new SExtInst(NewTrunc, Ty);
6791 }
6792 // Otherwise, we can't handle it yet.
6793 } else if (ShiftAmt1 < ShiftAmt2) {
6794 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6795
6796 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6797 if (I.getOpcode() == Instruction::Shl) {
6798 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6799 ShiftOp->getOpcode() == Instruction::AShr);
6800 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006801 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006802 InsertNewInstBefore(Shift, I);
6803
6804 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006805 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006806 }
6807
6808 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6809 if (I.getOpcode() == Instruction::LShr) {
6810 assert(ShiftOp->getOpcode() == Instruction::Shl);
6811 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006812 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006813 InsertNewInstBefore(Shift, I);
6814
6815 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006816 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006817 }
6818
6819 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6820 } else {
6821 assert(ShiftAmt2 < ShiftAmt1);
6822 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6823
6824 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6825 if (I.getOpcode() == Instruction::Shl) {
6826 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6827 ShiftOp->getOpcode() == Instruction::AShr);
6828 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006829 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006830 ConstantInt::get(Ty, ShiftDiff));
6831 InsertNewInstBefore(Shift, I);
6832
6833 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006834 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006835 }
6836
6837 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6838 if (I.getOpcode() == Instruction::LShr) {
6839 assert(ShiftOp->getOpcode() == Instruction::Shl);
6840 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006841 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006842 InsertNewInstBefore(Shift, I);
6843
6844 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006845 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006846 }
6847
6848 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6849 }
6850 }
6851 return 0;
6852}
6853
6854
6855/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6856/// expression. If so, decompose it, returning some value X, such that Val is
6857/// X*Scale+Offset.
6858///
6859static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6860 int &Offset) {
6861 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6862 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6863 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006864 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006865 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006866 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6867 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6868 if (I->getOpcode() == Instruction::Shl) {
6869 // This is a value scaled by '1 << the shift amt'.
6870 Scale = 1U << RHS->getZExtValue();
6871 Offset = 0;
6872 return I->getOperand(0);
6873 } else if (I->getOpcode() == Instruction::Mul) {
6874 // This value is scaled by 'RHS'.
6875 Scale = RHS->getZExtValue();
6876 Offset = 0;
6877 return I->getOperand(0);
6878 } else if (I->getOpcode() == Instruction::Add) {
6879 // We have X+C. Check to see if we really have (X*C2)+C1,
6880 // where C1 is divisible by C2.
6881 unsigned SubScale;
6882 Value *SubVal =
6883 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6884 Offset += RHS->getZExtValue();
6885 Scale = SubScale;
6886 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006887 }
6888 }
6889 }
6890
6891 // Otherwise, we can't look past this.
6892 Scale = 1;
6893 Offset = 0;
6894 return Val;
6895}
6896
6897
6898/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6899/// try to eliminate the cast by moving the type information into the alloc.
6900Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6901 AllocationInst &AI) {
6902 const PointerType *PTy = cast<PointerType>(CI.getType());
6903
6904 // Remove any uses of AI that are dead.
6905 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6906
6907 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6908 Instruction *User = cast<Instruction>(*UI++);
6909 if (isInstructionTriviallyDead(User)) {
6910 while (UI != E && *UI == User)
6911 ++UI; // If this instruction uses AI more than once, don't break UI.
6912
6913 ++NumDeadInst;
6914 DOUT << "IC: DCE: " << *User;
6915 EraseInstFromFunction(*User);
6916 }
6917 }
6918
6919 // Get the type really allocated and the type casted to.
6920 const Type *AllocElTy = AI.getAllocatedType();
6921 const Type *CastElTy = PTy->getElementType();
6922 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6923
6924 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6925 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6926 if (CastElTyAlign < AllocElTyAlign) return 0;
6927
6928 // If the allocation has multiple uses, only promote it if we are strictly
6929 // increasing the alignment of the resultant allocation. If we keep it the
6930 // same, we open the door to infinite loops of various kinds.
6931 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6932
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006933 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6934 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006935 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6936
6937 // See if we can satisfy the modulus by pulling a scale out of the array
6938 // size argument.
6939 unsigned ArraySizeScale;
6940 int ArrayOffset;
6941 Value *NumElements = // See if the array size is a decomposable linear expr.
6942 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6943
6944 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6945 // do the xform.
6946 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6947 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6948
6949 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6950 Value *Amt = 0;
6951 if (Scale == 1) {
6952 Amt = NumElements;
6953 } else {
6954 // If the allocation size is constant, form a constant mul expression
6955 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6956 if (isa<ConstantInt>(NumElements))
6957 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6958 // otherwise multiply the amount and the number of elements
6959 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006960 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006961 Amt = InsertNewInstBefore(Tmp, AI);
6962 }
6963 }
6964
6965 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6966 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00006967 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006968 Amt = InsertNewInstBefore(Tmp, AI);
6969 }
6970
6971 AllocationInst *New;
6972 if (isa<MallocInst>(AI))
6973 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6974 else
6975 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6976 InsertNewInstBefore(New, AI);
6977 New->takeName(&AI);
6978
6979 // If the allocation has multiple uses, insert a cast and change all things
6980 // that used it to use the new cast. This will also hack on CI, but it will
6981 // die soon.
6982 if (!AI.hasOneUse()) {
6983 AddUsesToWorkList(AI);
6984 // New is the allocation instruction, pointer typed. AI is the original
6985 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6986 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6987 InsertNewInstBefore(NewCast, AI);
6988 AI.replaceAllUsesWith(NewCast);
6989 }
6990 return ReplaceInstUsesWith(CI, New);
6991}
6992
6993/// CanEvaluateInDifferentType - Return true if we can take the specified value
6994/// and return it as type Ty without inserting any new casts and without
6995/// changing the computed value. This is used by code that tries to decide
6996/// whether promoting or shrinking integer operations to wider or smaller types
6997/// will allow us to eliminate a truncate or extend.
6998///
6999/// This is a truncation operation if Ty is smaller than V->getType(), or an
7000/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007001///
7002/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7003/// should return true if trunc(V) can be computed by computing V in the smaller
7004/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7005/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7006/// efficiently truncated.
7007///
7008/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7009/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7010/// the final result.
Dan Gohman2d648bb2008-04-10 18:43:06 +00007011bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7012 unsigned CastOpc,
7013 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007014 // We can always evaluate constants in another type.
7015 if (isa<ConstantInt>(V))
7016 return true;
7017
7018 Instruction *I = dyn_cast<Instruction>(V);
7019 if (!I) return false;
7020
7021 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7022
Chris Lattneref70bb82007-08-02 06:11:14 +00007023 // If this is an extension or truncate, we can often eliminate it.
7024 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7025 // If this is a cast from the destination type, we can trivially eliminate
7026 // it, and this will remove a cast overall.
7027 if (I->getOperand(0)->getType() == Ty) {
7028 // If the first operand is itself a cast, and is eliminable, do not count
7029 // this as an eliminable cast. We would prefer to eliminate those two
7030 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007031 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007032 ++NumCastsRemoved;
7033 return true;
7034 }
7035 }
7036
7037 // We can't extend or shrink something that has multiple uses: doing so would
7038 // require duplicating the instruction in general, which isn't profitable.
7039 if (!I->hasOneUse()) return false;
7040
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007041 switch (I->getOpcode()) {
7042 case Instruction::Add:
7043 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007044 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007045 case Instruction::And:
7046 case Instruction::Or:
7047 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007048 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007049 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7050 NumCastsRemoved) &&
7051 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7052 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007053
7054 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007055 // If we are truncating the result of this SHL, and if it's a shift of a
7056 // constant amount, we can always perform a SHL in a smaller type.
7057 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7058 uint32_t BitWidth = Ty->getBitWidth();
7059 if (BitWidth < OrigTy->getBitWidth() &&
7060 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007061 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7062 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007063 }
7064 break;
7065 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007066 // If this is a truncate of a logical shr, we can truncate it to a smaller
7067 // lshr iff we know that the bits we would otherwise be shifting in are
7068 // already zeros.
7069 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7070 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7071 uint32_t BitWidth = Ty->getBitWidth();
7072 if (BitWidth < OrigBitWidth &&
7073 MaskedValueIsZero(I->getOperand(0),
7074 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7075 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007076 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7077 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007078 }
7079 }
7080 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007081 case Instruction::ZExt:
7082 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007083 case Instruction::Trunc:
7084 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007085 // can safely replace it. Note that replacing it does not reduce the number
7086 // of casts in the input.
7087 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007088 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007089 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007090 case Instruction::Select: {
7091 SelectInst *SI = cast<SelectInst>(I);
7092 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7093 NumCastsRemoved) &&
7094 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7095 NumCastsRemoved);
7096 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007097 case Instruction::PHI: {
7098 // We can change a phi if we can change all operands.
7099 PHINode *PN = cast<PHINode>(I);
7100 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7101 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7102 NumCastsRemoved))
7103 return false;
7104 return true;
7105 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007106 default:
7107 // TODO: Can handle more cases here.
7108 break;
7109 }
7110
7111 return false;
7112}
7113
7114/// EvaluateInDifferentType - Given an expression that
7115/// CanEvaluateInDifferentType returns true for, actually insert the code to
7116/// evaluate the expression.
7117Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7118 bool isSigned) {
7119 if (Constant *C = dyn_cast<Constant>(V))
7120 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7121
7122 // Otherwise, it must be an instruction.
7123 Instruction *I = cast<Instruction>(V);
7124 Instruction *Res = 0;
7125 switch (I->getOpcode()) {
7126 case Instruction::Add:
7127 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007128 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007129 case Instruction::And:
7130 case Instruction::Or:
7131 case Instruction::Xor:
7132 case Instruction::AShr:
7133 case Instruction::LShr:
7134 case Instruction::Shl: {
7135 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7136 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007137 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattner4200c2062008-06-18 04:00:49 +00007138 LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007139 break;
7140 }
7141 case Instruction::Trunc:
7142 case Instruction::ZExt:
7143 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007144 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007145 // just return the source. There's no need to insert it because it is not
7146 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 if (I->getOperand(0)->getType() == Ty)
7148 return I->getOperand(0);
7149
Chris Lattner4200c2062008-06-18 04:00:49 +00007150 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007151 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007152 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007153 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007154 case Instruction::Select: {
7155 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7156 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7157 Res = SelectInst::Create(I->getOperand(0), True, False);
7158 break;
7159 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007160 case Instruction::PHI: {
7161 PHINode *OPN = cast<PHINode>(I);
7162 PHINode *NPN = PHINode::Create(Ty);
7163 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7164 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7165 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7166 }
7167 Res = NPN;
7168 break;
7169 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007170 default:
7171 // TODO: Can handle more cases here.
7172 assert(0 && "Unreachable!");
7173 break;
7174 }
7175
Chris Lattner4200c2062008-06-18 04:00:49 +00007176 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007177 return InsertNewInstBefore(Res, *I);
7178}
7179
7180/// @brief Implement the transforms common to all CastInst visitors.
7181Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7182 Value *Src = CI.getOperand(0);
7183
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007184 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7185 // eliminate it now.
7186 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7187 if (Instruction::CastOps opc =
7188 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7189 // The first cast (CSrc) is eliminable so we need to fix up or replace
7190 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007191 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007192 }
7193 }
7194
7195 // If we are casting a select then fold the cast into the select
7196 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7197 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7198 return NV;
7199
7200 // If we are casting a PHI then fold the cast into the PHI
7201 if (isa<PHINode>(Src))
7202 if (Instruction *NV = FoldOpIntoPhi(CI))
7203 return NV;
7204
7205 return 0;
7206}
7207
7208/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7209Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7210 Value *Src = CI.getOperand(0);
7211
7212 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7213 // If casting the result of a getelementptr instruction with no offset, turn
7214 // this into a cast of the original pointer!
7215 if (GEP->hasAllZeroIndices()) {
7216 // Changing the cast operand is usually not a good idea but it is safe
7217 // here because the pointer operand is being replaced with another
7218 // pointer operand so the opcode doesn't need to change.
7219 AddToWorkList(GEP);
7220 CI.setOperand(0, GEP->getOperand(0));
7221 return &CI;
7222 }
7223
7224 // If the GEP has a single use, and the base pointer is a bitcast, and the
7225 // GEP computes a constant offset, see if we can convert these three
7226 // instructions into fewer. This typically happens with unions and other
7227 // non-type-safe code.
7228 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7229 if (GEP->hasAllConstantIndices()) {
7230 // We are guaranteed to get a constant from EmitGEPOffset.
7231 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7232 int64_t Offset = OffsetV->getSExtValue();
7233
7234 // Get the base pointer input of the bitcast, and the type it points to.
7235 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7236 const Type *GEPIdxTy =
7237 cast<PointerType>(OrigBase->getType())->getElementType();
7238 if (GEPIdxTy->isSized()) {
7239 SmallVector<Value*, 8> NewIndices;
7240
7241 // Start with the index over the outer type. Note that the type size
7242 // might be zero (even if the offset isn't zero) if the indexed type
7243 // is something like [0 x {int, int}]
7244 const Type *IntPtrTy = TD->getIntPtrType();
7245 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007246 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007247 FirstIdx = Offset/TySize;
7248 Offset %= TySize;
7249
7250 // Handle silly modulus not returning values values [0..TySize).
7251 if (Offset < 0) {
7252 --FirstIdx;
7253 Offset += TySize;
7254 assert(Offset >= 0);
7255 }
7256 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7257 }
7258
7259 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7260
7261 // Index into the types. If we fail, set OrigBase to null.
7262 while (Offset) {
7263 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7264 const StructLayout *SL = TD->getStructLayout(STy);
7265 if (Offset < (int64_t)SL->getSizeInBytes()) {
7266 unsigned Elt = SL->getElementContainingOffset(Offset);
7267 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7268
7269 Offset -= SL->getElementOffset(Elt);
7270 GEPIdxTy = STy->getElementType(Elt);
7271 } else {
7272 // Otherwise, we can't index into this, bail out.
7273 Offset = 0;
7274 OrigBase = 0;
7275 }
7276 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7277 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007278 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007279 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7280 Offset %= EltSize;
7281 } else {
7282 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7283 }
7284 GEPIdxTy = STy->getElementType();
7285 } else {
7286 // Otherwise, we can't index into this, bail out.
7287 Offset = 0;
7288 OrigBase = 0;
7289 }
7290 }
7291 if (OrigBase) {
7292 // If we were able to index down into an element, create the GEP
7293 // and bitcast the result. This eliminates one bitcast, potentially
7294 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007295 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7296 NewIndices.begin(),
7297 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007298 InsertNewInstBefore(NGEP, CI);
7299 NGEP->takeName(GEP);
7300
7301 if (isa<BitCastInst>(CI))
7302 return new BitCastInst(NGEP, CI.getType());
7303 assert(isa<PtrToIntInst>(CI));
7304 return new PtrToIntInst(NGEP, CI.getType());
7305 }
7306 }
7307 }
7308 }
7309 }
7310
7311 return commonCastTransforms(CI);
7312}
7313
7314
7315
7316/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7317/// integer types. This function implements the common transforms for all those
7318/// cases.
7319/// @brief Implement the transforms common to CastInst with integer operands
7320Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7321 if (Instruction *Result = commonCastTransforms(CI))
7322 return Result;
7323
7324 Value *Src = CI.getOperand(0);
7325 const Type *SrcTy = Src->getType();
7326 const Type *DestTy = CI.getType();
7327 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7328 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7329
7330 // See if we can simplify any instructions used by the LHS whose sole
7331 // purpose is to compute bits we don't care about.
7332 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7333 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7334 KnownZero, KnownOne))
7335 return &CI;
7336
7337 // If the source isn't an instruction or has more than one use then we
7338 // can't do anything more.
7339 Instruction *SrcI = dyn_cast<Instruction>(Src);
7340 if (!SrcI || !Src->hasOneUse())
7341 return 0;
7342
7343 // Attempt to propagate the cast into the instruction for int->int casts.
7344 int NumCastsRemoved = 0;
7345 if (!isa<BitCastInst>(CI) &&
7346 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007347 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007348 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007349 // eliminates the cast, so it is always a win. If this is a zero-extension,
7350 // we need to do an AND to maintain the clear top-part of the computation,
7351 // so we require that the input have eliminated at least one cast. If this
7352 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007353 // require that two casts have been eliminated.
7354 bool DoXForm;
7355 switch (CI.getOpcode()) {
7356 default:
7357 // All the others use floating point so we shouldn't actually
7358 // get here because of the check above.
7359 assert(0 && "Unknown cast type");
7360 case Instruction::Trunc:
7361 DoXForm = true;
7362 break;
7363 case Instruction::ZExt:
7364 DoXForm = NumCastsRemoved >= 1;
7365 break;
7366 case Instruction::SExt:
7367 DoXForm = NumCastsRemoved >= 2;
7368 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007369 }
7370
7371 if (DoXForm) {
7372 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7373 CI.getOpcode() == Instruction::SExt);
7374 assert(Res->getType() == DestTy);
7375 switch (CI.getOpcode()) {
7376 default: assert(0 && "Unknown cast type!");
7377 case Instruction::Trunc:
7378 case Instruction::BitCast:
7379 // Just replace this cast with the result.
7380 return ReplaceInstUsesWith(CI, Res);
7381 case Instruction::ZExt: {
7382 // We need to emit an AND to clear the high bits.
7383 assert(SrcBitSize < DestBitSize && "Not a zext?");
7384 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7385 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007386 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007387 }
7388 case Instruction::SExt:
7389 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007390 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007391 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7392 CI), DestTy);
7393 }
7394 }
7395 }
7396
7397 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7398 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7399
7400 switch (SrcI->getOpcode()) {
7401 case Instruction::Add:
7402 case Instruction::Mul:
7403 case Instruction::And:
7404 case Instruction::Or:
7405 case Instruction::Xor:
7406 // If we are discarding information, rewrite.
7407 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7408 // Don't insert two casts if they cannot be eliminated. We allow
7409 // two casts to be inserted if the sizes are the same. This could
7410 // only be converting signedness, which is a noop.
7411 if (DestBitSize == SrcBitSize ||
7412 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7413 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7414 Instruction::CastOps opcode = CI.getOpcode();
7415 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7416 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007417 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007418 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7419 }
7420 }
7421
7422 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7423 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7424 SrcI->getOpcode() == Instruction::Xor &&
7425 Op1 == ConstantInt::getTrue() &&
7426 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7427 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007428 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007429 }
7430 break;
7431 case Instruction::SDiv:
7432 case Instruction::UDiv:
7433 case Instruction::SRem:
7434 case Instruction::URem:
7435 // If we are just changing the sign, rewrite.
7436 if (DestBitSize == SrcBitSize) {
7437 // Don't insert two casts if they cannot be eliminated. We allow
7438 // two casts to be inserted if the sizes are the same. This could
7439 // only be converting signedness, which is a noop.
7440 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7441 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7442 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7443 Op0, DestTy, SrcI);
7444 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7445 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007446 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007447 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7448 }
7449 }
7450 break;
7451
7452 case Instruction::Shl:
7453 // Allow changing the sign of the source operand. Do not allow
7454 // changing the size of the shift, UNLESS the shift amount is a
7455 // constant. We must not change variable sized shifts to a smaller
7456 // size, because it is undefined to shift more bits out than exist
7457 // in the value.
7458 if (DestBitSize == SrcBitSize ||
7459 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7460 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7461 Instruction::BitCast : Instruction::Trunc);
7462 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7463 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007464 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007465 }
7466 break;
7467 case Instruction::AShr:
7468 // If this is a signed shr, and if all bits shifted in are about to be
7469 // truncated off, turn it into an unsigned shr to allow greater
7470 // simplifications.
7471 if (DestBitSize < SrcBitSize &&
7472 isa<ConstantInt>(Op1)) {
7473 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7474 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7475 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007476 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007477 }
7478 }
7479 break;
7480 }
7481 return 0;
7482}
7483
7484Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7485 if (Instruction *Result = commonIntCastTransforms(CI))
7486 return Result;
7487
7488 Value *Src = CI.getOperand(0);
7489 const Type *Ty = CI.getType();
7490 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7491 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7492
7493 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7494 switch (SrcI->getOpcode()) {
7495 default: break;
7496 case Instruction::LShr:
7497 // We can shrink lshr to something smaller if we know the bits shifted in
7498 // are already zeros.
7499 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7500 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7501
7502 // Get a mask for the bits shifting in.
7503 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7504 Value* SrcIOp0 = SrcI->getOperand(0);
7505 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7506 if (ShAmt >= DestBitWidth) // All zeros.
7507 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7508
7509 // Okay, we can shrink this. Truncate the input, then return a new
7510 // shift.
7511 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7512 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7513 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007514 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007515 }
7516 } else { // This is a variable shr.
7517
7518 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7519 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7520 // loop-invariant and CSE'd.
7521 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7522 Value *One = ConstantInt::get(SrcI->getType(), 1);
7523
7524 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007525 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007526 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007527 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007528 SrcI->getOperand(0),
7529 "tmp"), CI);
7530 Value *Zero = Constant::getNullValue(V->getType());
7531 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7532 }
7533 }
7534 break;
7535 }
7536 }
7537
7538 return 0;
7539}
7540
Evan Chenge3779cf2008-03-24 00:21:34 +00007541/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7542/// in order to eliminate the icmp.
7543Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7544 bool DoXform) {
7545 // If we are just checking for a icmp eq of a single bit and zext'ing it
7546 // to an integer, then shift the bit to the appropriate place and then
7547 // cast to integer to avoid the comparison.
7548 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7549 const APInt &Op1CV = Op1C->getValue();
7550
7551 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7552 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7553 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7554 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7555 if (!DoXform) return ICI;
7556
7557 Value *In = ICI->getOperand(0);
7558 Value *Sh = ConstantInt::get(In->getType(),
7559 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007560 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007561 In->getName()+".lobit"),
7562 CI);
7563 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007564 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007565 false/*ZExt*/, "tmp", &CI);
7566
7567 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7568 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007569 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007570 In->getName()+".not"),
7571 CI);
7572 }
7573
7574 return ReplaceInstUsesWith(CI, In);
7575 }
7576
7577
7578
7579 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7580 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7581 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7582 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7583 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7584 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7585 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7586 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7587 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7588 // This only works for EQ and NE
7589 ICI->isEquality()) {
7590 // If Op1C some other power of two, convert:
7591 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7592 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7593 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7594 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7595
7596 APInt KnownZeroMask(~KnownZero);
7597 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7598 if (!DoXform) return ICI;
7599
7600 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7601 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7602 // (X&4) == 2 --> false
7603 // (X&4) != 2 --> true
7604 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7605 Res = ConstantExpr::getZExt(Res, CI.getType());
7606 return ReplaceInstUsesWith(CI, Res);
7607 }
7608
7609 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7610 Value *In = ICI->getOperand(0);
7611 if (ShiftAmt) {
7612 // Perform a logical shr by shiftamt.
7613 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007614 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007615 ConstantInt::get(In->getType(), ShiftAmt),
7616 In->getName()+".lobit"), CI);
7617 }
7618
7619 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7620 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007621 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007622 InsertNewInstBefore(cast<Instruction>(In), CI);
7623 }
7624
7625 if (CI.getType() == In->getType())
7626 return ReplaceInstUsesWith(CI, In);
7627 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007628 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007629 }
7630 }
7631 }
7632
7633 return 0;
7634}
7635
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007636Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7637 // If one of the common conversion will work ..
7638 if (Instruction *Result = commonIntCastTransforms(CI))
7639 return Result;
7640
7641 Value *Src = CI.getOperand(0);
7642
7643 // If this is a cast of a cast
7644 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7645 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7646 // types and if the sizes are just right we can convert this into a logical
7647 // 'and' which will be much cheaper than the pair of casts.
7648 if (isa<TruncInst>(CSrc)) {
7649 // Get the sizes of the types involved
7650 Value *A = CSrc->getOperand(0);
7651 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7652 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7653 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7654 // If we're actually extending zero bits and the trunc is a no-op
7655 if (MidSize < DstSize && SrcSize == DstSize) {
7656 // Replace both of the casts with an And of the type mask.
7657 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7658 Constant *AndConst = ConstantInt::get(AndValue);
7659 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007660 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007661 // Unfortunately, if the type changed, we need to cast it back.
7662 if (And->getType() != CI.getType()) {
7663 And->setName(CSrc->getName()+".mask");
7664 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007665 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007666 }
7667 return And;
7668 }
7669 }
7670 }
7671
Evan Chenge3779cf2008-03-24 00:21:34 +00007672 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7673 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007674
Evan Chenge3779cf2008-03-24 00:21:34 +00007675 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7676 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7677 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7678 // of the (zext icmp) will be transformed.
7679 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7680 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7681 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7682 (transformZExtICmp(LHS, CI, false) ||
7683 transformZExtICmp(RHS, CI, false))) {
7684 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7685 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007686 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007687 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007688 }
7689
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007690 return 0;
7691}
7692
7693Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7694 if (Instruction *I = commonIntCastTransforms(CI))
7695 return I;
7696
7697 Value *Src = CI.getOperand(0);
7698
7699 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7700 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7701 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7702 // If we are just checking for a icmp eq of a single bit and zext'ing it
7703 // to an integer, then shift the bit to the appropriate place and then
7704 // cast to integer to avoid the comparison.
7705 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7706 const APInt &Op1CV = Op1C->getValue();
7707
7708 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7709 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7710 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7711 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7712 Value *In = ICI->getOperand(0);
7713 Value *Sh = ConstantInt::get(In->getType(),
7714 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007715 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007716 In->getName()+".lobit"),
7717 CI);
7718 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007719 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007720 true/*SExt*/, "tmp", &CI);
7721
7722 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007723 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007724 In->getName()+".not"), CI);
7725
7726 return ReplaceInstUsesWith(CI, In);
7727 }
7728 }
7729 }
Dan Gohmanf0f12022008-05-20 21:01:12 +00007730
7731 // See if the value being truncated is already sign extended. If so, just
7732 // eliminate the trunc/sext pair.
7733 if (getOpcode(Src) == Instruction::Trunc) {
7734 Value *Op = cast<User>(Src)->getOperand(0);
7735 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7736 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7737 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7738 unsigned NumSignBits = ComputeNumSignBits(Op);
7739
7740 if (OpBits == DestBits) {
7741 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7742 // bits, it is already ready.
7743 if (NumSignBits > DestBits-MidBits)
7744 return ReplaceInstUsesWith(CI, Op);
7745 } else if (OpBits < DestBits) {
7746 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7747 // bits, just sext from i32.
7748 if (NumSignBits > OpBits-MidBits)
7749 return new SExtInst(Op, CI.getType(), "tmp");
7750 } else {
7751 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7752 // bits, just truncate to i32.
7753 if (NumSignBits > OpBits-MidBits)
7754 return new TruncInst(Op, CI.getType(), "tmp");
7755 }
7756 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00007757
7758 // If the input is a shl/ashr pair of a same constant, then this is a sign
7759 // extension from a smaller value. If we could trust arbitrary bitwidth
7760 // integers, we could turn this into a truncate to the smaller bit and then
7761 // use a sext for the whole extension. Since we don't, look deeper and check
7762 // for a truncate. If the source and dest are the same type, eliminate the
7763 // trunc and extend and just do shifts. For example, turn:
7764 // %a = trunc i32 %i to i8
7765 // %b = shl i8 %a, 6
7766 // %c = ashr i8 %b, 6
7767 // %d = sext i8 %c to i32
7768 // into:
7769 // %a = shl i32 %i, 30
7770 // %d = ashr i32 %a, 30
7771 Value *A = 0;
7772 ConstantInt *BA = 0, *CA = 0;
7773 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7774 m_ConstantInt(CA))) &&
7775 BA == CA && isa<TruncInst>(A)) {
7776 Value *I = cast<TruncInst>(A)->getOperand(0);
7777 if (I->getType() == CI.getType()) {
7778 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7779 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7780 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7781 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7782 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7783 CI.getName()), CI);
7784 return BinaryOperator::CreateAShr(I, ShAmtV);
7785 }
7786 }
7787
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007788 return 0;
7789}
7790
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007791/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7792/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007793static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007794 APFloat F = CFP->getValueAPF();
7795 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007796 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007797 return 0;
7798}
7799
7800/// LookThroughFPExtensions - If this is an fp extension instruction, look
7801/// through it until we get the source value.
7802static Value *LookThroughFPExtensions(Value *V) {
7803 if (Instruction *I = dyn_cast<Instruction>(V))
7804 if (I->getOpcode() == Instruction::FPExt)
7805 return LookThroughFPExtensions(I->getOperand(0));
7806
7807 // If this value is a constant, return the constant in the smallest FP type
7808 // that can accurately represent it. This allows us to turn
7809 // (float)((double)X+2.0) into x+2.0f.
7810 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7811 if (CFP->getType() == Type::PPC_FP128Ty)
7812 return V; // No constant folding of this.
7813 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007814 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007815 return V;
7816 if (CFP->getType() == Type::DoubleTy)
7817 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007818 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007819 return V;
7820 // Don't try to shrink to various long double types.
7821 }
7822
7823 return V;
7824}
7825
7826Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7827 if (Instruction *I = commonCastTransforms(CI))
7828 return I;
7829
7830 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7831 // smaller than the destination type, we can eliminate the truncate by doing
7832 // the add as the smaller type. This applies to add/sub/mul/div as well as
7833 // many builtins (sqrt, etc).
7834 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7835 if (OpI && OpI->hasOneUse()) {
7836 switch (OpI->getOpcode()) {
7837 default: break;
7838 case Instruction::Add:
7839 case Instruction::Sub:
7840 case Instruction::Mul:
7841 case Instruction::FDiv:
7842 case Instruction::FRem:
7843 const Type *SrcTy = OpI->getType();
7844 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7845 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7846 if (LHSTrunc->getType() != SrcTy &&
7847 RHSTrunc->getType() != SrcTy) {
7848 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7849 // If the source types were both smaller than the destination type of
7850 // the cast, do this xform.
7851 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7852 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7853 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7854 CI.getType(), CI);
7855 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7856 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007857 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007858 }
7859 }
7860 break;
7861 }
7862 }
7863 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007864}
7865
7866Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7867 return commonCastTransforms(CI);
7868}
7869
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007870Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00007871 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7872 if (OpI == 0)
7873 return commonCastTransforms(FI);
7874
7875 // fptoui(uitofp(X)) --> X
7876 // fptoui(sitofp(X)) --> X
7877 // This is safe if the intermediate type has enough bits in its mantissa to
7878 // accurately represent all values of X. For example, do not do this with
7879 // i64->float->i64. This is also safe for sitofp case, because any negative
7880 // 'X' value would cause an undefined result for the fptoui.
7881 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7882 OpI->getOperand(0)->getType() == FI.getType() &&
7883 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7884 OpI->getType()->getFPMantissaWidth())
7885 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007886
7887 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007888}
7889
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007890Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00007891 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7892 if (OpI == 0)
7893 return commonCastTransforms(FI);
7894
7895 // fptosi(sitofp(X)) --> X
7896 // fptosi(uitofp(X)) --> X
7897 // This is safe if the intermediate type has enough bits in its mantissa to
7898 // accurately represent all values of X. For example, do not do this with
7899 // i64->float->i64. This is also safe for sitofp case, because any negative
7900 // 'X' value would cause an undefined result for the fptoui.
7901 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7902 OpI->getOperand(0)->getType() == FI.getType() &&
7903 (int)FI.getType()->getPrimitiveSizeInBits() <=
7904 OpI->getType()->getFPMantissaWidth())
7905 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00007906
7907 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007908}
7909
7910Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7911 return commonCastTransforms(CI);
7912}
7913
7914Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7915 return commonCastTransforms(CI);
7916}
7917
7918Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7919 return commonPointerCastTransforms(CI);
7920}
7921
Chris Lattner7c1626482008-01-08 07:23:51 +00007922Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7923 if (Instruction *I = commonCastTransforms(CI))
7924 return I;
7925
7926 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7927 if (!DestPointee->isSized()) return 0;
7928
7929 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7930 ConstantInt *Cst;
7931 Value *X;
7932 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7933 m_ConstantInt(Cst)))) {
7934 // If the source and destination operands have the same type, see if this
7935 // is a single-index GEP.
7936 if (X->getType() == CI.getType()) {
7937 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007938 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007939
7940 // Convert the constant to intptr type.
7941 APInt Offset = Cst->getValue();
7942 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7943
7944 // If Offset is evenly divisible by Size, we can do this xform.
7945 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7946 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00007947 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00007948 }
7949 }
7950 // TODO: Could handle other cases, e.g. where add is indexing into field of
7951 // struct etc.
7952 } else if (CI.getOperand(0)->hasOneUse() &&
7953 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7954 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7955 // "inttoptr+GEP" instead of "add+intptr".
7956
7957 // Get the size of the pointee type.
7958 uint64_t Size = TD->getABITypeSize(DestPointee);
7959
7960 // Convert the constant to intptr type.
7961 APInt Offset = Cst->getValue();
7962 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7963
7964 // If Offset is evenly divisible by Size, we can do this xform.
7965 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7966 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7967
7968 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7969 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007970 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00007971 }
7972 }
7973 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007974}
7975
7976Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7977 // If the operands are integer typed then apply the integer transforms,
7978 // otherwise just apply the common ones.
7979 Value *Src = CI.getOperand(0);
7980 const Type *SrcTy = Src->getType();
7981 const Type *DestTy = CI.getType();
7982
7983 if (SrcTy->isInteger() && DestTy->isInteger()) {
7984 if (Instruction *Result = commonIntCastTransforms(CI))
7985 return Result;
7986 } else if (isa<PointerType>(SrcTy)) {
7987 if (Instruction *I = commonPointerCastTransforms(CI))
7988 return I;
7989 } else {
7990 if (Instruction *Result = commonCastTransforms(CI))
7991 return Result;
7992 }
7993
7994
7995 // Get rid of casts from one type to the same type. These are useless and can
7996 // be replaced by the operand.
7997 if (DestTy == Src->getType())
7998 return ReplaceInstUsesWith(CI, Src);
7999
8000 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8001 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8002 const Type *DstElTy = DstPTy->getElementType();
8003 const Type *SrcElTy = SrcPTy->getElementType();
8004
Nate Begemandf5b3612008-03-31 00:22:16 +00008005 // If the address spaces don't match, don't eliminate the bitcast, which is
8006 // required for changing types.
8007 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8008 return 0;
8009
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008010 // If we are casting a malloc or alloca to a pointer to a type of the same
8011 // size, rewrite the allocation instruction to allocate the "right" type.
8012 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8013 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8014 return V;
8015
8016 // If the source and destination are pointers, and this cast is equivalent
8017 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8018 // This can enhance SROA and other transforms that want type-safe pointers.
8019 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8020 unsigned NumZeros = 0;
8021 while (SrcElTy != DstElTy &&
8022 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8023 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8024 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8025 ++NumZeros;
8026 }
8027
8028 // If we found a path from the src to dest, create the getelementptr now.
8029 if (SrcElTy == DstElTy) {
8030 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008031 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8032 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008033 }
8034 }
8035
8036 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8037 if (SVI->hasOneUse()) {
8038 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8039 // a bitconvert to a vector with the same # elts.
8040 if (isa<VectorType>(DestTy) &&
8041 cast<VectorType>(DestTy)->getNumElements() ==
8042 SVI->getType()->getNumElements()) {
8043 CastInst *Tmp;
8044 // If either of the operands is a cast from CI.getType(), then
8045 // evaluating the shuffle in the casted destination's type will allow
8046 // us to eliminate at least one cast.
8047 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8048 Tmp->getOperand(0)->getType() == DestTy) ||
8049 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8050 Tmp->getOperand(0)->getType() == DestTy)) {
8051 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8052 SVI->getOperand(0), DestTy, &CI);
8053 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8054 SVI->getOperand(1), DestTy, &CI);
8055 // Return a new shuffle vector. Use the same element ID's, as we
8056 // know the vector types match #elts.
8057 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8058 }
8059 }
8060 }
8061 }
8062 return 0;
8063}
8064
8065/// GetSelectFoldableOperands - We want to turn code that looks like this:
8066/// %C = or %A, %B
8067/// %D = select %cond, %C, %A
8068/// into:
8069/// %C = select %cond, %B, 0
8070/// %D = or %A, %C
8071///
8072/// Assuming that the specified instruction is an operand to the select, return
8073/// a bitmask indicating which operands of this instruction are foldable if they
8074/// equal the other incoming value of the select.
8075///
8076static unsigned GetSelectFoldableOperands(Instruction *I) {
8077 switch (I->getOpcode()) {
8078 case Instruction::Add:
8079 case Instruction::Mul:
8080 case Instruction::And:
8081 case Instruction::Or:
8082 case Instruction::Xor:
8083 return 3; // Can fold through either operand.
8084 case Instruction::Sub: // Can only fold on the amount subtracted.
8085 case Instruction::Shl: // Can only fold on the shift amount.
8086 case Instruction::LShr:
8087 case Instruction::AShr:
8088 return 1;
8089 default:
8090 return 0; // Cannot fold
8091 }
8092}
8093
8094/// GetSelectFoldableConstant - For the same transformation as the previous
8095/// function, return the identity constant that goes into the select.
8096static Constant *GetSelectFoldableConstant(Instruction *I) {
8097 switch (I->getOpcode()) {
8098 default: assert(0 && "This cannot happen!"); abort();
8099 case Instruction::Add:
8100 case Instruction::Sub:
8101 case Instruction::Or:
8102 case Instruction::Xor:
8103 case Instruction::Shl:
8104 case Instruction::LShr:
8105 case Instruction::AShr:
8106 return Constant::getNullValue(I->getType());
8107 case Instruction::And:
8108 return Constant::getAllOnesValue(I->getType());
8109 case Instruction::Mul:
8110 return ConstantInt::get(I->getType(), 1);
8111 }
8112}
8113
8114/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8115/// have the same opcode and only one use each. Try to simplify this.
8116Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8117 Instruction *FI) {
8118 if (TI->getNumOperands() == 1) {
8119 // If this is a non-volatile load or a cast from the same type,
8120 // merge.
8121 if (TI->isCast()) {
8122 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8123 return 0;
8124 } else {
8125 return 0; // unknown unary op.
8126 }
8127
8128 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008129 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8130 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008131 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008132 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008133 TI->getType());
8134 }
8135
8136 // Only handle binary operators here.
8137 if (!isa<BinaryOperator>(TI))
8138 return 0;
8139
8140 // Figure out if the operations have any operands in common.
8141 Value *MatchOp, *OtherOpT, *OtherOpF;
8142 bool MatchIsOpZero;
8143 if (TI->getOperand(0) == FI->getOperand(0)) {
8144 MatchOp = TI->getOperand(0);
8145 OtherOpT = TI->getOperand(1);
8146 OtherOpF = FI->getOperand(1);
8147 MatchIsOpZero = true;
8148 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8149 MatchOp = TI->getOperand(1);
8150 OtherOpT = TI->getOperand(0);
8151 OtherOpF = FI->getOperand(0);
8152 MatchIsOpZero = false;
8153 } else if (!TI->isCommutative()) {
8154 return 0;
8155 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8156 MatchOp = TI->getOperand(0);
8157 OtherOpT = TI->getOperand(1);
8158 OtherOpF = FI->getOperand(0);
8159 MatchIsOpZero = true;
8160 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8161 MatchOp = TI->getOperand(1);
8162 OtherOpT = TI->getOperand(0);
8163 OtherOpF = FI->getOperand(1);
8164 MatchIsOpZero = true;
8165 } else {
8166 return 0;
8167 }
8168
8169 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008170 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8171 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008172 InsertNewInstBefore(NewSI, SI);
8173
8174 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8175 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008176 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008177 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008178 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008179 }
8180 assert(0 && "Shouldn't get here");
8181 return 0;
8182}
8183
8184Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8185 Value *CondVal = SI.getCondition();
8186 Value *TrueVal = SI.getTrueValue();
8187 Value *FalseVal = SI.getFalseValue();
8188
8189 // select true, X, Y -> X
8190 // select false, X, Y -> Y
8191 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8192 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8193
8194 // select C, X, X -> X
8195 if (TrueVal == FalseVal)
8196 return ReplaceInstUsesWith(SI, TrueVal);
8197
8198 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8199 return ReplaceInstUsesWith(SI, FalseVal);
8200 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8201 return ReplaceInstUsesWith(SI, TrueVal);
8202 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8203 if (isa<Constant>(TrueVal))
8204 return ReplaceInstUsesWith(SI, TrueVal);
8205 else
8206 return ReplaceInstUsesWith(SI, FalseVal);
8207 }
8208
8209 if (SI.getType() == Type::Int1Ty) {
8210 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8211 if (C->getZExtValue()) {
8212 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008213 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008214 } else {
8215 // Change: A = select B, false, C --> A = and !B, C
8216 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008217 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008218 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008219 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008220 }
8221 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8222 if (C->getZExtValue() == false) {
8223 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008224 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008225 } else {
8226 // Change: A = select B, C, true --> A = or !B, C
8227 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008228 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008229 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008230 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008231 }
8232 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008233
8234 // select a, b, a -> a&b
8235 // select a, a, b -> a|b
8236 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008237 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008238 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008239 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008240 }
8241
8242 // Selecting between two integer constants?
8243 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8244 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8245 // select C, 1, 0 -> zext C to int
8246 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008247 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008248 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8249 // select C, 0, 1 -> zext !C to int
8250 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008251 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008252 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008253 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008254 }
8255
8256 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8257
8258 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8259
8260 // (x <s 0) ? -1 : 0 -> ashr x, 31
8261 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8262 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8263 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8264 // The comparison constant and the result are not neccessarily the
8265 // same width. Make an all-ones value by inserting a AShr.
8266 Value *X = IC->getOperand(0);
8267 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8268 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008269 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008270 ShAmt, "ones");
8271 InsertNewInstBefore(SRA, SI);
8272
8273 // Finally, convert to the type of the select RHS. We figure out
8274 // if this requires a SExt, Trunc or BitCast based on the sizes.
8275 Instruction::CastOps opc = Instruction::BitCast;
8276 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8277 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8278 if (SRASize < SISize)
8279 opc = Instruction::SExt;
8280 else if (SRASize > SISize)
8281 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008282 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008283 }
8284 }
8285
8286
8287 // If one of the constants is zero (we know they can't both be) and we
8288 // have an icmp instruction with zero, and we have an 'and' with the
8289 // non-constant value, eliminate this whole mess. This corresponds to
8290 // cases like this: ((X & 27) ? 27 : 0)
8291 if (TrueValC->isZero() || FalseValC->isZero())
8292 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8293 cast<Constant>(IC->getOperand(1))->isNullValue())
8294 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8295 if (ICA->getOpcode() == Instruction::And &&
8296 isa<ConstantInt>(ICA->getOperand(1)) &&
8297 (ICA->getOperand(1) == TrueValC ||
8298 ICA->getOperand(1) == FalseValC) &&
8299 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8300 // Okay, now we know that everything is set up, we just don't
8301 // know whether we have a icmp_ne or icmp_eq and whether the
8302 // true or false val is the zero.
8303 bool ShouldNotVal = !TrueValC->isZero();
8304 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8305 Value *V = ICA;
8306 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008307 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008308 Instruction::Xor, V, ICA->getOperand(1)), SI);
8309 return ReplaceInstUsesWith(SI, V);
8310 }
8311 }
8312 }
8313
8314 // See if we are selecting two values based on a comparison of the two values.
8315 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8316 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8317 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008318 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8319 // This is not safe in general for floating point:
8320 // consider X== -0, Y== +0.
8321 // It becomes safe if either operand is a nonzero constant.
8322 ConstantFP *CFPt, *CFPf;
8323 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8324 !CFPt->getValueAPF().isZero()) ||
8325 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8326 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008327 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008328 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008329 // Transform (X != Y) ? X : Y -> X
8330 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8331 return ReplaceInstUsesWith(SI, TrueVal);
8332 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8333
8334 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8335 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008336 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8337 // This is not safe in general for floating point:
8338 // consider X== -0, Y== +0.
8339 // It becomes safe if either operand is a nonzero constant.
8340 ConstantFP *CFPt, *CFPf;
8341 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8342 !CFPt->getValueAPF().isZero()) ||
8343 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8344 !CFPf->getValueAPF().isZero()))
8345 return ReplaceInstUsesWith(SI, FalseVal);
8346 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008347 // Transform (X != Y) ? Y : X -> Y
8348 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8349 return ReplaceInstUsesWith(SI, TrueVal);
8350 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8351 }
8352 }
8353
8354 // See if we are selecting two values based on a comparison of the two values.
8355 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8356 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8357 // Transform (X == Y) ? X : Y -> Y
8358 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8359 return ReplaceInstUsesWith(SI, FalseVal);
8360 // Transform (X != Y) ? X : Y -> X
8361 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8362 return ReplaceInstUsesWith(SI, TrueVal);
8363 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8364
8365 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8366 // Transform (X == Y) ? Y : X -> X
8367 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8368 return ReplaceInstUsesWith(SI, FalseVal);
8369 // Transform (X != Y) ? Y : X -> Y
8370 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8371 return ReplaceInstUsesWith(SI, TrueVal);
8372 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8373 }
8374 }
8375
8376 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8377 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8378 if (TI->hasOneUse() && FI->hasOneUse()) {
8379 Instruction *AddOp = 0, *SubOp = 0;
8380
8381 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8382 if (TI->getOpcode() == FI->getOpcode())
8383 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8384 return IV;
8385
8386 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8387 // even legal for FP.
8388 if (TI->getOpcode() == Instruction::Sub &&
8389 FI->getOpcode() == Instruction::Add) {
8390 AddOp = FI; SubOp = TI;
8391 } else if (FI->getOpcode() == Instruction::Sub &&
8392 TI->getOpcode() == Instruction::Add) {
8393 AddOp = TI; SubOp = FI;
8394 }
8395
8396 if (AddOp) {
8397 Value *OtherAddOp = 0;
8398 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8399 OtherAddOp = AddOp->getOperand(1);
8400 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8401 OtherAddOp = AddOp->getOperand(0);
8402 }
8403
8404 if (OtherAddOp) {
8405 // So at this point we know we have (Y -> OtherAddOp):
8406 // select C, (add X, Y), (sub X, Z)
8407 Value *NegVal; // Compute -Z
8408 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8409 NegVal = ConstantExpr::getNeg(C);
8410 } else {
8411 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008412 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 }
8414
8415 Value *NewTrueOp = OtherAddOp;
8416 Value *NewFalseOp = NegVal;
8417 if (AddOp != TI)
8418 std::swap(NewTrueOp, NewFalseOp);
8419 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008420 SelectInst::Create(CondVal, NewTrueOp,
8421 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008422
8423 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008424 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008425 }
8426 }
8427 }
8428
8429 // See if we can fold the select into one of our operands.
8430 if (SI.getType()->isInteger()) {
8431 // See the comment above GetSelectFoldableOperands for a description of the
8432 // transformation we are doing here.
8433 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8434 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8435 !isa<Constant>(FalseVal))
8436 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8437 unsigned OpToFold = 0;
8438 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8439 OpToFold = 1;
8440 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8441 OpToFold = 2;
8442 }
8443
8444 if (OpToFold) {
8445 Constant *C = GetSelectFoldableConstant(TVI);
8446 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008447 SelectInst::Create(SI.getCondition(),
8448 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008449 InsertNewInstBefore(NewSel, SI);
8450 NewSel->takeName(TVI);
8451 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008452 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008453 else {
8454 assert(0 && "Unknown instruction!!");
8455 }
8456 }
8457 }
8458
8459 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8460 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8461 !isa<Constant>(TrueVal))
8462 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8463 unsigned OpToFold = 0;
8464 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8465 OpToFold = 1;
8466 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8467 OpToFold = 2;
8468 }
8469
8470 if (OpToFold) {
8471 Constant *C = GetSelectFoldableConstant(FVI);
8472 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008473 SelectInst::Create(SI.getCondition(), C,
8474 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008475 InsertNewInstBefore(NewSel, SI);
8476 NewSel->takeName(FVI);
8477 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008478 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008479 else
8480 assert(0 && "Unknown instruction!!");
8481 }
8482 }
8483 }
8484
8485 if (BinaryOperator::isNot(CondVal)) {
8486 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8487 SI.setOperand(1, FalseVal);
8488 SI.setOperand(2, TrueVal);
8489 return &SI;
8490 }
8491
8492 return 0;
8493}
8494
Dan Gohman2d648bb2008-04-10 18:43:06 +00008495/// EnforceKnownAlignment - If the specified pointer points to an object that
8496/// we control, modify the object's alignment to PrefAlign. This isn't
8497/// often possible though. If alignment is important, a more reliable approach
8498/// is to simply align all global variables and allocation instructions to
8499/// their preferred alignment from the beginning.
8500///
8501static unsigned EnforceKnownAlignment(Value *V,
8502 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008503
Dan Gohman2d648bb2008-04-10 18:43:06 +00008504 User *U = dyn_cast<User>(V);
8505 if (!U) return Align;
8506
8507 switch (getOpcode(U)) {
8508 default: break;
8509 case Instruction::BitCast:
8510 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8511 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008512 // If all indexes are zero, it is just the alignment of the base pointer.
8513 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00008514 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00008515 if (!isa<Constant>(*i) ||
8516 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008517 AllZeroOperands = false;
8518 break;
8519 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008520
8521 if (AllZeroOperands) {
8522 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008523 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008524 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008525 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008526 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008527 }
8528
8529 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8530 // If there is a large requested alignment and we can, bump up the alignment
8531 // of the global.
8532 if (!GV->isDeclaration()) {
8533 GV->setAlignment(PrefAlign);
8534 Align = PrefAlign;
8535 }
8536 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8537 // If there is a requested alignment and if this is an alloca, round up. We
8538 // don't do this for malloc, because some systems can't respect the request.
8539 if (isa<AllocaInst>(AI)) {
8540 AI->setAlignment(PrefAlign);
8541 Align = PrefAlign;
8542 }
8543 }
8544
8545 return Align;
8546}
8547
8548/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8549/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8550/// and it is more than the alignment of the ultimate object, see if we can
8551/// increase the alignment of the ultimate object, making this check succeed.
8552unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8553 unsigned PrefAlign) {
8554 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8555 sizeof(PrefAlign) * CHAR_BIT;
8556 APInt Mask = APInt::getAllOnesValue(BitWidth);
8557 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8558 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8559 unsigned TrailZ = KnownZero.countTrailingOnes();
8560 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8561
8562 if (PrefAlign > Align)
8563 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8564
8565 // We don't need to make any adjustment.
8566 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008567}
8568
Chris Lattner00ae5132008-01-13 23:50:23 +00008569Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008570 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8571 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008572 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8573 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8574
8575 if (CopyAlign < MinAlign) {
8576 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8577 return MI;
8578 }
8579
8580 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8581 // load/store.
8582 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8583 if (MemOpLength == 0) return 0;
8584
Chris Lattnerc669fb62008-01-14 00:28:35 +00008585 // Source and destination pointer types are always "i8*" for intrinsic. See
8586 // if the size is something we can handle with a single primitive load/store.
8587 // A single load+store correctly handles overlapping memory in the memmove
8588 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008589 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008590 if (Size == 0) return MI; // Delete this mem transfer.
8591
8592 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008593 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008594
Chris Lattnerc669fb62008-01-14 00:28:35 +00008595 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008596 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008597
8598 // Memcpy forces the use of i8* for the source and destination. That means
8599 // that if you're using memcpy to move one double around, you'll get a cast
8600 // from double* to i8*. We'd much rather use a double load+store rather than
8601 // an i64 load+store, here because this improves the odds that the source or
8602 // dest address will be promotable. See if we can find a better type than the
8603 // integer datatype.
8604 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8605 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8606 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8607 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8608 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008609 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00008610 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8611 if (STy->getNumElements() == 1)
8612 SrcETy = STy->getElementType(0);
8613 else
8614 break;
8615 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8616 if (ATy->getNumElements() == 1)
8617 SrcETy = ATy->getElementType();
8618 else
8619 break;
8620 } else
8621 break;
8622 }
8623
Dan Gohmanb8e94f62008-05-23 01:52:21 +00008624 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00008625 NewPtrTy = PointerType::getUnqual(SrcETy);
8626 }
8627 }
8628
8629
Chris Lattner00ae5132008-01-13 23:50:23 +00008630 // If the memcpy/memmove provides better alignment info than we can
8631 // infer, use it.
8632 SrcAlign = std::max(SrcAlign, CopyAlign);
8633 DstAlign = std::max(DstAlign, CopyAlign);
8634
8635 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8636 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008637 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8638 InsertNewInstBefore(L, *MI);
8639 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8640
8641 // Set the size of the copy to 0, it will be deleted on the next iteration.
8642 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8643 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008644}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008645
Chris Lattner5af8a912008-04-30 06:39:11 +00008646Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8647 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8648 if (MI->getAlignment()->getZExtValue() < Alignment) {
8649 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8650 return MI;
8651 }
8652
8653 // Extract the length and alignment and fill if they are constant.
8654 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8655 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8656 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8657 return 0;
8658 uint64_t Len = LenC->getZExtValue();
8659 Alignment = MI->getAlignment()->getZExtValue();
8660
8661 // If the length is zero, this is a no-op
8662 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8663
8664 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8665 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8666 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8667
8668 Value *Dest = MI->getDest();
8669 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8670
8671 // Alignment 0 is identity for alignment 1 for memset, but not store.
8672 if (Alignment == 0) Alignment = 1;
8673
8674 // Extract the fill value and store.
8675 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8676 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8677 Alignment), *MI);
8678
8679 // Set the size of the copy to 0, it will be deleted on the next iteration.
8680 MI->setLength(Constant::getNullValue(LenC->getType()));
8681 return MI;
8682 }
8683
8684 return 0;
8685}
8686
8687
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008688/// visitCallInst - CallInst simplification. This mostly only handles folding
8689/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8690/// the heavy lifting.
8691///
8692Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8693 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8694 if (!II) return visitCallSite(&CI);
8695
8696 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8697 // visitCallSite.
8698 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8699 bool Changed = false;
8700
8701 // memmove/cpy/set of zero bytes is a noop.
8702 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8703 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8704
8705 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8706 if (CI->getZExtValue() == 1) {
8707 // Replace the instruction with just byte operations. We would
8708 // transform other cases to loads/stores, but we don't know if
8709 // alignment is sufficient.
8710 }
8711 }
8712
8713 // If we have a memmove and the source operation is a constant global,
8714 // then the source and dest pointers can't alias, so we can change this
8715 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008716 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008717 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8718 if (GVSrc->isConstant()) {
8719 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008720 Intrinsic::ID MemCpyID;
8721 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8722 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008723 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008724 MemCpyID = Intrinsic::memcpy_i64;
8725 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008726 Changed = true;
8727 }
Chris Lattner59b27d92008-05-28 05:30:41 +00008728
8729 // memmove(x,x,size) -> noop.
8730 if (MMI->getSource() == MMI->getDest())
8731 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008732 }
8733
8734 // If we can determine a pointer alignment that is bigger than currently
8735 // set, update the alignment.
8736 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008737 if (Instruction *I = SimplifyMemTransfer(MI))
8738 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008739 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8740 if (Instruction *I = SimplifyMemSet(MSI))
8741 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008742 }
8743
8744 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00008745 }
8746
8747 switch (II->getIntrinsicID()) {
8748 default: break;
8749 case Intrinsic::bswap:
8750 // bswap(bswap(x)) -> x
8751 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8752 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8753 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8754 break;
8755 case Intrinsic::ppc_altivec_lvx:
8756 case Intrinsic::ppc_altivec_lvxl:
8757 case Intrinsic::x86_sse_loadu_ps:
8758 case Intrinsic::x86_sse2_loadu_pd:
8759 case Intrinsic::x86_sse2_loadu_dq:
8760 // Turn PPC lvx -> load if the pointer is known aligned.
8761 // Turn X86 loadups -> load if the pointer is known aligned.
8762 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8763 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8764 PointerType::getUnqual(II->getType()),
8765 CI);
8766 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008767 }
Chris Lattner989ba312008-06-18 04:33:20 +00008768 break;
8769 case Intrinsic::ppc_altivec_stvx:
8770 case Intrinsic::ppc_altivec_stvxl:
8771 // Turn stvx -> store if the pointer is known aligned.
8772 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8773 const Type *OpPtrTy =
8774 PointerType::getUnqual(II->getOperand(1)->getType());
8775 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8776 return new StoreInst(II->getOperand(1), Ptr);
8777 }
8778 break;
8779 case Intrinsic::x86_sse_storeu_ps:
8780 case Intrinsic::x86_sse2_storeu_pd:
8781 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00008782 // Turn X86 storeu -> store if the pointer is known aligned.
8783 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8784 const Type *OpPtrTy =
8785 PointerType::getUnqual(II->getOperand(2)->getType());
8786 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8787 return new StoreInst(II->getOperand(2), Ptr);
8788 }
8789 break;
8790
8791 case Intrinsic::x86_sse_cvttss2si: {
8792 // These intrinsics only demands the 0th element of its input vector. If
8793 // we can simplify the input based on that, do so now.
8794 uint64_t UndefElts;
8795 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8796 UndefElts)) {
8797 II->setOperand(1, V);
8798 return II;
8799 }
8800 break;
8801 }
8802
8803 case Intrinsic::ppc_altivec_vperm:
8804 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8805 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8806 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008807
Chris Lattner989ba312008-06-18 04:33:20 +00008808 // Check that all of the elements are integer constants or undefs.
8809 bool AllEltsOk = true;
8810 for (unsigned i = 0; i != 16; ++i) {
8811 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8812 !isa<UndefValue>(Mask->getOperand(i))) {
8813 AllEltsOk = false;
8814 break;
8815 }
8816 }
8817
8818 if (AllEltsOk) {
8819 // Cast the input vectors to byte vectors.
8820 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8821 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8822 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008823
Chris Lattner989ba312008-06-18 04:33:20 +00008824 // Only extract each element once.
8825 Value *ExtractedElts[32];
8826 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8827
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008828 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00008829 if (isa<UndefValue>(Mask->getOperand(i)))
8830 continue;
8831 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8832 Idx &= 31; // Match the hardware behavior.
8833
8834 if (ExtractedElts[Idx] == 0) {
8835 Instruction *Elt =
8836 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8837 InsertNewInstBefore(Elt, CI);
8838 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008839 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008840
Chris Lattner989ba312008-06-18 04:33:20 +00008841 // Insert this value into the result vector.
8842 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8843 i, "tmp");
8844 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008845 }
Chris Lattner989ba312008-06-18 04:33:20 +00008846 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008847 }
Chris Lattner989ba312008-06-18 04:33:20 +00008848 }
8849 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008850
Chris Lattner989ba312008-06-18 04:33:20 +00008851 case Intrinsic::stackrestore: {
8852 // If the save is right next to the restore, remove the restore. This can
8853 // happen when variable allocas are DCE'd.
8854 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8855 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8856 BasicBlock::iterator BI = SS;
8857 if (&*++BI == II)
8858 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008859 }
Chris Lattner989ba312008-06-18 04:33:20 +00008860 }
8861
8862 // Scan down this block to see if there is another stack restore in the
8863 // same block without an intervening call/alloca.
8864 BasicBlock::iterator BI = II;
8865 TerminatorInst *TI = II->getParent()->getTerminator();
8866 bool CannotRemove = false;
8867 for (++BI; &*BI != TI; ++BI) {
8868 if (isa<AllocaInst>(BI)) {
8869 CannotRemove = true;
8870 break;
8871 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00008872 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8873 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8874 // If there is a stackrestore below this one, remove this one.
8875 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8876 return EraseInstFromFunction(CI);
8877 // Otherwise, ignore the intrinsic.
8878 } else {
8879 // If we found a non-intrinsic call, we can't remove the stack
8880 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00008881 CannotRemove = true;
8882 break;
8883 }
Chris Lattner989ba312008-06-18 04:33:20 +00008884 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008885 }
Chris Lattner989ba312008-06-18 04:33:20 +00008886
8887 // If the stack restore is in a return/unwind block and if there are no
8888 // allocas or calls between the restore and the return, nuke the restore.
8889 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8890 return EraseInstFromFunction(CI);
8891 break;
8892 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008893 }
8894
8895 return visitCallSite(II);
8896}
8897
8898// InvokeInst simplification
8899//
8900Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8901 return visitCallSite(&II);
8902}
8903
Dale Johannesen96021832008-04-25 21:16:07 +00008904/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8905/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008906static bool isSafeToEliminateVarargsCast(const CallSite CS,
8907 const CastInst * const CI,
8908 const TargetData * const TD,
8909 const int ix) {
8910 if (!CI->isLosslessCast())
8911 return false;
8912
8913 // The size of ByVal arguments is derived from the type, so we
8914 // can't change to a type with a different size. If the size were
8915 // passed explicitly we could avoid this check.
8916 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8917 return true;
8918
8919 const Type* SrcTy =
8920 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8921 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8922 if (!SrcTy->isSized() || !DstTy->isSized())
8923 return false;
8924 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8925 return false;
8926 return true;
8927}
8928
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008929// visitCallSite - Improvements for call and invoke instructions.
8930//
8931Instruction *InstCombiner::visitCallSite(CallSite CS) {
8932 bool Changed = false;
8933
8934 // If the callee is a constexpr cast of a function, attempt to move the cast
8935 // to the arguments of the call/invoke.
8936 if (transformConstExprCastCall(CS)) return 0;
8937
8938 Value *Callee = CS.getCalledValue();
8939
8940 if (Function *CalleeF = dyn_cast<Function>(Callee))
8941 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8942 Instruction *OldCall = CS.getInstruction();
8943 // If the call and callee calling conventions don't match, this call must
8944 // be unreachable, as the call is undefined.
8945 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008946 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8947 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008948 if (!OldCall->use_empty())
8949 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8950 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8951 return EraseInstFromFunction(*OldCall);
8952 return 0;
8953 }
8954
8955 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8956 // This instruction is not reachable, just remove it. We insert a store to
8957 // undef so that we know that this code is not reachable, despite the fact
8958 // that we can't modify the CFG here.
8959 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008960 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008961 CS.getInstruction());
8962
8963 if (!CS.getInstruction()->use_empty())
8964 CS.getInstruction()->
8965 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8966
8967 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8968 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008969 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8970 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008971 }
8972 return EraseInstFromFunction(*CS.getInstruction());
8973 }
8974
Duncan Sands74833f22007-09-17 10:26:40 +00008975 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8976 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8977 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8978 return transformCallThroughTrampoline(CS);
8979
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008980 const PointerType *PTy = cast<PointerType>(Callee->getType());
8981 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8982 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00008983 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008984 // See if we can optimize any arguments passed through the varargs area of
8985 // the call.
8986 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00008987 E = CS.arg_end(); I != E; ++I, ++ix) {
8988 CastInst *CI = dyn_cast<CastInst>(*I);
8989 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8990 *I = CI->getOperand(0);
8991 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008992 }
Dale Johannesen35615462008-04-23 18:34:37 +00008993 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008994 }
8995
Duncan Sands2937e352007-12-19 21:13:37 +00008996 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008997 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008998 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008999 Changed = true;
9000 }
9001
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009002 return Changed ? CS.getInstruction() : 0;
9003}
9004
9005// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9006// attempt to move the cast to the arguments of the call/invoke.
9007//
9008bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9009 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9010 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9011 if (CE->getOpcode() != Instruction::BitCast ||
9012 !isa<Function>(CE->getOperand(0)))
9013 return false;
9014 Function *Callee = cast<Function>(CE->getOperand(0));
9015 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009016 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009017
9018 // Okay, this is a cast from a function to a different type. Unless doing so
9019 // would cause a type conversion of one of our arguments, change this call to
9020 // be a direct call with arguments casted to the appropriate types.
9021 //
9022 const FunctionType *FT = Callee->getFunctionType();
9023 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00009024 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009025
Duncan Sands7901ce12008-06-01 07:38:42 +00009026 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00009027 return false; // TODO: Handle multiple return values.
9028
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009029 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00009030 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009031 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00009032 // Conversion is ok if changing from one pointer type to another or from
9033 // a pointer to an integer of the same size.
9034 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +00009035 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009036 return false; // Cannot transform this return value.
9037
Duncan Sands5c489582008-01-06 10:12:28 +00009038 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009039 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00009040 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009041 return false; // Cannot transform this return value.
9042
Chris Lattner1c8733e2008-03-12 17:45:29 +00009043 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9044 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands7901ce12008-06-01 07:38:42 +00009045 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009046 return false; // Attribute not compatible with transformed value.
9047 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009048
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009049 // If the callsite is an invoke instruction, and the return value is used by
9050 // a PHI node in a successor, we cannot change the return type of the call
9051 // because there is no place to put the cast instruction (without breaking
9052 // the critical edge). Bail out in this case.
9053 if (!Caller->use_empty())
9054 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9055 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9056 UI != E; ++UI)
9057 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9058 if (PN->getParent() == II->getNormalDest() ||
9059 PN->getParent() == II->getUnwindDest())
9060 return false;
9061 }
9062
9063 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9064 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9065
9066 CallSite::arg_iterator AI = CS.arg_begin();
9067 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9068 const Type *ParamTy = FT->getParamType(i);
9069 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009070
9071 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009072 return false; // Cannot transform this parameter value.
9073
Chris Lattner1c8733e2008-03-12 17:45:29 +00009074 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9075 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009076
Duncan Sands7901ce12008-06-01 07:38:42 +00009077 // Converting from one pointer type to another or between a pointer and an
9078 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009079 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00009080 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9081 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009082 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009083 }
9084
9085 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9086 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009087 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009088
Chris Lattner1c8733e2008-03-12 17:45:29 +00009089 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9090 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009091 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009092 // won't be dropping them. Check that these extra arguments have attributes
9093 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009094 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9095 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009096 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009097 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00009098 if (PAttrs & ParamAttr::VarArgsIncompatible)
9099 return false;
9100 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009101
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009102 // Okay, we decided that this is a safe thing to do: go ahead and start
9103 // inserting cast instructions as necessary...
9104 std::vector<Value*> Args;
9105 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009106 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009107 attrVec.reserve(NumCommonArgs);
9108
9109 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009110 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00009111
9112 // If the return value is not being used, the type may not be compatible
9113 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands7901ce12008-06-01 07:38:42 +00009114 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00009115
9116 // Add the new return attributes.
9117 if (RAttrs)
9118 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009119
9120 AI = CS.arg_begin();
9121 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9122 const Type *ParamTy = FT->getParamType(i);
9123 if ((*AI)->getType() == ParamTy) {
9124 Args.push_back(*AI);
9125 } else {
9126 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9127 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009128 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009129 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9130 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009131
9132 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009133 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00009134 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009135 }
9136
9137 // If the function takes more arguments than the call was taking, add them
9138 // now...
9139 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9140 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9141
9142 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009143 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009144 if (!FT->isVarArg()) {
9145 cerr << "WARNING: While resolving call to function '"
9146 << Callee->getName() << "' arguments were dropped!\n";
9147 } else {
9148 // Add all of the arguments in their promoted form to the arg list...
9149 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9150 const Type *PTy = getPromotedType((*AI)->getType());
9151 if (PTy != (*AI)->getType()) {
9152 // Must promote to pass through va_arg area!
9153 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9154 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009155 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009156 InsertNewInstBefore(Cast, *Caller);
9157 Args.push_back(Cast);
9158 } else {
9159 Args.push_back(*AI);
9160 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009161
Duncan Sands4ced1f82008-01-13 08:02:44 +00009162 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009163 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00009164 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9165 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009166 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009167 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009168
Duncan Sands7901ce12008-06-01 07:38:42 +00009169 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009170 Caller->setName(""); // Void type should not have a name.
9171
Chris Lattner1c8733e2008-03-12 17:45:29 +00009172 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009173
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009174 Instruction *NC;
9175 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009176 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009177 Args.begin(), Args.end(),
9178 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009179 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009180 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009181 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009182 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9183 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009184 CallInst *CI = cast<CallInst>(Caller);
9185 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009186 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009187 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009188 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009189 }
9190
9191 // Insert a cast of the return type as necessary.
9192 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009193 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009194 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009195 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009196 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009197 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009198
9199 // If this is an invoke instruction, we should insert it after the first
9200 // non-phi, instruction in the normal successor block.
9201 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00009202 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009203 InsertNewInstBefore(NC, *I);
9204 } else {
9205 // Otherwise, it's a call, just insert cast right after the call instr
9206 InsertNewInstBefore(NC, *Caller);
9207 }
9208 AddUsersToWorkList(*Caller);
9209 } else {
9210 NV = UndefValue::get(Caller->getType());
9211 }
9212 }
9213
9214 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9215 Caller->replaceAllUsesWith(NV);
9216 Caller->eraseFromParent();
9217 RemoveFromWorkList(Caller);
9218 return true;
9219}
9220
Duncan Sands74833f22007-09-17 10:26:40 +00009221// transformCallThroughTrampoline - Turn a call to a function created by the
9222// init_trampoline intrinsic into a direct call to the underlying function.
9223//
9224Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9225 Value *Callee = CS.getCalledValue();
9226 const PointerType *PTy = cast<PointerType>(Callee->getType());
9227 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009228 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009229
9230 // If the call already has the 'nest' attribute somewhere then give up -
9231 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009232 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009233 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009234
9235 IntrinsicInst *Tramp =
9236 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9237
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009238 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009239 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9240 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9241
Chris Lattner1c8733e2008-03-12 17:45:29 +00009242 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9243 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009244 unsigned NestIdx = 1;
9245 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009246 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009247
9248 // Look for a parameter marked with the 'nest' attribute.
9249 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9250 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009251 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009252 // Record the parameter type and any other attributes.
9253 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009254 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009255 break;
9256 }
9257
9258 if (NestTy) {
9259 Instruction *Caller = CS.getInstruction();
9260 std::vector<Value*> NewArgs;
9261 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9262
Chris Lattner1c8733e2008-03-12 17:45:29 +00009263 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9264 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009265
Duncan Sands74833f22007-09-17 10:26:40 +00009266 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009267 // mean appending it. Likewise for attributes.
9268
9269 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009270 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9271 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009272
Duncan Sands74833f22007-09-17 10:26:40 +00009273 {
9274 unsigned Idx = 1;
9275 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9276 do {
9277 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009278 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009279 Value *NestVal = Tramp->getOperand(3);
9280 if (NestVal->getType() != NestTy)
9281 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9282 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009283 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009284 }
9285
9286 if (I == E)
9287 break;
9288
Duncan Sands48b81112008-01-14 19:52:09 +00009289 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009290 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009291 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009292 NewAttrs.push_back
9293 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009294
9295 ++Idx, ++I;
9296 } while (1);
9297 }
9298
9299 // The trampoline may have been bitcast to a bogus type (FTy).
9300 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009301 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009302
Duncan Sands74833f22007-09-17 10:26:40 +00009303 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009304 NewTypes.reserve(FTy->getNumParams()+1);
9305
Duncan Sands74833f22007-09-17 10:26:40 +00009306 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009307 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009308 {
9309 unsigned Idx = 1;
9310 FunctionType::param_iterator I = FTy->param_begin(),
9311 E = FTy->param_end();
9312
9313 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009314 if (Idx == NestIdx)
9315 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009316 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009317
9318 if (I == E)
9319 break;
9320
Duncan Sands48b81112008-01-14 19:52:09 +00009321 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009322 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009323
9324 ++Idx, ++I;
9325 } while (1);
9326 }
9327
9328 // Replace the trampoline call with a direct call. Let the generic
9329 // code sort out any function type mismatches.
9330 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009331 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009332 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9333 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009334 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009335
9336 Instruction *NewCaller;
9337 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009338 NewCaller = InvokeInst::Create(NewCallee,
9339 II->getNormalDest(), II->getUnwindDest(),
9340 NewArgs.begin(), NewArgs.end(),
9341 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009342 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009343 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009344 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009345 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9346 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009347 if (cast<CallInst>(Caller)->isTailCall())
9348 cast<CallInst>(NewCaller)->setTailCall();
9349 cast<CallInst>(NewCaller)->
9350 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009351 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009352 }
9353 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9354 Caller->replaceAllUsesWith(NewCaller);
9355 Caller->eraseFromParent();
9356 RemoveFromWorkList(Caller);
9357 return 0;
9358 }
9359 }
9360
9361 // Replace the trampoline call with a direct call. Since there is no 'nest'
9362 // parameter, there is no need to adjust the argument list. Let the generic
9363 // code sort out any function type mismatches.
9364 Constant *NewCallee =
9365 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9366 CS.setCalledFunction(NewCallee);
9367 return CS.getInstruction();
9368}
9369
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009370/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9371/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9372/// and a single binop.
9373Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9374 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9375 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9376 isa<CmpInst>(FirstInst));
9377 unsigned Opc = FirstInst->getOpcode();
9378 Value *LHSVal = FirstInst->getOperand(0);
9379 Value *RHSVal = FirstInst->getOperand(1);
9380
9381 const Type *LHSType = LHSVal->getType();
9382 const Type *RHSType = RHSVal->getType();
9383
9384 // Scan to see if all operands are the same opcode, all have one use, and all
9385 // kill their operands (i.e. the operands have one use).
9386 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9387 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9388 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9389 // Verify type of the LHS matches so we don't fold cmp's of different
9390 // types or GEP's with different index types.
9391 I->getOperand(0)->getType() != LHSType ||
9392 I->getOperand(1)->getType() != RHSType)
9393 return 0;
9394
9395 // If they are CmpInst instructions, check their predicates
9396 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9397 if (cast<CmpInst>(I)->getPredicate() !=
9398 cast<CmpInst>(FirstInst)->getPredicate())
9399 return 0;
9400
9401 // Keep track of which operand needs a phi node.
9402 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9403 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9404 }
9405
9406 // Otherwise, this is safe to transform, determine if it is profitable.
9407
9408 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9409 // Indexes are often folded into load/store instructions, so we don't want to
9410 // hide them behind a phi.
9411 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9412 return 0;
9413
9414 Value *InLHS = FirstInst->getOperand(0);
9415 Value *InRHS = FirstInst->getOperand(1);
9416 PHINode *NewLHS = 0, *NewRHS = 0;
9417 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009418 NewLHS = PHINode::Create(LHSType,
9419 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009420 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9421 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9422 InsertNewInstBefore(NewLHS, PN);
9423 LHSVal = NewLHS;
9424 }
9425
9426 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009427 NewRHS = PHINode::Create(RHSType,
9428 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009429 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9430 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9431 InsertNewInstBefore(NewRHS, PN);
9432 RHSVal = NewRHS;
9433 }
9434
9435 // Add all operands to the new PHIs.
9436 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9437 if (NewLHS) {
9438 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9439 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9440 }
9441 if (NewRHS) {
9442 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9443 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9444 }
9445 }
9446
9447 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009448 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009450 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009451 RHSVal);
9452 else {
9453 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009454 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009455 }
9456}
9457
9458/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9459/// of the block that defines it. This means that it must be obvious the value
9460/// of the load is not changed from the point of the load to the end of the
9461/// block it is in.
9462///
9463/// Finally, it is safe, but not profitable, to sink a load targetting a
9464/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9465/// to a register.
9466static bool isSafeToSinkLoad(LoadInst *L) {
9467 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9468
9469 for (++BBI; BBI != E; ++BBI)
9470 if (BBI->mayWriteToMemory())
9471 return false;
9472
9473 // Check for non-address taken alloca. If not address-taken already, it isn't
9474 // profitable to do this xform.
9475 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9476 bool isAddressTaken = false;
9477 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9478 UI != E; ++UI) {
9479 if (isa<LoadInst>(UI)) continue;
9480 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9481 // If storing TO the alloca, then the address isn't taken.
9482 if (SI->getOperand(1) == AI) continue;
9483 }
9484 isAddressTaken = true;
9485 break;
9486 }
9487
9488 if (!isAddressTaken)
9489 return false;
9490 }
9491
9492 return true;
9493}
9494
9495
9496// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9497// operator and they all are only used by the PHI, PHI together their
9498// inputs, and do the operation once, to the result of the PHI.
9499Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9500 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9501
9502 // Scan the instruction, looking for input operations that can be folded away.
9503 // If all input operands to the phi are the same instruction (e.g. a cast from
9504 // the same type or "+42") we can pull the operation through the PHI, reducing
9505 // code size and simplifying code.
9506 Constant *ConstantOp = 0;
9507 const Type *CastSrcTy = 0;
9508 bool isVolatile = false;
9509 if (isa<CastInst>(FirstInst)) {
9510 CastSrcTy = FirstInst->getOperand(0)->getType();
9511 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9512 // Can fold binop, compare or shift here if the RHS is a constant,
9513 // otherwise call FoldPHIArgBinOpIntoPHI.
9514 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9515 if (ConstantOp == 0)
9516 return FoldPHIArgBinOpIntoPHI(PN);
9517 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9518 isVolatile = LI->isVolatile();
9519 // We can't sink the load if the loaded value could be modified between the
9520 // load and the PHI.
9521 if (LI->getParent() != PN.getIncomingBlock(0) ||
9522 !isSafeToSinkLoad(LI))
9523 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +00009524
9525 // If the PHI is of volatile loads and the load block has multiple
9526 // successors, sinking it would remove a load of the volatile value from
9527 // the path through the other successor.
9528 if (isVolatile &&
9529 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9530 return 0;
9531
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009532 } else if (isa<GetElementPtrInst>(FirstInst)) {
9533 if (FirstInst->getNumOperands() == 2)
9534 return FoldPHIArgBinOpIntoPHI(PN);
9535 // Can't handle general GEPs yet.
9536 return 0;
9537 } else {
9538 return 0; // Cannot fold this operation.
9539 }
9540
9541 // Check to see if all arguments are the same operation.
9542 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9543 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9544 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9545 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9546 return 0;
9547 if (CastSrcTy) {
9548 if (I->getOperand(0)->getType() != CastSrcTy)
9549 return 0; // Cast operation must match.
9550 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9551 // We can't sink the load if the loaded value could be modified between
9552 // the load and the PHI.
9553 if (LI->isVolatile() != isVolatile ||
9554 LI->getParent() != PN.getIncomingBlock(i) ||
9555 !isSafeToSinkLoad(LI))
9556 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009557
Chris Lattner2d9fdd82008-07-08 17:18:32 +00009558 // If the PHI is of volatile loads and the load block has multiple
9559 // successors, sinking it would remove a load of the volatile value from
9560 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +00009561 if (isVolatile &&
9562 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9563 return 0;
9564
9565
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009566 } else if (I->getOperand(1) != ConstantOp) {
9567 return 0;
9568 }
9569 }
9570
9571 // Okay, they are all the same operation. Create a new PHI node of the
9572 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009573 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9574 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009575 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9576
9577 Value *InVal = FirstInst->getOperand(0);
9578 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9579
9580 // Add all operands to the new PHI.
9581 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9582 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9583 if (NewInVal != InVal)
9584 InVal = 0;
9585 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9586 }
9587
9588 Value *PhiVal;
9589 if (InVal) {
9590 // The new PHI unions all of the same values together. This is really
9591 // common, so we handle it intelligently here for compile-time speed.
9592 PhiVal = InVal;
9593 delete NewPN;
9594 } else {
9595 InsertNewInstBefore(NewPN, PN);
9596 PhiVal = NewPN;
9597 }
9598
9599 // Insert and return the new operation.
9600 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009601 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009602 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009603 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009604 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009605 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009606 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009607 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9608
9609 // If this was a volatile load that we are merging, make sure to loop through
9610 // and mark all the input loads as non-volatile. If we don't do this, we will
9611 // insert a new volatile load and the old ones will not be deletable.
9612 if (isVolatile)
9613 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9614 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9615
9616 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009617}
9618
9619/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9620/// that is dead.
9621static bool DeadPHICycle(PHINode *PN,
9622 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9623 if (PN->use_empty()) return true;
9624 if (!PN->hasOneUse()) return false;
9625
9626 // Remember this node, and if we find the cycle, return.
9627 if (!PotentiallyDeadPHIs.insert(PN))
9628 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009629
9630 // Don't scan crazily complex things.
9631 if (PotentiallyDeadPHIs.size() == 16)
9632 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009633
9634 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9635 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9636
9637 return false;
9638}
9639
Chris Lattner27b695d2007-11-06 21:52:06 +00009640/// PHIsEqualValue - Return true if this phi node is always equal to
9641/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9642/// z = some value; x = phi (y, z); y = phi (x, z)
9643static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9644 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9645 // See if we already saw this PHI node.
9646 if (!ValueEqualPHIs.insert(PN))
9647 return true;
9648
9649 // Don't scan crazily complex things.
9650 if (ValueEqualPHIs.size() == 16)
9651 return false;
9652
9653 // Scan the operands to see if they are either phi nodes or are equal to
9654 // the value.
9655 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9656 Value *Op = PN->getIncomingValue(i);
9657 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9658 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9659 return false;
9660 } else if (Op != NonPhiInVal)
9661 return false;
9662 }
9663
9664 return true;
9665}
9666
9667
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009668// PHINode simplification
9669//
9670Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9671 // If LCSSA is around, don't mess with Phi nodes
9672 if (MustPreserveLCSSA) return 0;
9673
9674 if (Value *V = PN.hasConstantValue())
9675 return ReplaceInstUsesWith(PN, V);
9676
9677 // If all PHI operands are the same operation, pull them through the PHI,
9678 // reducing code size.
9679 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9680 PN.getIncomingValue(0)->hasOneUse())
9681 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9682 return Result;
9683
9684 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9685 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9686 // PHI)... break the cycle.
9687 if (PN.hasOneUse()) {
9688 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9689 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9690 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9691 PotentiallyDeadPHIs.insert(&PN);
9692 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9693 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9694 }
9695
9696 // If this phi has a single use, and if that use just computes a value for
9697 // the next iteration of a loop, delete the phi. This occurs with unused
9698 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9699 // common case here is good because the only other things that catch this
9700 // are induction variable analysis (sometimes) and ADCE, which is only run
9701 // late.
9702 if (PHIUser->hasOneUse() &&
9703 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9704 PHIUser->use_back() == &PN) {
9705 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9706 }
9707 }
9708
Chris Lattner27b695d2007-11-06 21:52:06 +00009709 // We sometimes end up with phi cycles that non-obviously end up being the
9710 // same value, for example:
9711 // z = some value; x = phi (y, z); y = phi (x, z)
9712 // where the phi nodes don't necessarily need to be in the same block. Do a
9713 // quick check to see if the PHI node only contains a single non-phi value, if
9714 // so, scan to see if the phi cycle is actually equal to that value.
9715 {
9716 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9717 // Scan for the first non-phi operand.
9718 while (InValNo != NumOperandVals &&
9719 isa<PHINode>(PN.getIncomingValue(InValNo)))
9720 ++InValNo;
9721
9722 if (InValNo != NumOperandVals) {
9723 Value *NonPhiInVal = PN.getOperand(InValNo);
9724
9725 // Scan the rest of the operands to see if there are any conflicts, if so
9726 // there is no need to recursively scan other phis.
9727 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9728 Value *OpVal = PN.getIncomingValue(InValNo);
9729 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9730 break;
9731 }
9732
9733 // If we scanned over all operands, then we have one unique value plus
9734 // phi values. Scan PHI nodes to see if they all merge in each other or
9735 // the value.
9736 if (InValNo == NumOperandVals) {
9737 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9738 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9739 return ReplaceInstUsesWith(PN, NonPhiInVal);
9740 }
9741 }
9742 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009743 return 0;
9744}
9745
9746static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9747 Instruction *InsertPoint,
9748 InstCombiner *IC) {
9749 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9750 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9751 // We must cast correctly to the pointer type. Ensure that we
9752 // sign extend the integer value if it is smaller as this is
9753 // used for address computation.
9754 Instruction::CastOps opcode =
9755 (VTySize < PtrSize ? Instruction::SExt :
9756 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9757 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9758}
9759
9760
9761Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9762 Value *PtrOp = GEP.getOperand(0);
9763 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9764 // If so, eliminate the noop.
9765 if (GEP.getNumOperands() == 1)
9766 return ReplaceInstUsesWith(GEP, PtrOp);
9767
9768 if (isa<UndefValue>(GEP.getOperand(0)))
9769 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9770
9771 bool HasZeroPointerIndex = false;
9772 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9773 HasZeroPointerIndex = C->isNullValue();
9774
9775 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9776 return ReplaceInstUsesWith(GEP, PtrOp);
9777
9778 // Eliminate unneeded casts for indices.
9779 bool MadeChange = false;
9780
9781 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009782 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9783 i != e; ++i, ++GTI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009784 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +00009785 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009786 if (CI->getOpcode() == Instruction::ZExt ||
9787 CI->getOpcode() == Instruction::SExt) {
9788 const Type *SrcTy = CI->getOperand(0)->getType();
9789 // We can eliminate a cast from i32 to i64 iff the target
9790 // is a 32-bit pointer target.
9791 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9792 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +00009793 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009794 }
9795 }
9796 }
9797 // If we are using a wider index than needed for this platform, shrink it
9798 // to what we need. If the incoming value needs a cast instruction,
9799 // insert it. This explicit cast can make subsequent optimizations more
9800 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +00009801 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009802 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009803 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +00009804 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009805 MadeChange = true;
9806 } else {
9807 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9808 GEP);
Gabor Greif17396002008-06-12 21:37:33 +00009809 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009810 MadeChange = true;
9811 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009812 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009813 }
9814 }
9815 if (MadeChange) return &GEP;
9816
9817 // If this GEP instruction doesn't move the pointer, and if the input operand
9818 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9819 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009820 if (GEP.hasAllZeroIndices()) {
9821 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9822 // If the bitcast is of an allocation, and the allocation will be
9823 // converted to match the type of the cast, don't touch this.
9824 if (isa<AllocationInst>(BCI->getOperand(0))) {
9825 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009826 if (Instruction *I = visitBitCast(*BCI)) {
9827 if (I != BCI) {
9828 I->takeName(BCI);
9829 BCI->getParent()->getInstList().insert(BCI, I);
9830 ReplaceInstUsesWith(*BCI, I);
9831 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009832 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009833 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009834 }
9835 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9836 }
9837 }
9838
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009839 // Combine Indices - If the source pointer to this getelementptr instruction
9840 // is a getelementptr instruction, combine the indices of the two
9841 // getelementptr instructions into a single instruction.
9842 //
9843 SmallVector<Value*, 8> SrcGEPOperands;
9844 if (User *Src = dyn_castGetElementPtr(PtrOp))
9845 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9846
9847 if (!SrcGEPOperands.empty()) {
9848 // Note that if our source is a gep chain itself that we wait for that
9849 // chain to be resolved before we perform this transformation. This
9850 // avoids us creating a TON of code in some cases.
9851 //
9852 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9853 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9854 return 0; // Wait until our source is folded to completion.
9855
9856 SmallVector<Value*, 8> Indices;
9857
9858 // Find out whether the last index in the source GEP is a sequential idx.
9859 bool EndsWithSequential = false;
9860 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9861 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9862 EndsWithSequential = !isa<StructType>(*I);
9863
9864 // Can we combine the two pointer arithmetics offsets?
9865 if (EndsWithSequential) {
9866 // Replace: gep (gep %P, long B), long A, ...
9867 // With: T = long A+B; gep %P, T, ...
9868 //
9869 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9870 if (SO1 == Constant::getNullValue(SO1->getType())) {
9871 Sum = GO1;
9872 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9873 Sum = SO1;
9874 } else {
9875 // If they aren't the same type, convert both to an integer of the
9876 // target's pointer size.
9877 if (SO1->getType() != GO1->getType()) {
9878 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9879 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9880 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9881 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9882 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009883 unsigned PS = TD->getPointerSizeInBits();
9884 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009885 // Convert GO1 to SO1's type.
9886 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9887
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009888 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009889 // Convert SO1 to GO1's type.
9890 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9891 } else {
9892 const Type *PT = TD->getIntPtrType();
9893 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9894 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9895 }
9896 }
9897 }
9898 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9899 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9900 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00009901 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009902 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9903 }
9904 }
9905
9906 // Recycle the GEP we already have if possible.
9907 if (SrcGEPOperands.size() == 2) {
9908 GEP.setOperand(0, SrcGEPOperands[0]);
9909 GEP.setOperand(1, Sum);
9910 return &GEP;
9911 } else {
9912 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9913 SrcGEPOperands.end()-1);
9914 Indices.push_back(Sum);
9915 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9916 }
9917 } else if (isa<Constant>(*GEP.idx_begin()) &&
9918 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9919 SrcGEPOperands.size() != 1) {
9920 // Otherwise we can do the fold if the first index of the GEP is a zero
9921 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9922 SrcGEPOperands.end());
9923 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9924 }
9925
9926 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +00009927 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9928 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009929
9930 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9931 // GEP of global variable. If all of the indices for this GEP are
9932 // constants, we can promote this to a constexpr instead of an instruction.
9933
9934 // Scan for nonconstants...
9935 SmallVector<Constant*, 8> Indices;
9936 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9937 for (; I != E && isa<Constant>(*I); ++I)
9938 Indices.push_back(cast<Constant>(*I));
9939
9940 if (I == E) { // If they are all constants...
9941 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9942 &Indices[0],Indices.size());
9943
9944 // Replace all uses of the GEP with the new constexpr...
9945 return ReplaceInstUsesWith(GEP, CE);
9946 }
9947 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9948 if (!isa<PointerType>(X->getType())) {
9949 // Not interesting. Source pointer must be a cast from pointer.
9950 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009951 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9952 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009953 //
9954 // This occurs when the program declares an array extern like "int X[];"
9955 //
9956 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9957 const PointerType *XTy = cast<PointerType>(X->getType());
9958 if (const ArrayType *XATy =
9959 dyn_cast<ArrayType>(XTy->getElementType()))
9960 if (const ArrayType *CATy =
9961 dyn_cast<ArrayType>(CPTy->getElementType()))
9962 if (CATy->getElementType() == XATy->getElementType()) {
9963 // At this point, we know that the cast source type is a pointer
9964 // to an array of the same type as the destination pointer
9965 // array. Because the array type is never stepped over (there
9966 // is a leading zero) we can fold the cast into this GEP.
9967 GEP.setOperand(0, X);
9968 return &GEP;
9969 }
9970 } else if (GEP.getNumOperands() == 2) {
9971 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009972 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9973 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009974 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9975 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9976 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009977 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9978 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009979 Value *Idx[2];
9980 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9981 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009982 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +00009983 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009984 // V and GEP are both pointer types --> BitCast
9985 return new BitCastInst(V, GEP.getType());
9986 }
9987
9988 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009989 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009990 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009991 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009992
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009993 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009994 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009995 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009996
9997 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9998 // allow either a mul, shift, or constant here.
9999 Value *NewIdx = 0;
10000 ConstantInt *Scale = 0;
10001 if (ArrayEltSize == 1) {
10002 NewIdx = GEP.getOperand(1);
10003 Scale = ConstantInt::get(NewIdx->getType(), 1);
10004 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10005 NewIdx = ConstantInt::get(CI->getType(), 1);
10006 Scale = CI;
10007 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10008 if (Inst->getOpcode() == Instruction::Shl &&
10009 isa<ConstantInt>(Inst->getOperand(1))) {
10010 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10011 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10012 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10013 NewIdx = Inst->getOperand(0);
10014 } else if (Inst->getOpcode() == Instruction::Mul &&
10015 isa<ConstantInt>(Inst->getOperand(1))) {
10016 Scale = cast<ConstantInt>(Inst->getOperand(1));
10017 NewIdx = Inst->getOperand(0);
10018 }
10019 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010020
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010021 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010022 // out, perform the transformation. Note, we don't know whether Scale is
10023 // signed or not. We'll use unsigned version of division/modulo
10024 // operation after making sure Scale doesn't have the sign bit set.
10025 if (Scale && Scale->getSExtValue() >= 0LL &&
10026 Scale->getZExtValue() % ArrayEltSize == 0) {
10027 Scale = ConstantInt::get(Scale->getType(),
10028 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010029 if (Scale->getZExtValue() != 1) {
10030 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010031 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010032 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010033 NewIdx = InsertNewInstBefore(Sc, GEP);
10034 }
10035
10036 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010037 Value *Idx[2];
10038 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10039 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010040 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010041 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010042 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10043 // The NewGEP must be pointer typed, so must the old one -> BitCast
10044 return new BitCastInst(NewGEP, GEP.getType());
10045 }
10046 }
10047 }
10048 }
10049
10050 return 0;
10051}
10052
10053Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10054 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010055 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010056 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10057 const Type *NewTy =
10058 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10059 AllocationInst *New = 0;
10060
10061 // Create and insert the replacement instruction...
10062 if (isa<MallocInst>(AI))
10063 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10064 else {
10065 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10066 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10067 }
10068
10069 InsertNewInstBefore(New, AI);
10070
10071 // Scan to the end of the allocation instructions, to skip over a block of
10072 // allocas if possible...
10073 //
10074 BasicBlock::iterator It = New;
10075 while (isa<AllocationInst>(*It)) ++It;
10076
10077 // Now that I is pointing to the first non-allocation-inst in the block,
10078 // insert our getelementptr instruction...
10079 //
10080 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010081 Value *Idx[2];
10082 Idx[0] = NullIdx;
10083 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010084 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10085 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010086
10087 // Now make everything use the getelementptr instead of the original
10088 // allocation.
10089 return ReplaceInstUsesWith(AI, V);
10090 } else if (isa<UndefValue>(AI.getArraySize())) {
10091 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10092 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010093 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010094
10095 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10096 // Note that we only do this for alloca's, because malloc should allocate and
10097 // return a unique pointer, even for a zero byte allocation.
10098 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010099 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010100 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10101
10102 return 0;
10103}
10104
10105Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10106 Value *Op = FI.getOperand(0);
10107
10108 // free undef -> unreachable.
10109 if (isa<UndefValue>(Op)) {
10110 // Insert a new store to null because we cannot modify the CFG here.
10111 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010112 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010113 return EraseInstFromFunction(FI);
10114 }
10115
10116 // If we have 'free null' delete the instruction. This can happen in stl code
10117 // when lots of inlining happens.
10118 if (isa<ConstantPointerNull>(Op))
10119 return EraseInstFromFunction(FI);
10120
10121 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10122 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10123 FI.setOperand(0, CI->getOperand(0));
10124 return &FI;
10125 }
10126
10127 // Change free (gep X, 0,0,0,0) into free(X)
10128 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10129 if (GEPI->hasAllZeroIndices()) {
10130 AddToWorkList(GEPI);
10131 FI.setOperand(0, GEPI->getOperand(0));
10132 return &FI;
10133 }
10134 }
10135
10136 // Change free(malloc) into nothing, if the malloc has a single use.
10137 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10138 if (MI->hasOneUse()) {
10139 EraseInstFromFunction(FI);
10140 return EraseInstFromFunction(*MI);
10141 }
10142
10143 return 0;
10144}
10145
10146
10147/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010148static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010149 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010150 User *CI = cast<User>(LI.getOperand(0));
10151 Value *CastOp = CI->getOperand(0);
10152
Devang Patela0f8ea82007-10-18 19:52:32 +000010153 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10154 // Instead of loading constant c string, use corresponding integer value
10155 // directly if string length is small enough.
Evan Cheng833501d2008-06-30 07:31:25 +000010156 std::string Str;
10157 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010158 unsigned len = Str.length();
10159 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10160 unsigned numBits = Ty->getPrimitiveSizeInBits();
10161 // Replace LI with immediate integer store.
10162 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010163 APInt StrVal(numBits, 0);
10164 APInt SingleChar(numBits, 0);
10165 if (TD->isLittleEndian()) {
10166 for (signed i = len-1; i >= 0; i--) {
10167 SingleChar = (uint64_t) Str[i];
10168 StrVal = (StrVal << 8) | SingleChar;
10169 }
10170 } else {
10171 for (unsigned i = 0; i < len; i++) {
10172 SingleChar = (uint64_t) Str[i];
10173 StrVal = (StrVal << 8) | SingleChar;
10174 }
10175 // Append NULL at the end.
10176 SingleChar = 0;
10177 StrVal = (StrVal << 8) | SingleChar;
10178 }
10179 Value *NL = ConstantInt::get(StrVal);
10180 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010181 }
10182 }
10183 }
10184
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010185 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10186 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10187 const Type *SrcPTy = SrcTy->getElementType();
10188
10189 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10190 isa<VectorType>(DestPTy)) {
10191 // If the source is an array, the code below will not succeed. Check to
10192 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10193 // constants.
10194 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10195 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10196 if (ASrcTy->getNumElements() != 0) {
10197 Value *Idxs[2];
10198 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10199 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10200 SrcTy = cast<PointerType>(CastOp->getType());
10201 SrcPTy = SrcTy->getElementType();
10202 }
10203
10204 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10205 isa<VectorType>(SrcPTy)) &&
10206 // Do not allow turning this into a load of an integer, which is then
10207 // casted to a pointer, this pessimizes pointer analysis a lot.
10208 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10209 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10210 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10211
10212 // Okay, we are casting from one integer or pointer type to another of
10213 // the same size. Instead of casting the pointer before the load, cast
10214 // the result of the loaded value.
10215 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10216 CI->getName(),
10217 LI.isVolatile()),LI);
10218 // Now cast the result of the load.
10219 return new BitCastInst(NewLoad, LI.getType());
10220 }
10221 }
10222 }
10223 return 0;
10224}
10225
10226/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10227/// from this value cannot trap. If it is not obviously safe to load from the
10228/// specified pointer, we do a quick local scan of the basic block containing
10229/// ScanFrom, to determine if the address is already accessed.
10230static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010231 // If it is an alloca it is always safe to load from.
10232 if (isa<AllocaInst>(V)) return true;
10233
Duncan Sandse40a94a2007-09-19 10:25:38 +000010234 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010235 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010236 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010237 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010238
10239 // Otherwise, be a little bit agressive by scanning the local block where we
10240 // want to check to see if the pointer is already being loaded or stored
10241 // from/to. If so, the previous load or store would have already trapped,
10242 // so there is no harm doing an extra load (also, CSE will later eliminate
10243 // the load entirely).
10244 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10245
10246 while (BBI != E) {
10247 --BBI;
10248
Chris Lattner476983a2008-06-20 05:12:56 +000010249 // If we see a free or a call (which might do a free) the pointer could be
10250 // marked invalid.
10251 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10252 return false;
10253
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010254 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10255 if (LI->getOperand(0) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010256 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010257 if (SI->getOperand(1) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010258 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010259
10260 }
10261 return false;
10262}
10263
Chris Lattner0270a112007-08-11 18:48:48 +000010264/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10265/// until we find the underlying object a pointer is referring to or something
10266/// we don't understand. Note that the returned pointer may be offset from the
10267/// input, because we ignore GEP indices.
10268static Value *GetUnderlyingObject(Value *Ptr) {
10269 while (1) {
10270 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10271 if (CE->getOpcode() == Instruction::BitCast ||
10272 CE->getOpcode() == Instruction::GetElementPtr)
10273 Ptr = CE->getOperand(0);
10274 else
10275 return Ptr;
10276 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10277 Ptr = BCI->getOperand(0);
10278 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10279 Ptr = GEP->getOperand(0);
10280 } else {
10281 return Ptr;
10282 }
10283 }
10284}
10285
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010286Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10287 Value *Op = LI.getOperand(0);
10288
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010289 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010290 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10291 if (KnownAlign >
10292 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10293 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010294 LI.setAlignment(KnownAlign);
10295
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010296 // load (cast X) --> cast (load X) iff safe
10297 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010298 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010299 return Res;
10300
10301 // None of the following transforms are legal for volatile loads.
10302 if (LI.isVolatile()) return 0;
10303
10304 if (&LI.getParent()->front() != &LI) {
10305 BasicBlock::iterator BBI = &LI; --BBI;
10306 // If the instruction immediately before this is a store to the same
10307 // address, do a simple form of store->load forwarding.
10308 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10309 if (SI->getOperand(1) == LI.getOperand(0))
10310 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10311 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10312 if (LIB->getOperand(0) == LI.getOperand(0))
10313 return ReplaceInstUsesWith(LI, LIB);
10314 }
10315
Christopher Lamb2c175392007-12-29 07:56:53 +000010316 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10317 const Value *GEPI0 = GEPI->getOperand(0);
10318 // TODO: Consider a target hook for valid address spaces for this xform.
10319 if (isa<ConstantPointerNull>(GEPI0) &&
10320 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010321 // Insert a new store to null instruction before the load to indicate
10322 // that this code is not reachable. We do this instead of inserting
10323 // an unreachable instruction directly because we cannot modify the
10324 // CFG.
10325 new StoreInst(UndefValue::get(LI.getType()),
10326 Constant::getNullValue(Op->getType()), &LI);
10327 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10328 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010329 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010330
10331 if (Constant *C = dyn_cast<Constant>(Op)) {
10332 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010333 // TODO: Consider a target hook for valid address spaces for this xform.
10334 if (isa<UndefValue>(C) || (C->isNullValue() &&
10335 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010336 // Insert a new store to null instruction before the load to indicate that
10337 // this code is not reachable. We do this instead of inserting an
10338 // unreachable instruction directly because we cannot modify the CFG.
10339 new StoreInst(UndefValue::get(LI.getType()),
10340 Constant::getNullValue(Op->getType()), &LI);
10341 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10342 }
10343
10344 // Instcombine load (constant global) into the value loaded.
10345 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10346 if (GV->isConstant() && !GV->isDeclaration())
10347 return ReplaceInstUsesWith(LI, GV->getInitializer());
10348
10349 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010350 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010351 if (CE->getOpcode() == Instruction::GetElementPtr) {
10352 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10353 if (GV->isConstant() && !GV->isDeclaration())
10354 if (Constant *V =
10355 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10356 return ReplaceInstUsesWith(LI, V);
10357 if (CE->getOperand(0)->isNullValue()) {
10358 // Insert a new store to null instruction before the load to indicate
10359 // that this code is not reachable. We do this instead of inserting
10360 // an unreachable instruction directly because we cannot modify the
10361 // CFG.
10362 new StoreInst(UndefValue::get(LI.getType()),
10363 Constant::getNullValue(Op->getType()), &LI);
10364 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10365 }
10366
10367 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010368 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010369 return Res;
10370 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010371 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010372 }
Chris Lattner0270a112007-08-11 18:48:48 +000010373
10374 // If this load comes from anywhere in a constant global, and if the global
10375 // is all undef or zero, we know what it loads.
10376 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10377 if (GV->isConstant() && GV->hasInitializer()) {
10378 if (GV->getInitializer()->isNullValue())
10379 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10380 else if (isa<UndefValue>(GV->getInitializer()))
10381 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10382 }
10383 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010384
10385 if (Op->hasOneUse()) {
10386 // Change select and PHI nodes to select values instead of addresses: this
10387 // helps alias analysis out a lot, allows many others simplifications, and
10388 // exposes redundancy in the code.
10389 //
10390 // Note that we cannot do the transformation unless we know that the
10391 // introduced loads cannot trap! Something like this is valid as long as
10392 // the condition is always false: load (select bool %C, int* null, int* %G),
10393 // but it would not be valid if we transformed it to load from null
10394 // unconditionally.
10395 //
10396 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10397 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10398 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10399 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10400 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10401 SI->getOperand(1)->getName()+".val"), LI);
10402 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10403 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010404 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010405 }
10406
10407 // load (select (cond, null, P)) -> load P
10408 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10409 if (C->isNullValue()) {
10410 LI.setOperand(0, SI->getOperand(2));
10411 return &LI;
10412 }
10413
10414 // load (select (cond, P, null)) -> load P
10415 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10416 if (C->isNullValue()) {
10417 LI.setOperand(0, SI->getOperand(1));
10418 return &LI;
10419 }
10420 }
10421 }
10422 return 0;
10423}
10424
10425/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10426/// when possible.
10427static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10428 User *CI = cast<User>(SI.getOperand(1));
10429 Value *CastOp = CI->getOperand(0);
10430
10431 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10432 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10433 const Type *SrcPTy = SrcTy->getElementType();
10434
10435 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10436 // If the source is an array, the code below will not succeed. Check to
10437 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10438 // constants.
10439 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10440 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10441 if (ASrcTy->getNumElements() != 0) {
10442 Value* Idxs[2];
10443 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10444 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10445 SrcTy = cast<PointerType>(CastOp->getType());
10446 SrcPTy = SrcTy->getElementType();
10447 }
10448
10449 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10450 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10451 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10452
10453 // Okay, we are casting from one integer or pointer type to another of
10454 // the same size. Instead of casting the pointer before
10455 // the store, cast the value to be stored.
10456 Value *NewCast;
10457 Value *SIOp0 = SI.getOperand(0);
10458 Instruction::CastOps opcode = Instruction::BitCast;
10459 const Type* CastSrcTy = SIOp0->getType();
10460 const Type* CastDstTy = SrcPTy;
10461 if (isa<PointerType>(CastDstTy)) {
10462 if (CastSrcTy->isInteger())
10463 opcode = Instruction::IntToPtr;
10464 } else if (isa<IntegerType>(CastDstTy)) {
10465 if (isa<PointerType>(SIOp0->getType()))
10466 opcode = Instruction::PtrToInt;
10467 }
10468 if (Constant *C = dyn_cast<Constant>(SIOp0))
10469 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10470 else
10471 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010472 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010473 SI);
10474 return new StoreInst(NewCast, CastOp);
10475 }
10476 }
10477 }
10478 return 0;
10479}
10480
10481Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10482 Value *Val = SI.getOperand(0);
10483 Value *Ptr = SI.getOperand(1);
10484
10485 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10486 EraseInstFromFunction(SI);
10487 ++NumCombined;
10488 return 0;
10489 }
10490
10491 // If the RHS is an alloca with a single use, zapify the store, making the
10492 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010493 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010494 if (isa<AllocaInst>(Ptr)) {
10495 EraseInstFromFunction(SI);
10496 ++NumCombined;
10497 return 0;
10498 }
10499
10500 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10501 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10502 GEP->getOperand(0)->hasOneUse()) {
10503 EraseInstFromFunction(SI);
10504 ++NumCombined;
10505 return 0;
10506 }
10507 }
10508
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010509 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010510 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10511 if (KnownAlign >
10512 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10513 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010514 SI.setAlignment(KnownAlign);
10515
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010516 // Do really simple DSE, to catch cases where there are several consequtive
10517 // stores to the same location, separated by a few arithmetic operations. This
10518 // situation often occurs with bitfield accesses.
10519 BasicBlock::iterator BBI = &SI;
10520 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10521 --ScanInsts) {
10522 --BBI;
10523
10524 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10525 // Prev store isn't volatile, and stores to the same location?
10526 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10527 ++NumDeadStore;
10528 ++BBI;
10529 EraseInstFromFunction(*PrevSI);
10530 continue;
10531 }
10532 break;
10533 }
10534
10535 // If this is a load, we have to stop. However, if the loaded value is from
10536 // the pointer we're loading and is producing the pointer we're storing,
10537 // then *this* store is dead (X = load P; store X -> P).
10538 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010539 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010540 EraseInstFromFunction(SI);
10541 ++NumCombined;
10542 return 0;
10543 }
10544 // Otherwise, this is a load from some other location. Stores before it
10545 // may not be dead.
10546 break;
10547 }
10548
10549 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010550 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010551 break;
10552 }
10553
10554
10555 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10556
10557 // store X, null -> turns into 'unreachable' in SimplifyCFG
10558 if (isa<ConstantPointerNull>(Ptr)) {
10559 if (!isa<UndefValue>(Val)) {
10560 SI.setOperand(0, UndefValue::get(Val->getType()));
10561 if (Instruction *U = dyn_cast<Instruction>(Val))
10562 AddToWorkList(U); // Dropped a use.
10563 ++NumCombined;
10564 }
10565 return 0; // Do not modify these!
10566 }
10567
10568 // store undef, Ptr -> noop
10569 if (isa<UndefValue>(Val)) {
10570 EraseInstFromFunction(SI);
10571 ++NumCombined;
10572 return 0;
10573 }
10574
10575 // If the pointer destination is a cast, see if we can fold the cast into the
10576 // source instead.
10577 if (isa<CastInst>(Ptr))
10578 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10579 return Res;
10580 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10581 if (CE->isCast())
10582 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10583 return Res;
10584
10585
10586 // If this store is the last instruction in the basic block, and if the block
10587 // ends with an unconditional branch, try to move it to the successor block.
10588 BBI = &SI; ++BBI;
10589 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10590 if (BI->isUnconditional())
10591 if (SimplifyStoreAtEndOfBlock(SI))
10592 return 0; // xform done!
10593
10594 return 0;
10595}
10596
10597/// SimplifyStoreAtEndOfBlock - Turn things like:
10598/// if () { *P = v1; } else { *P = v2 }
10599/// into a phi node with a store in the successor.
10600///
10601/// Simplify things like:
10602/// *P = v1; if () { *P = v2; }
10603/// into a phi node with a store in the successor.
10604///
10605bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10606 BasicBlock *StoreBB = SI.getParent();
10607
10608 // Check to see if the successor block has exactly two incoming edges. If
10609 // so, see if the other predecessor contains a store to the same location.
10610 // if so, insert a PHI node (if needed) and move the stores down.
10611 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10612
10613 // Determine whether Dest has exactly two predecessors and, if so, compute
10614 // the other predecessor.
10615 pred_iterator PI = pred_begin(DestBB);
10616 BasicBlock *OtherBB = 0;
10617 if (*PI != StoreBB)
10618 OtherBB = *PI;
10619 ++PI;
10620 if (PI == pred_end(DestBB))
10621 return false;
10622
10623 if (*PI != StoreBB) {
10624 if (OtherBB)
10625 return false;
10626 OtherBB = *PI;
10627 }
10628 if (++PI != pred_end(DestBB))
10629 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000010630
10631 // Bail out if all the relevant blocks aren't distinct (this can happen,
10632 // for example, if SI is in an infinite loop)
10633 if (StoreBB == DestBB || OtherBB == DestBB)
10634 return false;
10635
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010636 // Verify that the other block ends in a branch and is not otherwise empty.
10637 BasicBlock::iterator BBI = OtherBB->getTerminator();
10638 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10639 if (!OtherBr || BBI == OtherBB->begin())
10640 return false;
10641
10642 // If the other block ends in an unconditional branch, check for the 'if then
10643 // else' case. there is an instruction before the branch.
10644 StoreInst *OtherStore = 0;
10645 if (OtherBr->isUnconditional()) {
10646 // If this isn't a store, or isn't a store to the same location, bail out.
10647 --BBI;
10648 OtherStore = dyn_cast<StoreInst>(BBI);
10649 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10650 return false;
10651 } else {
10652 // Otherwise, the other block ended with a conditional branch. If one of the
10653 // destinations is StoreBB, then we have the if/then case.
10654 if (OtherBr->getSuccessor(0) != StoreBB &&
10655 OtherBr->getSuccessor(1) != StoreBB)
10656 return false;
10657
10658 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10659 // if/then triangle. See if there is a store to the same ptr as SI that
10660 // lives in OtherBB.
10661 for (;; --BBI) {
10662 // Check to see if we find the matching store.
10663 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10664 if (OtherStore->getOperand(1) != SI.getOperand(1))
10665 return false;
10666 break;
10667 }
Eli Friedman3a311d52008-06-13 22:02:12 +000010668 // If we find something that may be using or overwriting the stored
10669 // value, or if we run out of instructions, we can't do the xform.
10670 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010671 BBI == OtherBB->begin())
10672 return false;
10673 }
10674
10675 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000010676 // make sure nothing reads or overwrites the stored value in
10677 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010678 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10679 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000010680 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010681 return false;
10682 }
10683 }
10684
10685 // Insert a PHI node now if we need it.
10686 Value *MergedVal = OtherStore->getOperand(0);
10687 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010688 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010689 PN->reserveOperandSpace(2);
10690 PN->addIncoming(SI.getOperand(0), SI.getParent());
10691 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10692 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10693 }
10694
10695 // Advance to a place where it is safe to insert the new store and
10696 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000010697 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010698 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10699 OtherStore->isVolatile()), *BBI);
10700
10701 // Nuke the old stores.
10702 EraseInstFromFunction(SI);
10703 EraseInstFromFunction(*OtherStore);
10704 ++NumCombined;
10705 return true;
10706}
10707
10708
10709Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10710 // Change br (not X), label True, label False to: br X, label False, True
10711 Value *X = 0;
10712 BasicBlock *TrueDest;
10713 BasicBlock *FalseDest;
10714 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10715 !isa<Constant>(X)) {
10716 // Swap Destinations and condition...
10717 BI.setCondition(X);
10718 BI.setSuccessor(0, FalseDest);
10719 BI.setSuccessor(1, TrueDest);
10720 return &BI;
10721 }
10722
10723 // Cannonicalize fcmp_one -> fcmp_oeq
10724 FCmpInst::Predicate FPred; Value *Y;
10725 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10726 TrueDest, FalseDest)))
10727 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10728 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10729 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10730 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10731 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10732 NewSCC->takeName(I);
10733 // Swap Destinations and condition...
10734 BI.setCondition(NewSCC);
10735 BI.setSuccessor(0, FalseDest);
10736 BI.setSuccessor(1, TrueDest);
10737 RemoveFromWorkList(I);
10738 I->eraseFromParent();
10739 AddToWorkList(NewSCC);
10740 return &BI;
10741 }
10742
10743 // Cannonicalize icmp_ne -> icmp_eq
10744 ICmpInst::Predicate IPred;
10745 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10746 TrueDest, FalseDest)))
10747 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10748 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10749 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10750 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10751 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10752 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10753 NewSCC->takeName(I);
10754 // Swap Destinations and condition...
10755 BI.setCondition(NewSCC);
10756 BI.setSuccessor(0, FalseDest);
10757 BI.setSuccessor(1, TrueDest);
10758 RemoveFromWorkList(I);
10759 I->eraseFromParent();;
10760 AddToWorkList(NewSCC);
10761 return &BI;
10762 }
10763
10764 return 0;
10765}
10766
10767Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10768 Value *Cond = SI.getCondition();
10769 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10770 if (I->getOpcode() == Instruction::Add)
10771 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10772 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10773 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10774 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10775 AddRHS));
10776 SI.setOperand(0, I->getOperand(0));
10777 AddToWorkList(I);
10778 return &SI;
10779 }
10780 }
10781 return 0;
10782}
10783
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010784Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000010785 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010786
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000010787 if (!EV.hasIndices())
10788 return ReplaceInstUsesWith(EV, Agg);
10789
10790 if (Constant *C = dyn_cast<Constant>(Agg)) {
10791 if (isa<UndefValue>(C))
10792 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10793
10794 if (isa<ConstantAggregateZero>(C))
10795 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10796
10797 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10798 // Extract the element indexed by the first index out of the constant
10799 Value *V = C->getOperand(*EV.idx_begin());
10800 if (EV.getNumIndices() > 1)
10801 // Extract the remaining indices out of the constant indexed by the
10802 // first index
10803 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10804 else
10805 return ReplaceInstUsesWith(EV, V);
10806 }
10807 return 0; // Can't handle other constants
10808 }
10809 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10810 // We're extracting from an insertvalue instruction, compare the indices
10811 const unsigned *exti, *exte, *insi, *inse;
10812 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10813 exte = EV.idx_end(), inse = IV->idx_end();
10814 exti != exte && insi != inse;
10815 ++exti, ++insi) {
10816 if (*insi != *exti)
10817 // The insert and extract both reference distinctly different elements.
10818 // This means the extract is not influenced by the insert, and we can
10819 // replace the aggregate operand of the extract with the aggregate
10820 // operand of the insert. i.e., replace
10821 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10822 // %E = extractvalue { i32, { i32 } } %I, 0
10823 // with
10824 // %E = extractvalue { i32, { i32 } } %A, 0
10825 return ExtractValueInst::Create(IV->getAggregateOperand(),
10826 EV.idx_begin(), EV.idx_end());
10827 }
10828 if (exti == exte && insi == inse)
10829 // Both iterators are at the end: Index lists are identical. Replace
10830 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10831 // %C = extractvalue { i32, { i32 } } %B, 1, 0
10832 // with "i32 42"
10833 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10834 if (exti == exte) {
10835 // The extract list is a prefix of the insert list. i.e. replace
10836 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10837 // %E = extractvalue { i32, { i32 } } %I, 1
10838 // with
10839 // %X = extractvalue { i32, { i32 } } %A, 1
10840 // %E = insertvalue { i32 } %X, i32 42, 0
10841 // by switching the order of the insert and extract (though the
10842 // insertvalue should be left in, since it may have other uses).
10843 Value *NewEV = InsertNewInstBefore(
10844 ExtractValueInst::Create(IV->getAggregateOperand(),
10845 EV.idx_begin(), EV.idx_end()),
10846 EV);
10847 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10848 insi, inse);
10849 }
10850 if (insi == inse)
10851 // The insert list is a prefix of the extract list
10852 // We can simply remove the common indices from the extract and make it
10853 // operate on the inserted value instead of the insertvalue result.
10854 // i.e., replace
10855 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10856 // %E = extractvalue { i32, { i32 } } %I, 1, 0
10857 // with
10858 // %E extractvalue { i32 } { i32 42 }, 0
10859 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
10860 exti, exte);
10861 }
10862 // Can't simplify extracts from other values. Note that nested extracts are
10863 // already simplified implicitely by the above (extract ( extract (insert) )
10864 // will be translated into extract ( insert ( extract ) ) first and then just
10865 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000010866 return 0;
10867}
10868
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010869/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10870/// is to leave as a vector operation.
10871static bool CheapToScalarize(Value *V, bool isConstant) {
10872 if (isa<ConstantAggregateZero>(V))
10873 return true;
10874 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10875 if (isConstant) return true;
10876 // If all elts are the same, we can extract.
10877 Constant *Op0 = C->getOperand(0);
10878 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10879 if (C->getOperand(i) != Op0)
10880 return false;
10881 return true;
10882 }
10883 Instruction *I = dyn_cast<Instruction>(V);
10884 if (!I) return false;
10885
10886 // Insert element gets simplified to the inserted element or is deleted if
10887 // this is constant idx extract element and its a constant idx insertelt.
10888 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10889 isa<ConstantInt>(I->getOperand(2)))
10890 return true;
10891 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10892 return true;
10893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10894 if (BO->hasOneUse() &&
10895 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10896 CheapToScalarize(BO->getOperand(1), isConstant)))
10897 return true;
10898 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10899 if (CI->hasOneUse() &&
10900 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10901 CheapToScalarize(CI->getOperand(1), isConstant)))
10902 return true;
10903
10904 return false;
10905}
10906
10907/// Read and decode a shufflevector mask.
10908///
10909/// It turns undef elements into values that are larger than the number of
10910/// elements in the input.
10911static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10912 unsigned NElts = SVI->getType()->getNumElements();
10913 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10914 return std::vector<unsigned>(NElts, 0);
10915 if (isa<UndefValue>(SVI->getOperand(2)))
10916 return std::vector<unsigned>(NElts, 2*NElts);
10917
10918 std::vector<unsigned> Result;
10919 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000010920 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10921 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010922 Result.push_back(NElts*2); // undef -> 8
10923 else
Gabor Greif17396002008-06-12 21:37:33 +000010924 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010925 return Result;
10926}
10927
10928/// FindScalarElement - Given a vector and an element number, see if the scalar
10929/// value is already around as a register, for example if it were inserted then
10930/// extracted from the vector.
10931static Value *FindScalarElement(Value *V, unsigned EltNo) {
10932 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10933 const VectorType *PTy = cast<VectorType>(V->getType());
10934 unsigned Width = PTy->getNumElements();
10935 if (EltNo >= Width) // Out of range access.
10936 return UndefValue::get(PTy->getElementType());
10937
10938 if (isa<UndefValue>(V))
10939 return UndefValue::get(PTy->getElementType());
10940 else if (isa<ConstantAggregateZero>(V))
10941 return Constant::getNullValue(PTy->getElementType());
10942 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10943 return CP->getOperand(EltNo);
10944 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10945 // If this is an insert to a variable element, we don't know what it is.
10946 if (!isa<ConstantInt>(III->getOperand(2)))
10947 return 0;
10948 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10949
10950 // If this is an insert to the element we are looking for, return the
10951 // inserted value.
10952 if (EltNo == IIElt)
10953 return III->getOperand(1);
10954
10955 // Otherwise, the insertelement doesn't modify the value, recurse on its
10956 // vector input.
10957 return FindScalarElement(III->getOperand(0), EltNo);
10958 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10959 unsigned InEl = getShuffleMask(SVI)[EltNo];
10960 if (InEl < Width)
10961 return FindScalarElement(SVI->getOperand(0), InEl);
10962 else if (InEl < Width*2)
10963 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10964 else
10965 return UndefValue::get(PTy->getElementType());
10966 }
10967
10968 // Otherwise, we don't know.
10969 return 0;
10970}
10971
10972Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010973 // If vector val is undef, replace extract with scalar undef.
10974 if (isa<UndefValue>(EI.getOperand(0)))
10975 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10976
10977 // If vector val is constant 0, replace extract with scalar 0.
10978 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10979 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10980
10981 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000010982 // If vector val is constant with all elements the same, replace EI with
10983 // that element. When the elements are not identical, we cannot replace yet
10984 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010985 Constant *op0 = C->getOperand(0);
10986 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10987 if (C->getOperand(i) != op0) {
10988 op0 = 0;
10989 break;
10990 }
10991 if (op0)
10992 return ReplaceInstUsesWith(EI, op0);
10993 }
10994
10995 // If extracting a specified index from the vector, see if we can recursively
10996 // find a previously computed scalar that was inserted into the vector.
10997 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10998 unsigned IndexVal = IdxC->getZExtValue();
10999 unsigned VectorWidth =
11000 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11001
11002 // If this is extracting an invalid index, turn this into undef, to avoid
11003 // crashing the code below.
11004 if (IndexVal >= VectorWidth)
11005 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11006
11007 // This instruction only demands the single element from the input vector.
11008 // If the input vector has a single use, simplify it based on this use
11009 // property.
11010 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11011 uint64_t UndefElts;
11012 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11013 1 << IndexVal,
11014 UndefElts)) {
11015 EI.setOperand(0, V);
11016 return &EI;
11017 }
11018 }
11019
11020 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11021 return ReplaceInstUsesWith(EI, Elt);
11022
11023 // If the this extractelement is directly using a bitcast from a vector of
11024 // the same number of elements, see if we can find the source element from
11025 // it. In this case, we will end up needing to bitcast the scalars.
11026 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11027 if (const VectorType *VT =
11028 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11029 if (VT->getNumElements() == VectorWidth)
11030 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11031 return new BitCastInst(Elt, EI.getType());
11032 }
11033 }
11034
11035 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11036 if (I->hasOneUse()) {
11037 // Push extractelement into predecessor operation if legal and
11038 // profitable to do so
11039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11040 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11041 if (CheapToScalarize(BO, isConstantElt)) {
11042 ExtractElementInst *newEI0 =
11043 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11044 EI.getName()+".lhs");
11045 ExtractElementInst *newEI1 =
11046 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11047 EI.getName()+".rhs");
11048 InsertNewInstBefore(newEI0, EI);
11049 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011050 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011051 }
11052 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011053 unsigned AS =
11054 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011055 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11056 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011057 GetElementPtrInst *GEP =
11058 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011059 InsertNewInstBefore(GEP, EI);
11060 return new LoadInst(GEP);
11061 }
11062 }
11063 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11064 // Extracting the inserted element?
11065 if (IE->getOperand(2) == EI.getOperand(1))
11066 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11067 // If the inserted and extracted elements are constants, they must not
11068 // be the same value, extract from the pre-inserted value instead.
11069 if (isa<Constant>(IE->getOperand(2)) &&
11070 isa<Constant>(EI.getOperand(1))) {
11071 AddUsesToWorkList(EI);
11072 EI.setOperand(0, IE->getOperand(0));
11073 return &EI;
11074 }
11075 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11076 // If this is extracting an element from a shufflevector, figure out where
11077 // it came from and extract from the appropriate input element instead.
11078 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11079 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11080 Value *Src;
11081 if (SrcIdx < SVI->getType()->getNumElements())
11082 Src = SVI->getOperand(0);
11083 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11084 SrcIdx -= SVI->getType()->getNumElements();
11085 Src = SVI->getOperand(1);
11086 } else {
11087 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11088 }
11089 return new ExtractElementInst(Src, SrcIdx);
11090 }
11091 }
11092 }
11093 return 0;
11094}
11095
11096/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11097/// elements from either LHS or RHS, return the shuffle mask and true.
11098/// Otherwise, return false.
11099static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11100 std::vector<Constant*> &Mask) {
11101 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11102 "Invalid CollectSingleShuffleElements");
11103 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11104
11105 if (isa<UndefValue>(V)) {
11106 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11107 return true;
11108 } else if (V == LHS) {
11109 for (unsigned i = 0; i != NumElts; ++i)
11110 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11111 return true;
11112 } else if (V == RHS) {
11113 for (unsigned i = 0; i != NumElts; ++i)
11114 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11115 return true;
11116 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11117 // If this is an insert of an extract from some other vector, include it.
11118 Value *VecOp = IEI->getOperand(0);
11119 Value *ScalarOp = IEI->getOperand(1);
11120 Value *IdxOp = IEI->getOperand(2);
11121
11122 if (!isa<ConstantInt>(IdxOp))
11123 return false;
11124 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11125
11126 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11127 // Okay, we can handle this if the vector we are insertinting into is
11128 // transitively ok.
11129 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11130 // If so, update the mask to reflect the inserted undef.
11131 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11132 return true;
11133 }
11134 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11135 if (isa<ConstantInt>(EI->getOperand(1)) &&
11136 EI->getOperand(0)->getType() == V->getType()) {
11137 unsigned ExtractedIdx =
11138 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11139
11140 // This must be extracting from either LHS or RHS.
11141 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11142 // Okay, we can handle this if the vector we are insertinting into is
11143 // transitively ok.
11144 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11145 // If so, update the mask to reflect the inserted value.
11146 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000011147 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011148 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11149 } else {
11150 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011151 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011152 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11153
11154 }
11155 return true;
11156 }
11157 }
11158 }
11159 }
11160 }
11161 // TODO: Handle shufflevector here!
11162
11163 return false;
11164}
11165
11166/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11167/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11168/// that computes V and the LHS value of the shuffle.
11169static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11170 Value *&RHS) {
11171 assert(isa<VectorType>(V->getType()) &&
11172 (RHS == 0 || V->getType() == RHS->getType()) &&
11173 "Invalid shuffle!");
11174 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11175
11176 if (isa<UndefValue>(V)) {
11177 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11178 return V;
11179 } else if (isa<ConstantAggregateZero>(V)) {
11180 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11181 return V;
11182 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11183 // If this is an insert of an extract from some other vector, include it.
11184 Value *VecOp = IEI->getOperand(0);
11185 Value *ScalarOp = IEI->getOperand(1);
11186 Value *IdxOp = IEI->getOperand(2);
11187
11188 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11189 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11190 EI->getOperand(0)->getType() == V->getType()) {
11191 unsigned ExtractedIdx =
11192 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11193 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11194
11195 // Either the extracted from or inserted into vector must be RHSVec,
11196 // otherwise we'd end up with a shuffle of three inputs.
11197 if (EI->getOperand(0) == RHS || RHS == 0) {
11198 RHS = EI->getOperand(0);
11199 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011200 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011201 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11202 return V;
11203 }
11204
11205 if (VecOp == RHS) {
11206 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11207 // Everything but the extracted element is replaced with the RHS.
11208 for (unsigned i = 0; i != NumElts; ++i) {
11209 if (i != InsertedIdx)
11210 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11211 }
11212 return V;
11213 }
11214
11215 // If this insertelement is a chain that comes from exactly these two
11216 // vectors, return the vector and the effective shuffle.
11217 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11218 return EI->getOperand(0);
11219
11220 }
11221 }
11222 }
11223 // TODO: Handle shufflevector here!
11224
11225 // Otherwise, can't do anything fancy. Return an identity vector.
11226 for (unsigned i = 0; i != NumElts; ++i)
11227 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11228 return V;
11229}
11230
11231Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11232 Value *VecOp = IE.getOperand(0);
11233 Value *ScalarOp = IE.getOperand(1);
11234 Value *IdxOp = IE.getOperand(2);
11235
11236 // Inserting an undef or into an undefined place, remove this.
11237 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11238 ReplaceInstUsesWith(IE, VecOp);
11239
11240 // If the inserted element was extracted from some other vector, and if the
11241 // indexes are constant, try to turn this into a shufflevector operation.
11242 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11243 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11244 EI->getOperand(0)->getType() == IE.getType()) {
11245 unsigned NumVectorElts = IE.getType()->getNumElements();
11246 unsigned ExtractedIdx =
11247 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11248 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11249
11250 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11251 return ReplaceInstUsesWith(IE, VecOp);
11252
11253 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11254 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11255
11256 // If we are extracting a value from a vector, then inserting it right
11257 // back into the same place, just use the input vector.
11258 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11259 return ReplaceInstUsesWith(IE, VecOp);
11260
11261 // We could theoretically do this for ANY input. However, doing so could
11262 // turn chains of insertelement instructions into a chain of shufflevector
11263 // instructions, and right now we do not merge shufflevectors. As such,
11264 // only do this in a situation where it is clear that there is benefit.
11265 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11266 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11267 // the values of VecOp, except then one read from EIOp0.
11268 // Build a new shuffle mask.
11269 std::vector<Constant*> Mask;
11270 if (isa<UndefValue>(VecOp))
11271 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11272 else {
11273 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11274 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11275 NumVectorElts));
11276 }
11277 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11278 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11279 ConstantVector::get(Mask));
11280 }
11281
11282 // If this insertelement isn't used by some other insertelement, turn it
11283 // (and any insertelements it points to), into one big shuffle.
11284 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11285 std::vector<Constant*> Mask;
11286 Value *RHS = 0;
11287 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11288 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11289 // We now have a shuffle of LHS, RHS, Mask.
11290 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11291 }
11292 }
11293 }
11294
11295 return 0;
11296}
11297
11298
11299Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11300 Value *LHS = SVI.getOperand(0);
11301 Value *RHS = SVI.getOperand(1);
11302 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11303
11304 bool MadeChange = false;
11305
11306 // Undefined shuffle mask -> undefined value.
11307 if (isa<UndefValue>(SVI.getOperand(2)))
11308 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000011309
11310 uint64_t UndefElts;
11311 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11312 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11313 if (VWidth <= 64 &&
Dan Gohman83b702d2008-09-11 22:47:57 +000011314 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11315 LHS = SVI.getOperand(0);
11316 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000011317 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000011318 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011319
11320 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11321 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11322 if (LHS == RHS || isa<UndefValue>(LHS)) {
11323 if (isa<UndefValue>(LHS) && LHS == RHS) {
11324 // shuffle(undef,undef,mask) -> undef.
11325 return ReplaceInstUsesWith(SVI, LHS);
11326 }
11327
11328 // Remap any references to RHS to use LHS.
11329 std::vector<Constant*> Elts;
11330 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11331 if (Mask[i] >= 2*e)
11332 Elts.push_back(UndefValue::get(Type::Int32Ty));
11333 else {
11334 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000011335 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011336 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanbba96b92008-08-06 18:17:32 +000011337 Elts.push_back(UndefValue::get(Type::Int32Ty));
11338 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000011339 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanbba96b92008-08-06 18:17:32 +000011340 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11341 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011342 }
11343 }
11344 SVI.setOperand(0, SVI.getOperand(1));
11345 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11346 SVI.setOperand(2, ConstantVector::get(Elts));
11347 LHS = SVI.getOperand(0);
11348 RHS = SVI.getOperand(1);
11349 MadeChange = true;
11350 }
11351
11352 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11353 bool isLHSID = true, isRHSID = true;
11354
11355 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11356 if (Mask[i] >= e*2) continue; // Ignore undef values.
11357 // Is this an identity shuffle of the LHS value?
11358 isLHSID &= (Mask[i] == i);
11359
11360 // Is this an identity shuffle of the RHS value?
11361 isRHSID &= (Mask[i]-e == i);
11362 }
11363
11364 // Eliminate identity shuffles.
11365 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11366 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11367
11368 // If the LHS is a shufflevector itself, see if we can combine it with this
11369 // one without producing an unusual shuffle. Here we are really conservative:
11370 // we are absolutely afraid of producing a shuffle mask not in the input
11371 // program, because the code gen may not be smart enough to turn a merged
11372 // shuffle into two specific shuffles: it may produce worse code. As such,
11373 // we only merge two shuffles if the result is one of the two input shuffle
11374 // masks. In this case, merging the shuffles just removes one instruction,
11375 // which we know is safe. This is good for things like turning:
11376 // (splat(splat)) -> splat.
11377 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11378 if (isa<UndefValue>(RHS)) {
11379 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11380
11381 std::vector<unsigned> NewMask;
11382 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11383 if (Mask[i] >= 2*e)
11384 NewMask.push_back(2*e);
11385 else
11386 NewMask.push_back(LHSMask[Mask[i]]);
11387
11388 // If the result mask is equal to the src shuffle or this shuffle mask, do
11389 // the replacement.
11390 if (NewMask == LHSMask || NewMask == Mask) {
11391 std::vector<Constant*> Elts;
11392 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11393 if (NewMask[i] >= e*2) {
11394 Elts.push_back(UndefValue::get(Type::Int32Ty));
11395 } else {
11396 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11397 }
11398 }
11399 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11400 LHSSVI->getOperand(1),
11401 ConstantVector::get(Elts));
11402 }
11403 }
11404 }
11405
11406 return MadeChange ? &SVI : 0;
11407}
11408
11409
11410
11411
11412/// TryToSinkInstruction - Try to move the specified instruction from its
11413/// current block into the beginning of DestBlock, which can only happen if it's
11414/// safe to move the instruction past all of the instructions between it and the
11415/// end of its block.
11416static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11417 assert(I->hasOneUse() && "Invariants didn't hold!");
11418
11419 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011420 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11421 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011422
11423 // Do not sink alloca instructions out of the entry block.
11424 if (isa<AllocaInst>(I) && I->getParent() ==
11425 &DestBlock->getParent()->getEntryBlock())
11426 return false;
11427
11428 // We can only sink load instructions if there is nothing between the load and
11429 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011430 if (I->mayReadFromMemory()) {
11431 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011432 Scan != E; ++Scan)
11433 if (Scan->mayWriteToMemory())
11434 return false;
11435 }
11436
Dan Gohman514277c2008-05-23 21:05:58 +000011437 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011438
11439 I->moveBefore(InsertPos);
11440 ++NumSunkInst;
11441 return true;
11442}
11443
11444
11445/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11446/// all reachable code to the worklist.
11447///
11448/// This has a couple of tricks to make the code faster and more powerful. In
11449/// particular, we constant fold and DCE instructions as we go, to avoid adding
11450/// them to the worklist (this significantly speeds up instcombine on code where
11451/// many instructions are dead or constant). Additionally, if we find a branch
11452/// whose condition is a known constant, we only visit the reachable successors.
11453///
11454static void AddReachableCodeToWorklist(BasicBlock *BB,
11455 SmallPtrSet<BasicBlock*, 64> &Visited,
11456 InstCombiner &IC,
11457 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000011458 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011459 Worklist.push_back(BB);
11460
11461 while (!Worklist.empty()) {
11462 BB = Worklist.back();
11463 Worklist.pop_back();
11464
11465 // We have now visited this block! If we've already been here, ignore it.
11466 if (!Visited.insert(BB)) continue;
11467
11468 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11469 Instruction *Inst = BBI++;
11470
11471 // DCE instruction if trivially dead.
11472 if (isInstructionTriviallyDead(Inst)) {
11473 ++NumDeadInst;
11474 DOUT << "IC: DCE: " << *Inst;
11475 Inst->eraseFromParent();
11476 continue;
11477 }
11478
11479 // ConstantProp instruction if trivially constant.
11480 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11481 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11482 Inst->replaceAllUsesWith(C);
11483 ++NumConstProp;
11484 Inst->eraseFromParent();
11485 continue;
11486 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011487
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011488 IC.AddToWorkList(Inst);
11489 }
11490
11491 // Recursively visit successors. If this is a branch or switch on a
11492 // constant, only visit the reachable successor.
11493 TerminatorInst *TI = BB->getTerminator();
11494 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11495 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11496 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011497 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011498 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011499 continue;
11500 }
11501 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11502 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11503 // See if this is an explicit destination.
11504 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11505 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011506 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011507 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011508 continue;
11509 }
11510
11511 // Otherwise it is the default destination.
11512 Worklist.push_back(SI->getSuccessor(0));
11513 continue;
11514 }
11515 }
11516
11517 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11518 Worklist.push_back(TI->getSuccessor(i));
11519 }
11520}
11521
11522bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11523 bool Changed = false;
11524 TD = &getAnalysis<TargetData>();
11525
11526 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11527 << F.getNameStr() << "\n");
11528
11529 {
11530 // Do a depth-first traversal of the function, populate the worklist with
11531 // the reachable instructions. Ignore blocks that are not reachable. Keep
11532 // track of which blocks we visit.
11533 SmallPtrSet<BasicBlock*, 64> Visited;
11534 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11535
11536 // Do a quick scan over the function. If we find any blocks that are
11537 // unreachable, remove any instructions inside of them. This prevents
11538 // the instcombine code from having to deal with some bad special cases.
11539 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11540 if (!Visited.count(BB)) {
11541 Instruction *Term = BB->getTerminator();
11542 while (Term != BB->begin()) { // Remove instrs bottom-up
11543 BasicBlock::iterator I = Term; --I;
11544
11545 DOUT << "IC: DCE: " << *I;
11546 ++NumDeadInst;
11547
11548 if (!I->use_empty())
11549 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11550 I->eraseFromParent();
11551 }
11552 }
11553 }
11554
11555 while (!Worklist.empty()) {
11556 Instruction *I = RemoveOneFromWorkList();
11557 if (I == 0) continue; // skip null values.
11558
11559 // Check to see if we can DCE the instruction.
11560 if (isInstructionTriviallyDead(I)) {
11561 // Add operands to the worklist.
11562 if (I->getNumOperands() < 4)
11563 AddUsesToWorkList(*I);
11564 ++NumDeadInst;
11565
11566 DOUT << "IC: DCE: " << *I;
11567
11568 I->eraseFromParent();
11569 RemoveFromWorkList(I);
11570 continue;
11571 }
11572
11573 // Instruction isn't dead, see if we can constant propagate it.
11574 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11575 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11576
11577 // Add operands to the worklist.
11578 AddUsesToWorkList(*I);
11579 ReplaceInstUsesWith(*I, C);
11580
11581 ++NumConstProp;
11582 I->eraseFromParent();
11583 RemoveFromWorkList(I);
11584 continue;
11585 }
11586
Nick Lewyckyadb67922008-05-25 20:56:15 +000011587 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11588 // See if we can constant fold its operands.
11589 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11591 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11592 i->set(NewC);
11593 }
11594 }
11595 }
11596
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011597 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000011598 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011599 BasicBlock *BB = I->getParent();
11600 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11601 if (UserParent != BB) {
11602 bool UserIsSuccessor = false;
11603 // See if the user is one of our successors.
11604 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11605 if (*SI == UserParent) {
11606 UserIsSuccessor = true;
11607 break;
11608 }
11609
11610 // If the user is one of our immediate successors, and if that successor
11611 // only has us as a predecessors (we'd have to split the critical edge
11612 // otherwise), we can keep going.
11613 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11614 next(pred_begin(UserParent)) == pred_end(UserParent))
11615 // Okay, the CFG is simple enough, try to sink this instruction.
11616 Changed |= TryToSinkInstruction(I, UserParent);
11617 }
11618 }
11619
11620 // Now that we have an instruction, try combining it to simplify it...
11621#ifndef NDEBUG
11622 std::string OrigI;
11623#endif
11624 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11625 if (Instruction *Result = visit(*I)) {
11626 ++NumCombined;
11627 // Should we replace the old instruction with a new one?
11628 if (Result != I) {
11629 DOUT << "IC: Old = " << *I
11630 << " New = " << *Result;
11631
11632 // Everything uses the new instruction now.
11633 I->replaceAllUsesWith(Result);
11634
11635 // Push the new instruction and any users onto the worklist.
11636 AddToWorkList(Result);
11637 AddUsersToWorkList(*Result);
11638
11639 // Move the name to the new instruction first.
11640 Result->takeName(I);
11641
11642 // Insert the new instruction into the basic block...
11643 BasicBlock *InstParent = I->getParent();
11644 BasicBlock::iterator InsertPos = I;
11645
11646 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11647 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11648 ++InsertPos;
11649
11650 InstParent->getInstList().insert(InsertPos, Result);
11651
11652 // Make sure that we reprocess all operands now that we reduced their
11653 // use counts.
11654 AddUsesToWorkList(*I);
11655
11656 // Instructions can end up on the worklist more than once. Make sure
11657 // we do not process an instruction that has been deleted.
11658 RemoveFromWorkList(I);
11659
11660 // Erase the old instruction.
11661 InstParent->getInstList().erase(I);
11662 } else {
11663#ifndef NDEBUG
11664 DOUT << "IC: Mod = " << OrigI
11665 << " New = " << *I;
11666#endif
11667
11668 // If the instruction was modified, it's possible that it is now dead.
11669 // if so, remove it.
11670 if (isInstructionTriviallyDead(I)) {
11671 // Make sure we process all operands now that we are reducing their
11672 // use counts.
11673 AddUsesToWorkList(*I);
11674
11675 // Instructions may end up in the worklist more than once. Erase all
11676 // occurrences of this instruction.
11677 RemoveFromWorkList(I);
11678 I->eraseFromParent();
11679 } else {
11680 AddToWorkList(I);
11681 AddUsersToWorkList(*I);
11682 }
11683 }
11684 Changed = true;
11685 }
11686 }
11687
11688 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011689
11690 // Do an explicit clear, this shrinks the map if needed.
11691 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011692 return Changed;
11693}
11694
11695
11696bool InstCombiner::runOnFunction(Function &F) {
11697 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11698
11699 bool EverMadeChange = false;
11700
11701 // Iterate while there is work to do.
11702 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011703 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011704 EverMadeChange = true;
11705 return EverMadeChange;
11706}
11707
11708FunctionPass *llvm::createInstructionCombiningPass() {
11709 return new InstCombiner();
11710}
11711
Chris Lattner6297fc72008-08-11 22:06:05 +000011712